To create a file in PHP if it does not exist, you can use the fopen
function with the x
mode. This function tries to create the file and open it for writing, and returns a file handle if it was successful.
Here’s an example:
$filename = 'file.txt';
$handle = fopen($filename, 'x');
if ($handle !== false) {
// The file was created and is now open for writing
fwrite($handle, 'Hello, world!');
fclose($handle);
} else {
// The file already exists or could not be created
}
Note that the x
mode is only available in PHP 5.4 and later. In older versions, you can use the fopen
function with the w
mode to open the file for writing, and then use the file_exists
function to check if the file already exists. If it does, you can use the fopen
function with the a
mode to open the file for appending instead:
$filename = 'file.txt';
if (!file_exists($filename)) {
$handle = fopen($filename, 'w');
} else {
$handle = fopen($filename, 'a');
}
if ($handle !== false) {
fwrite($handle, 'Hello, world!');
fclose($handle);
} else {
// There was an error opening the file
}