user306449
user306449

Reputation:

fopen create new file that not exists

I am trying to either create a file that doesn't exist or write to a file that already does.

within a php file I am trying this:

$file = fopen("data.txt", "a");

fwrite($file, "\n" . $name); fwrite($file, "," . $lastname);

fwrite($file, "," . $email);

fclose($file);

I am running Apache under windows Xp and have no luck that the file "data.txt" is being created. The docs say that adding the a parameter should create a file with a name mentioned in the fist parameter (data.txt). what am I doing wring here?

Thanks in advance undersound

Upvotes: 1

Views: 7509

Answers (4)

red
red

Reputation: 2040

If appending to an already existing data.txt works, but not creating a file that does not yet exist, it would most likely mean that the files permissions allow writing into it, but the folder the file resides in is not owned by Apache, and as such, it cannot create files there.

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

Let's add some tests and debug output to your code

echo 'cwd is: ', getcwd(), "<br />\n";
echo 'target should be: ', getcwd(), "/data.txt <br />\n";
echo 'file already exists: ', file_exists('data.txt') ? 'yes':'no', "<br />\n";

$file = fopen("data.txt", "a");
if ( !$file ) {
  die('fopen failed');
}
$c = fwrite($file, "\n$name,$lastname,$email");
fclose($file);
echo $c, ' bytes written';

Upvotes: 3

Ben
Ben

Reputation: 16543

Remember that the file is created in the directory where the main thread of the process is running. This meas that if the "main" program is in A/ and it includes a functions file from B/ a function in B that creates a file in "." creates it in A/ not in B/

Also, there's no need to call the fwrite function 3 times, you can do

fwrite($file, "\n" . $name . ", " . $lastname . ", " . $email);

Upvotes: 0

Konrad Neuwirth
Konrad Neuwirth

Reputation: 898

Are you looking into that directory the script also considers it's current one? Does your apache process have write permission there? Does the error log mention any failing command in this?

Upvotes: 1

Related Questions