Jace
Jace

Reputation: 9

PHP fopen problems

How do I create a file in php? I have tried using...

$num = file_get_contents('qnum/qnum.txt');
$newFile = 'question'.$num.'.txt';
$newNum = $num++;
$openingQNUM = fopen('qnum/qnum.txt','w');
echo fwrite($openingQNUM,$newNum);
fclose($openingQNUM);

and I know I have called the functions right cause it is giving me the following error messages:

Warning: fopen(qnum/qnum.txt) [function.fopen]: failed to open stream: Permission denied in D:\Hosting\11017597\html\Question Site\ask.php on line 16

Warning: fwrite() expects parameter 1 to be resource, boolean given in D:\Hosting\11017597\html\Question Site\ask.php on line 17

Warning: fclose() expects parameter 1 to be resource, boolean given in D:\Hosting\11017597\html\Question Site\ask.php on line 18

Can someone tell me what I am doing wrong?

Upvotes: 0

Views: 942

Answers (2)

Sven
Sven

Reputation: 70863

PHP is complaining about not being able to create a new file because the filesystem denies access for writing. You should check if the process running PHP is allowed to write to the directory.

And in other news: ´file_put_contents()does all of the above and is the counterpart offile_get_contents()` - consider using it. It won't work right now, though, because of the file permission issue.

And after that: Welcome to the world of concurrent accesses! You are not using any form of locking, which makes your code a victim of race conditions. Two requests might read the same file (counter = 5), both increment the counter (= 6) and write back. Result: Counter is 6, but 7 would have been correct.

Upvotes: 1

danielperaza
danielperaza

Reputation: 412

It seems you don't have read permissions on that file. Check if is_readable('qnum/qnum.txt') returns TRUE.

Upvotes: 0

Related Questions