sam
sam

Reputation: 698

Not able to write php file in php

I am able to write .txt file with the following code but unable to do so with php files(existing or newly created with the following code) on localhost.

Also it echo string length correctly without any error notice or warning

<?php
$file = fopen("test.php","w");
echo fwrite($file,"do not vote me down");
fclose($file);
?>

Thanks in advance

Upvotes: 0

Views: 854

Answers (3)

DarkKnight
DarkKnight

Reputation: 661

may be a ownership problem. try do chmod -R 775 /var/www/folder and/or chown -R domain:www-data /var/www/folder - where domain is the user of that particular virtualhost or www-data

Also to update a file instead rewrite you can use append option - adding + will help to create the file first time if it is not exists.

$file = fopen("test.php","a+");
echo fwrite($file,"do not vote me down ab");
fclose($file);

And If you want to change the ownership of the file you can use Php chown function-

chown('test.php','apache');

Too change permission of file or folder recusively use this code -

exec ("find /path/to/folder -type d -exec chmod 0750 {} +");
exec ("find /path/to/folder -type f -exec chmod 0644 {} +");

Upvotes: 3

Mobs
Mobs

Reputation: 28

Your code works. I can rewrite the content, as long as test.php has appropriate file permission.

Upvotes: 0

Saunak Surani
Saunak Surani

Reputation: 11

Maybe your file will not open so you can add die() function after fopen(), review below code :-

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Upvotes: 1

Related Questions