Php create a file if not exists

shyamkarthick picture shyamkarthick · Dec 14, 2013 · Viewed 84.7k times · Source

I try to create files and write the contents dynamically. Below is my code.

$sites = realpath(dirname(__FILE__)).'/';
$newfile = $sites.$filnme_epub.".js";

if (file_exists($newfile)) {
    $fh = fopen($newfile, 'a');
    fwrite($fh, 'd');
} else {
    echo "sfaf";
    $fh = fopen($newfile, 'wb');
    fwrite($fh, 'd');
}

fclose($fh);
chmod($newfile, 0777);

// echo (is_writable($filnme_epub.".js")) ? 'writable' : 'not writable';
echo (is_readable($filnme_epub.".js")) ? 'readable' : 'not readable';
die;

However, it does not create the files.

Please share your answers and help. Thanks!

Answer

Alejandro Iván picture Alejandro Iván · Dec 14, 2013

Try using:

$fh = fopen($newfile, 'w') or die("Can't create file");

for testing if you can create a file there or not.

If you can't create the file, that's probably because the directory is not writeable by the web server user (usually "www" or similar).

Do a chmod 777 folder to the folder you want to create the file and try again.

Does it work?