Save file with file_put_contents in folder

Save file with file_put_contents in folder

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

Stefan Bogdanescu

Founder & Senior Architect

Understanding Path Resolution in file_put_contents

When working with PHP's file_put_contents, it is easy to assume that providing a directory name in the path string will automatically create that directory if it doesn't exist. This intuition often leads directly into a common runtime error: failed to open stream: No such file or directory.

Consider a scenario where saving a file to the current working directory works perfectly, but attempting to save it to /subfolder/image.jpg fails immediately. The underlying code responsible for this behavior is straightforward:

// This works fine
file_put_contents('image.jpg', file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

// This fails with "No such file or directory"
file_put_contents('/subfolder/image.jpg', file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

The error occurs because PHP does not automatically create directories. When you provide a path like /subfolder/image.jpg, PHP treats the entire string as an absolute path rooted at the filesystem root (on Linux/Unix) or the Windows drive root. It attempts to write directly to C:\subfolder\image.jpg or /subfolder/image.jpg. Since the operating system does not create intermediate directories for you, the function cannot find the parent folder subfolder, resulting in the failure.

Unlike some high-level frameworks that might offer helper methods to ensure directory structures exist before saving, the core PHP functions operate strictly on what exists on the disk. If the directory is missing, the stream opens fail. This distinction is crucial when managing assets, logs, or uploaded files where you frequently need to organize them into subdirectories.

To resolve this, you must explicitly create the directory structure before attempting to write the file. The standard approach utilizes mkdir. However, you must ensure you do not try to create a directory that already exists, as this will throw a warning. Passing the boolean flag true to mkdir handles this gracefully by returning false rather than throwing an error if the directory is present.

Here is the robust pattern for handling this logic:

$targetPath = '/subfolder/image.jpg';
$relativeDirectory = dirname($targetPath);

// Ensure the directory exists before writing
if (!is_dir($relativeDirectory)) {
    mkdir($relativeDirectory, 0755, true);
}

// Now safely write the file
file_put_contents($targetPath, file_get_contents('http://static.adzerk.net/Advertisers/12f0cc69cd9742faa9c8ee0f7b0d210e.jpg'));

Using dirname() is essential here. It extracts the directory portion from your full path (/subfolder) without including the filename. If you simply used mkdir('/subfolder', ...) and later tried to write to /subfolder/image.jpg, you would be creating a new folder every time, potentially overwriting or confusing the file system state if multiple scripts run sequentially. By isolating the directory creation logic, you ensure that the file is only written once per execution cycle, provided the path hasn't changed.

It is also important to consider permissions. The 0755 permission set used in the example allows the owner to read and execute (enter) the directory, while group and others can only read and execute. If your application runs as a specific user but needs to write to a shared location, you may need to adjust these octal permissions or rely on the web server's default permissions via .htaccess or php.ini settings.

Furthermore, always verify that the target path is writable by the current process. Even if the directory exists, a restrictive filesystem permission or SELinux policy could block the write operation. Checking is_writable() or catching exceptions from file_put_contents in production environments can help prevent silent failures where a file appears to be missing but was simply unable to be written due to access restrictions.

For developers working within the Laravel ecosystem, you might prefer using the filesystem facade (Storage::disk()->put()) which handles path normalization and directory creation automatically under the hood. However, understanding the underlying mechanics of file_put_contents remains vital for debugging issues when custom storage drivers or raw file operations are required.

Our network