How to download a php file without executing it?

How to download a php file without executing it?

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

Stefan Bogdanescu

Founder & Senior Architect

How to download a php file without executing it?

In many content management systems, downloading files via HTTP is a standard feature. However, when that file has a .php extension, the server's default behavior often conflicts with your intent. If you request example.com/files/script.php, the web server (usually Apache or Nginx) sees the .php extension and routes the request to your PHP-FPM process. This causes the code inside the file to execute on the server before any data is sent back to the client.

If you are building a system where users can upload, edit, and download arbitrary files—including scripts—you must ensure that when downloading a PHP file, the content is treated as a raw binary stream rather than executable code. The core issue in your current implementation stems from using include_once($file). This function attempts to parse and execute the file on the server side. Even if you set headers like Content-Type: application/octet-stream, the execution happens before the headers are effectively processed or outputted, potentially leaking sensitive data or triggering logic errors.

The Correct Approach: Read and Stream

To download a file without executing it, you must read the file from the disk into memory (or stream it directly) and then send it to the browser using readfile(). Unlike include, which triggers the PHP interpreter on the file's contents, readfile() simply treats the file as a sequence of bytes.

Here is the corrected logic for your download handler:

<?php
$file = $_REQUEST['file_name'];

if (file_exists($file)) {
    // Ensure the path is safe and resolves correctly to prevent directory traversal
    $realPath = realpath(__DIR__ . '/' . $file);
    
    if ($realPath === false || strpos($realPath, __DIR__) !== 0) {
        http_response_code(403);
        exit('Forbidden');
    }

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    // Ensure the filename doesn't contain characters that might break headers
    $filename = basename($file); 
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($realPath));

    // CRITICAL: Use readfile instead of include or require
    if (readfile($realPath)) {
        exit;
    }
} else {
    http_response_code(404);
    echo 'File not found';
}
?>

Why include Fails for Downloads

The primary reason your original code executed the file is the semantics of include_once. When PHP encounters this directive, it parses the file as a script. If the file contains HTML output or logic intended for execution (like a database connection), it runs immediately. This violates the principle of separation between storage and execution during a download operation.

Using readfile() bypasses the parser entirely for that specific file. It reads the raw bytes from the filesystem and writes them to the standard output buffer, which is then transmitted to the client. This ensures that even if the downloaded .php file contains malicious logic or sensitive configuration details, that code never runs on your server during the download process.

Security Considerations for File Downloads

While fixing the execution issue is straightforward, handling arbitrary file downloads introduces significant security risks that require attention:

  1. Path Traversal: Your original code relied on $_REQUEST['file_name'] directly. If a user requests /../../../etc/passwd, the script might attempt to read files outside your intended directory. You must resolve the path against your base directory and verify that the resolved path starts with that base directory before reading it. The example above uses realpath() and a check against __DIR__ to mitigate this.
  2. Content-Type Precision: While application/octet-stream works for generic downloads, if you want the browser to handle the file correctly (e.g., opening it in an IDE or text editor), you might consider using text/plain; charset=utf-8 or even application/x-httpd-php depending on your specific use case. However, octet-stream is safer for preventing browsers from interpreting the content as an HTML page or executing scripts if they auto-detect based on headers.
  3. Filename Sanitization: Ensure the filename header contains only safe characters. Filesystem paths often contain slashes or other special characters that are illegal in HTTP headers. Using basename() isolates just the file name, stripping dangerous directory traversal attempts from the filename itself.

Framework Alternatives

If you are moving away from raw PHP logic to a framework like Laravel, this problem is abstracted away by the framework's built-in storage and download functionality. For instance, using Laravel's Storage facade or Response::download() methods handles these path resolutions and header settings internally, reducing the likelihood of manual errors.

However, understanding the underlying mechanism—reading raw bytes versus including code—is essential regardless of the stack you choose. Whether you are writing a custom CMS or extending an existing one, the directive is clear: never use include or require to serve file content; always use readfile.

Our network