Php create a file if not exists

Viewed 114213

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!

4 Answers

Use the function is_file to check if the file exists or not.

If the file doesn't exist, this sample will create a new file and add some contents:

<?php

$file = 'test.txt';

if(!is_file($file)){
    $contents = 'This is a test!';           // Some simple example content.
    file_put_contents($file, $contents);     // Save our content to the file.
}

?>

To be sure that a file exists before doing anything with it you can just touch it:

if (!file_exists('somefile.txt')) {
    touch('somefile.txt');
}

This will just create an empty file having the current time as creation time. The advantage over fopen is that you don't have to close the file.

You can also set the creation time, if you want. The following code will create a file with a creation time of yesterday:

if (!file_exists('somefile.txt')) {
    touch('somefile.txt', strtotime('-1 days'));
}

However: You should care about the fact that a file's modification time will be changed if you use touch for files which already exists.

If you want to run this command using shell, try this:

shell_exec("touch filename.filetype");

If you want to put contents in this file using shell, try this (if you do this, you do not need to touch it before this):

shell_exec("echo filecontent > filename.filetype");
Related