Create CSV file using PHP and save it into directory

Create CSV file using PHP and save it into directory

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

Stefan Bogdanescu

Founder & Senior Architect

Why Your CSV File is Downloading Instead of Saving

The core issue in your script isn't a bug in the logic; it's how the web server interprets the response. You are explicitly telling the browser to treat the output as an Excel file and force a download with header("content-disposition: attachment"). This behavior is correct if you want the user to click a link and get a file, but it breaks when you intend for the script to run silently in the background or be triggered by a cron job.

To save a file directly into a directory without triggering a download, you must stop sending headers that indicate a file transfer. Instead, you need to output the raw data to the server's standard output stream and then instruct PHP to terminate execution immediately. When done correctly, the web server will treat this response as plain text or binary data and write it directly to the filesystem path you specify.

Redirecting Output to the Filesystem

The most straightforward approach is to use file_put_contents() instead of echoing the content. This function writes data directly to a file on disk. However, simply writing the string isn't enough; you must disable PHP's output buffering and ensure no headers are sent that might interfere with the response type.

Here is a revised implementation strategy:

  1. Remove Download Headers: Delete header("Content-Type: application/vnd.ms-excel") and header("content-disposition: attachment"). If these remain, the client (or the web server acting as a proxy) may still attempt to render or download the content.
  2. Construct the Content: Build your CSV string in memory exactly as you did, ensuring proper newline characters (\n) are used.
  3. Write to Disk: Use file_put_contents() with an absolute path.
<?php
// Configuration
$MYSQL_HOST = "localhost";
$MYSQL_USERNAME = "root";
$MYSQL_PASSWORD = "";
$MYSQL_DATABASE = "paesana";
$MYSQL_TABLE = "ds_orders";
$TARGET_DIR = "/path/to/your/storage/directory/"; // Must be writable by web server
$filename = "ePay_" . date("Y-m-d_H-i") . ".csv";

// Connect and query (Note: mysql_* functions are deprecated)
$conn = mysql_connect($MYSQL_HOST, $MYSQL_USERNAME, $MYSQL_PASSWORD);
if (!$conn) { die("Connection failed: " . mysql_error()); }
mysql_select_db($MYSQL_DATABASE);

$today = "2008-12-21";
$sql = "SELECT * FROM $MYSQL_TABLE where cDate='$today'";
$result = mysql_query($sql);

if ($result && mysql_num_rows($result) > 0) {
    // Initialize CSV header
    $fileContent = "Beneficiary Name,Beneficiary Account No,Beneficiary Bank Code,Transaction Amount,Narration\n";

    while ($data = mysql_fetch_array($result)) {
        // Concatenate row data
        $row = $data['customer_id'] . "," . 
                $data['oNum'] . "," . 
                $today . "," . 
                trim($data['cShipService'] . " " . $data['cShipMethod']) . "," . 
                $data['cEmail'] . "," . 
                $data['ccType'] . "," . 
                $data['cShipInstruct'] . "," . 
                trim($data['cShipFname'] . " " . $data['cShipLname']);
        
        $fileContent .= $row . "\n";
    }

    // Define the full absolute path
    $absolutePath = $TARGET_DIR . $filename;

    // Write directly to file without sending headers
    if (file_put_contents($absolutePath, $fileContent) !== false) {
        echo "File saved successfully.";
    } else {
        echo "Failed to write to file. Check permissions.";
    }
}

// Close connection
mysql_close($conn);
?>

Critical Technical Considerations

Deprecated Functions and Modern Standards

Your source code relies on the mysql_* extension, which has been deprecated since PHP 5.5 and removed in PHP 7.0+. If you are running a modern PHP version, this script will fail immediately. You must migrate to either PDO or MySQLi. Furthermore, constructing SQL queries with variables like $MYSQL_TABLE without sanitization exposes your application to SQL injection attacks. Always use prepared statements.

File Permissions and Writable Directories

The most common reason a file write operation fails silently in a web environment is permission issues. The user running the web server (often www-data, apache, or nobody) must have write permissions for the target directory. If you are testing locally, ensure the folder exists and is writable by your current user. You can verify this with:

ls -ld /path/to/your/storage/directory

If the permissions are incorrect, the script will throw a "failed to write" error or return false from file_put_contents().

Handling Output in CLI vs. Web Context

The original question implies a desire for background processing ("save onto a directory"). If you intend to run this script via a cron job (command line), the output of echo is irrelevant because there is no browser to receive it. In that scenario, relying solely on file_put_contents() and checking its return value is sufficient. You do not need to echo anything to confirm success; instead, log the result or send an email notification if the write fails.

If you are running this from a web browser and want it to save automatically without a download prompt, you must also ensure that no whitespace exists before any output in the PHP file. Even a single space before <?php or a BOM character can cause headers to be sent prematurely, leading to conflicts when mixing logic with file operations.

Security Note on Data Exposure

Your CSV includes sensitive fields like email addresses and potentially account numbers. Ensure that the directory where these files are stored is not publicly accessible via web server configuration (e.g., using .htaccess or web.config to deny access) unless you intend for humans to manually download them later. Automated scripts should never expose raw database dumps containing PII directly through the filesystem if they are reachable via HTTP URLs.

Our network