How to import csv file in PHP?

How to import csv file in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

How to Import CSV Files in PHP

Importing a CSV file into a database is a common task, but the implementation varies wildly depending on your requirements. If you are working with PHP 5.3.5 as mentioned in the source material, you must rely on built-in functions like fgetcsv() because modern extensions might not be available or supported by that specific version.

The core challenge is balancing memory usage against processing speed. A naive approach reads the entire file into a single string and then parses it. This fails immediately if your CSV exceeds the memory_limit set in your php.ini. For large datasets, you need to process the file line-by-line or chunk-by-chunk to ensure your server doesn't crash.

Parsing Logic with fgetcsv()

The most straightforward method for older PHP environments involves opening a file handle and reading it row by row. This pattern ensures that memory consumption remains constant regardless of file size, provided you do not store the entire content in an array simultaneously.

Here is a basic implementation using fgetcsv():

<?php
$file = 'data.csv';
$handle = fopen($file, 'r');

if (!$handle) {
    die('Failed to open file: ' . $errno);
}

while (($data = fgetcsv($handle, 0, ',')) !== false) {
    // $data is now an array representing one row of the CSV
    // You can process each field here or insert into your database
    
    // Example: Insert into MySQL
    // $sql = "INSERT INTO users (name, email) VALUES ('" . $data[0] . "', '" . $data[1] . "')";
    // mysql_query($sql); 
}

fclose($handle);
?>

In this example, fgetcsv() automatically parses the row into an array based on the delimiter you specify (in this case, a comma). The function returns false when it reaches the end of the file or encounters a parsing error. This loop structure is essential for streaming large files without exhausting server resources.

Handling Headers and Data Separation

A frequent mistake beginners make is inserting header rows into the database. Most CSV exports contain a first row with column names, but your database table likely expects only data values. You must skip the first iteration of your loop to handle this cleanly.

You can achieve this by wrapping the parsing logic inside an index check or by explicitly reading and discarding the first line before starting the main loop. Additionally, CSV files often contain quoted fields that include commas within the data itself (e.g., "Smith, John"). The fgetcsv() function handles this automatically if configured correctly, but you must ensure your delimiter and enclosure settings match the file format exactly to avoid splitting fields incorrectly.

Security Considerations and Escaping

When moving from raw CSV parsing to database insertion, security becomes a critical concern. If you are using the older mysql_* functions mentioned in conjunction with PHP 5.3.5, you are dealing with legacy code that is deprecated and vulnerable to SQL injection. Even if you manage to parse the file correctly, directly interpolating user input from the CSV into a query string is dangerous.

For production environments, you should migrate away from mysql_* functions entirely. The recommended approach in modern PHP (5.5+) is to use PDO or MySQLi with prepared statements. Prepared statements separate the SQL logic from the data, ensuring that special characters in the CSV—such as quotes, semicolons, or single dashes—are treated as literal data rather than executable code.

If you must stick to the older environment due to constraints like PHP 5.3.5, at minimum, you should sanitize every string value before inserting it into the database. Functions like mysql_real_escape_string() were designed for this purpose in legacy setups, though they are no longer recommended for new development.

Alternative Libraries and Frameworks

If your project eventually evolves to use a framework like Laravel, importing CSV files becomes significantly easier with dedicated packages. While the raw fgetcsv() approach gives you full control and minimal dependencies, frameworks often provide higher-level abstractions that handle encoding issues, header detection, and bulk insertion more gracefully.

For instance, if you are starting a new project today, utilizing a library like laravel-excel or similar packages can abstract away the complexity of row iteration and database mapping. However, for a standalone PHP script running on WAMP with older versions, sticking to standard built-in functions is the most reliable path forward without introducing unnecessary dependencies.

When building robust data importers, always validate the file structure before processing. Check if the number of columns matches your expected schema across all rows. A single malformed line can cause a loop to break or insert corrupted data. Implementing error logging during the import process allows you to track which specific lines failed and why, making debugging much easier than relying solely on generic error messages.

Our network