File handling and directories 
Author Message
 File handling and directories

I can't for the life of me get this working. What I want to do is create a
file on the filesystem at a directory. Part of the path might exist, part
might not. I want the file and necessary folders to be created.

$textfile is in the form /path/to/dir/file.txt (or sometimes
C:\path\to\dir\file.txt)
$message is just a string.

Example input: /path/to/dir/file.txt
    Output: creates the folder /path/to/dir and then puts file.txt in it
(with the contents from $message).

The problem:  "Warning: Supplied argument is not a valid File-Handle
resource "

Note: code shown is messy because I tried dozens of "fixes" and didn't clean
them out properly. Sorry.

function write_file($textfile, $message, $OutputMessage="Normal") {
 $textfile = str_replace("C:", "", $textfile); //win
 $textfile = str_replace("\\", "/", $textfile); //win
 //Get the length of the directory
 $DirectoryNameLength = strlen($textfile) - 19;
 //set the directory to be equal to everything up to the start of the
filename
 $directory = substr($textfile, 0, $DirectoryNameLength);

 //check to see if the directory has been created
 if (!file_exists($directory)) {

 }

 //create file

 //Check to see if file has been created
 if (!($fp)) {
  //If the file hasn't been created, warn the user and exit

 }

 //Put content into file
 fputs($fp, "$message \n");

 if ($OutputMessage == "Normal"){
  //Echo that the file has been created
  echo ("<p>File Generated: $textfile </p>");
 }

 // close the textfile
 fclose($fp);

Quote:
}



Sun, 31 Jul 2005 07:34:01 GMT  
 File handling and directories


Quote:
> I can't for the life of me get this working. What I want to do is create a
> file on the filesystem at a directory. Part of the path might exist, part
> might not. I want the file and necessary folders to be created.

> $textfile is in the form /path/to/dir/file.txt (or sometimes
> C:\path\to\dir\file.txt)
> $message is just a string.

> Example input: /path/to/dir/file.txt
>     Output: creates the folder /path/to/dir and then puts file.txt in it
> (with the contents from $message).

> The problem:  "Warning: Supplied argument is not a valid File-Handle
> resource "

> Note: code shown is messy because I tried dozens of "fixes" and didn't
clean
> them out properly. Sorry.

> function write_file($textfile, $message, $OutputMessage="Normal") {
>  $textfile = str_replace("C:", "", $textfile); //win
>  $textfile = str_replace("\\", "/", $textfile); //win
>  //Get the length of the directory
>  $DirectoryNameLength = strlen($textfile) - 19;
>  //set the directory to be equal to everything up to the start of the
> filename
>  $directory = substr($textfile, 0, $DirectoryNameLength);

>  //check to see if the directory has been created
>  if (!file_exists($directory)) {

>  }

>  //create file

>  //Check to see if file has been created
>  if (!($fp)) {
>   //If the file hasn't been created, warn the user and exit

>  }

>  //Put content into file
>  fputs($fp, "$message \n");

>  if ($OutputMessage == "Normal"){
>   //Echo that the file has been created
>   echo ("<p>File Generated: $textfile </p>");
>  }

>  // close the textfile
>  fclose($fp);
> }

- First... you convert the directory path to a legal directory path - You
could use pathinfo() thus
$filePaths=pathinfo("$textfile");
$directory=$filePaths["dirname"];

- Second, you check if the directory exists - if it doesn't you ask for it
to be created... but the mkdir does not create every branch of the
directory, thus mkdir("/path/to/another/directory"); will not create
"to/another/directory" if "/path" does not exist... so you could use a for
loop to make each branch of the subdirectories, roughly speaking (untested
code) follows

if(!is_dir($directory))
{
    // The directory does not exist
    $dirPaths=explode("/", $directory);
    foreach($dirPaths as $element=>$dirName)
    {
        // Make each part of the directory as needed
        $dir="$dir/$dirName";
        if(!is_dir($dir))
        {
            print("<BR>Making $dir");
            if(!mkdir("$dir", "0777"))
            {
                die("<BR>Could not make $dir");
            }
        }
    }

Quote:
}

- lastly - your fopen asks to fopen $textfile - I would suggest you print
the value of $textfile and make sure its legal for your environment - it
looks like a windoze one.


they do?



Sun, 31 Jul 2005 08:20:56 GMT  
 File handling and directories

Quote:

> $textfile is in the form /path/to/dir/file.txt (or sometimes
> C:\path\to\dir\file.txt)
> $message is just a string.

> Example input: /path/to/dir/file.txt
>    Output: creates the folder /path/to/dir and then puts file.txt in it
> (with the contents from $message).

> The problem:  "Warning: Supplied argument is not a valid File-Handle
> resource "

> Note: code shown is messy because I tried dozens of "fixes" and didn't clean
> them out properly. Sorry.

assume: $textfile='/path/to/dir/file.txt';

Quote:
> function write_file($textfile, $message, $OutputMessage="Normal") {
> $textfile = str_replace("C:", "", $textfile); //win
> $textfile = str_replace("\\", "/", $textfile); //win
> //Get the length of the directory
> $DirectoryNameLength = strlen($textfile) - 19;

How do you know this (19)?

Quote:
> //set the directory to be equal to everything up to the start of the
> filename
> $directory = substr($textfile, 0, $DirectoryNameLength);

$directory contains '/p' at this moment.

Quote:
> //check to see if the directory has been created
> if (!file_exists($directory)) {

> }

Most likely will fail on a permission denied.

Quote:
> //create file

> //Check to see if file has been created
> if (!($fp)) {
>  //If the file hasn't been created, warn the user and exit

You didn't check $dp.

The solution is pretty simple (IMHO): take a look at dirname and
basename. You can use them recursevly to get the path to the file split
in all it's compentents. BTW code uses an global variable (which might
be considered a bit icky:) and only works for unixstyle paths.

<?php
/*put the path in reverse order in an aray*/
function getPath($str, $arr=array())
{
   if(strcmp(dirname($str),$str)!==0)
   {
      $arr[]=basename($str);
      getPath(dirname($str),$arr);
   }
   else
   {
      //we arived at the root. Save the paths.
      $GLOBALS['path']=$arr;
   }

Quote:
}

function mkhier($arr)
{
   $err=false;

   //walk thru the array in reverse order
   for($i=count($arr),$base='';$i>=0;$i--)
   {
      $base.="/{$arr[$i]}";

      if(file_exists($base) && is_dir($base))
      {
         continue;
      }
      else
      {
         //path doens't exist, try to reacte missing dir.
         if(mkdir($base)===false)
         {
            //mkdir failed, bailout.
            $err=true;
            break;
         }
      }
   }

   if(!$err)
   {
      $err=$base;
   }

   return $err;

Quote:
}

$str='/tmp/bla/foo/bar/file.txt';
$filename=basename($str);

getPath(dirname($str));

if(is_array($GLOBALS['path']) && $base=mkhier($GLOBALS['path']))
{
   echo "touching $base/$filename\n";
   touch("$base/$filename");
   //insert your file writing code here.

Quote:
}

?>

--

  Daniel Tryba



Sun, 31 Jul 2005 08:46:44 GMT  
 File handling and directories


Quote:
> I can't for the life of me get this working. What I want to do is create a
> file on the filesystem at a directory. Part of the path might exist, part
> might not. I want the file and necessary folders to be created.

> $textfile is in the form /path/to/dir/file.txt (or sometimes
> C:\path\to\dir\file.txt)
> $message is just a string.

> Example input: /path/to/dir/file.txt
>     Output: creates the folder /path/to/dir and then puts file.txt in it
> (with the contents from $message).

> The problem:  "Warning: Supplied argument is not a valid File-Handle
> resource "

> Note: code shown is messy because I tried dozens of "fixes" and didn't
clean
> them out properly. Sorry.

> function write_file($textfile, $message, $OutputMessage="Normal") {
>  $textfile = str_replace("C:", "", $textfile); //win
>  $textfile = str_replace("\\", "/", $textfile); //win
>  //Get the length of the directory
>  $DirectoryNameLength = strlen($textfile) - 19;
>  //set the directory to be equal to everything up to the start of the
> filename
>  $directory = substr($textfile, 0, $DirectoryNameLength);

>  //check to see if the directory has been created
>  if (!file_exists($directory)) {

>  }

>  //create file

>  //Check to see if file has been created
>  if (!($fp)) {
>   //If the file hasn't been created, warn the user and exit

>  }

>  //Put content into file
>  fputs($fp, "$message \n");

>  if ($OutputMessage == "Normal"){
>   //Echo that the file has been created
>   echo ("<p>File Generated: $textfile </p>");
>  }

>  // close the textfile
>  fclose($fp);
> }

Additionally... I was just thinking...in order to ensure your script is less
platform dependant, why not create a directory using the value of
$_SERVER['DOCUMENT_ROOT'] as a guide... this is what I do and it will have
the same drive letter that your PHP/Apache is installed on, if you're using
a windoze environment...

thus... something like

$directory="{$_SERVER[DOCUMENT_ROOT]}../data";
if(!is_dir($directory))
{
    mkdir("$directory", 0777);
    if(!is_dir($directory))
    {
        die("<BR>Directory $directory could not be creaeted");
    }

Quote:
}

This would place a directory called "data" sitting right along side your
htdocs directory... and it doesn't matter which platform you're using...


Sun, 31 Jul 2005 13:10:39 GMT  
 File handling and directories


Quote:

> - First...

[SNIP]
Thanks for your help! It worked perfectly!

Quote:
>Additionally... I was just thinking...in order to ensure your script is
less
>platform dependant, why not create a directory using the value of
>$_SERVER['DOCUMENT_ROOT'] as a guide... this is what I do and it will have
>the same drive letter that your PHP/Apache is installed on, if you're using
>a windoze environment...

This already happens (the root is prepended to $textfile before it's passed
into the function). I just didn't mention it. Whoops. The script has to run
on Windoze and *nix servers so  it's a concern I'd already looked into (for
other functions).

Quote:

> they do?


expression (bad functions, missing array keys etc) can be ignored by



Mon, 01 Aug 2005 05:40:16 GMT  
 
 [ 5 post ] 

 Relevant Pages 

1. small announcement: File/Directory Handling for supported Eiffel-Compilers

2. Converting Tcl File handle to C FILE* handle ?

3. Directory of File/Directories on CD

4. copy file from one directory to another directory

5. Block handling tips (was : File handling tips )

6. How to handle more than one directory?

7. Directory handling

8. Script to handle automatic backup of directories

9. bug in STV/PM 1.2 (HPFS directory handling)

10. file management: relinking icons to files in my directory

11. Making file path control only select directory paths not file names

12. Is there a way to hide files/directories and detect file access

 

 
Powered by phpBB® Forum Software