Php create a file if not exists

Php create a file if not exists

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

The "File Not Created" Illusion in PHP File Operations

You are running into a classic case of premature optimization masking a logical error in your flow control. Your code attempts to distinguish between creating a new file and appending to an existing one, but the logic inside your conditional branches is inverted relative to how file_exists() works in practice.

When you run this snippet, PHP likely executes without throwing a fatal error, which gives you the false impression that the script ran successfully. However, the specific branch executed depends on whether the file exists at runtime. If the file does not exist, your code enters the else block. Inside that block, you append 'd' to a non-existent file using 'a' mode (which is impossible) or worse, you might be relying on behavior that silently fails depending on directory permissions or stream wrappers. More critically, if you are looking at the output and seeing nothing new, it is highly probable that the file_exists() check returned true because the file was created by a previous run of the script, or your environment is returning unexpected results regarding path resolution.

Let's dissect the specific mechanics causing this failure. The line $sites = realpath(dirname(__FILE__)).'/'; resolves the script's location to an absolute path. This is generally safe and preferred over using dirname(__FILE__) directly for writing files, as it prevents issues when your application is symlinked or accessed via different URLs. However, appending a trailing slash '/' creates a directory separator at the end of $sites. When you concatenate $newfile = $sites.$filnme_epub.".js";, you are constructing a valid path string.

The core issue lies in how file_exists() interacts with your conditional logic. If the file does not exist, you enter the else block. You call fopen($newfile, 'wb'). This should create the file. However, if you are seeing no output or the file remains missing, consider two immediate possibilities:

  1. Directory Permissions: The directory containing $sites might not have write permissions for the web server user (e.g., www-data or apache). Even if you set chmod($newfile, 0777) after opening the file, the creation step fails silently if the parent directory is read-only.
  2. Logical Flow: If the file does exist, your code opens it in append mode ('a') and writes 'd'. This is fine for appending, but often developers want to overwrite existing files or create them fresh.

A More Robust Approach

Instead of branching on existence solely to change the open mode, use a single conditional that handles both scenarios cleanly. The standard pattern in PHP for "create if missing, else append" involves checking existence first, then deciding the flag. However, a cleaner approach often involves using file_put_contents or ensuring the file handle logic is strictly separated.

If you want to ensure the file is created fresh every time, regardless of its previous state, use 'w' mode in your fopen. This truncates the file if it exists and creates it if it doesn't. If you specifically need to append only when the file is missing, your original logic was conceptually correct but execution-dependent on permissions.

Here is a refined implementation that addresses the permission trap and simplifies the flow:

$sites = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
$filename = $sites . $filnme_epub . ".js";

// Check if file exists to decide open mode
if (file_exists($filename)) {
    // File exists, append content
    $fh = fopen($filename, 'a');
} else {
    // File does not exist, create and write
    $fh = fopen($filename, 'w');
}

if ($fh) {
    fwrite($fh, 'd');
    fclose($fh);
    
    // Set permissions here immediately after creation
    chmod($filename, 0777); 
    
    echo is_readable($filename) ? "readable" : "not readable";
} else {
    echo "Failed to open file for writing. Check directory permissions.";
}

Why This Works Better

This pattern separates the decision of how to write from the execution of the write. By checking file_exists() first, you ensure that if the file is missing, 'w' is used (creating it), and if present, 'a' is used (preserving existing content). The critical failure point in your original code was likely the assumption that fopen would succeed without verifying the return value. fopen returns false on failure. Your original code did not check $fh, so if fopen failed due to permissions, it proceeded to fclose(false) and then chmod. While chmod on a non-existent file throws an error, fclose on false is valid but unnecessary.

Handling Permissions Correctly

A common pitfall in server-side PHP is setting file permissions too loosely. 0777 allows everyone read, write, and execute access. This is a significant security risk if the script writes sensitive data. On production servers, it is standard practice to use 0644 (readable by all, writable only by owner) or 0664 depending on your group ownership setup. Always set permissions immediately after creating the file but before closing the handle or returning control to the web server logic.

If you are building a larger application where file generation is part of a pipeline, consider using Laravel's filesystem manager if you are already in that ecosystem. It abstracts away fopen and permission handling, providing a unified interface for mounting local and remote disks. For simple scripts, however, the direct method shown above remains the most efficient and transparent way to handle dynamic file creation.

Remember that realpath() can return false if the path does not resolve correctly or if there are symbolic loop issues in your directory structure. Always validate the result of realpath before concatenating it into a filename to avoid creating files in unexpected locations or failing silently on relative path assumptions.

Our network