PHP File Upload & Save – Upload a CSV File in a PHP Script

How to Upload & Save a CSV File in PHP

  1. Confirm PHP.ini settings
  2. Create HTML form on the front-end
  3. Create a file input button on the front-end
  4. Create a PHP backend script to process the CSV file upload
  5. Write a PHP function to fetch the file data from the TMP folder
  6. Move the file data to the permanent storage location and save the location
  7. Add an entry into to your database and save the reference ID
  8. Respond with your file reference location and a 200 response to the user’s web browser.
Process to upload a CSV file to storage in PHP

CSV PHP Code Examples and Learning Path

Code to Upload a CSV file in PHP

We can use a PHP script with an HTML form to upload a CSV file to the server. When we upload a file, it initially uploads into a temporary directory and is then relocated to the target location by a PHP script.

Here’s the code for file upload in PHP.

<?php
 
//If form submits successfully.
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // If file uploads successfully
    if(isset($_FILES["file"]) && $_FILES["file"]["error"] == 0){
        $allowedFileTypes = array("csv" => "text/csv");
        $filename = $_FILES["file"]["name"];
        $filetype = $_FILES["file"]["type"];
        $filesize = $_FILES["file"]["size"];
   
        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Exception("Invalid file Format");
        }
   
        // Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Exception("The File size is larger than the allowed limit.");
        }
   
        // Verify The MIME type of the file.
        if(in_array($filetype, $allowedFileTypes)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            }
            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $filename);    
            }
        }
        //If not a valid MIME type
        else{
            throw new Exception("Invalid file format");
        }
    }
    //If file fails to upload
    else{
        echo "Error: " . $_FILES["file"]["error"];
    }
}
//If form fails to submit
else {
    throw new Exception("Form submission failed");
}
?>

Detail Walk-through of Uploading a CSV File using a PHP Script

We can upload any type of file using PHP. It can be a JPG, PNG, GIF, text, PDF, or CSV file. This article will explain how to upload a CSV file using PHP. 

Learn more about how to upload and save files in PHP at FuelingPHP.

This article will demonstrate a step-by-step walkthrough where it uploads a CSV file via an HTML form and processes it via PHP script. Finally, the script saves the CSV to a local uploads directory.

Step 1 | Configure the “php.ini” File Settings

To upload a file using PHP, first, we need to configure some key settings in the php.ini file. You can learn more about finding the php.ini file here.

PHP.ini | file_uploads

Open the php.ini file on your computer. Ensure the value of the file_uploads is On, as shown in the image below.

File Uploads

If the file_uploads value is off, then the uploading process will fail.

PHP.ini | upload_max_filesize

Next, we need to set the maximum file size in the php.ini file. If the maximum file size is less than the file we upload, we will get an error uploading the file. We can set desired maximum file size in the php.ini shown in the image below.

Max file size

Step 2 | Create an HTML Form

First, create an HTML form that only expects a user to upload a CSV file.

HTML Form Code Snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload Form</title>
</head>
<body>
    <form action="upload-manager.php" method="post" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="file" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Only .csv file allowed.</p>
    </form>
</body>
</html>

Output

 upload and save a CSV File in PHP
Upload a CSV file

Step 3 | Upload and Save a CSV File in PHP

Check if the Form Submits

First things first, the example needs to check if the form submits successfully, and for that, it uses IF/ELSE to ensure the script throws an error on form submission failure

//If form submits successfully.
if($_SERVER["REQUEST_METHOD"] == "POST"){
   // Rest of the logic goes here
}
//If form fails to submit
else {
    throw new Exception("Form submission failed");
}

Check if the File Uploads Successfully

The next logical step will be to check if the file has been uploaded successfully. So, the example uses another IF/ELSE to ensure that.

   // If file uploads successfully
   if(isset($_FILES["file"]) && $_FILES["file"]["error"] == 0){
     //File upload logic goes here.
   }
 
   //If file fails to upload
   else{
   echo "Error: " . $_FILES["file"]["error"];
   }

Check if the File Extension is Valid

In this step, the example adds code to retrieve file information from the $_FILES array and uses an IF statement that would catch conditions when a file has an invalid extension.

$allowedFileTypes = array("csv" => "text/csv");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
   
        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Exception("Invalid file Format");
        } 

Verify the File Size of your CSV

The next thing to check is whether the file size is within limits – 25MB in our case.

        // Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Exception("The File size is larger than the allowed   limit.");
        }

Check the File MIME Type

Next, the example checks if the file MIME type (Media type) is correct. In the $allowedFileTypes array, the values are MIME types.

 // Verify The MIME type of the file.
if(in_array($filetype, $allowedFileTypes)){
 }
//If not a valid MIME type
else{
   throw new Exception("Invalid file format");
 }

Check if File Already Exists

Finally, the example ensures if the file doesn’t exist already, and if that’s true, it uploads it to the temporary folder.

// Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            }
            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $filename);
                echo "Upload successful";
            }

Voila! Let’s put these pieces together in the next section.

Full PHP Code to Upload & Save CSV File From Start to Finish

<?php
 
//If form submits successfully.
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // If file uploads successfully
    if(isset($_FILES["file"]) && $_FILES["file"]["error"] == 0){
        $allowedFileTypes = array("csv" => "text/csv");
        $filename = $_FILES["file"]["name"];
        $filetype = $_FILES["file"]["type"];
        $filesize = $_FILES["file"]["size"];
   
        // Get file extension
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
 
        //Check if file extension is valid.
        if(!array_key_exists($extension, $allowedFileTypes)) {
           throw new Exception("Invalid file Format");
        }
   
        // Verify file size - 25MB max.
        $maxsize = 25 * 1024 * 1024;
        if($filesize > $maxsize){
            throw new Exception("The File size is larger than the allowed limit.");
        }
   
        // Verify The MIME type of the file.
        if(in_array($filetype, $allowedFileTypes)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            }
            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $filename);
                echo "Upload successful";
            }
        }
        //If not a valid MIME type
        else{
            throw new Exception("Invalid file format");
        }
    }
    //If file fails to upload
    else{
        echo "Error: " . $_FILES["file"]["error"];
    }
}
//If form fails to submit
else {
    throw new Exception("Form submission failed");
}
?>

Output Results of our PHP CSV File Upload Script

 upload and save a CSV File in PHP
Upload a CSV File

Step 4 (Optional) | Read CSV File to Populate HTML Form

This optional step will read the uploaded CSV file and populate the data in an HTML table.

Read a CSV File as an Associative Array in PHP

Here’s an example that reads a CSV file and converts it to an associative array in PHP. Learn more about it here.

<?php
    //Map lines of the string returned by file function to $rows array.
    $rows   = array_map('str_getcsv', file('uploads/employee_record.csv'));
    //Get the first row that is the HEADER row.
    $header_row = array_shift($rows);
    //This array holds the final response.
    $employee_csv    = array();
    foreach($rows as $row) {
        if(!empty($row)){
            $employee_csv[] = array_combine($header_row, $row);
        }
    }
?>

HTML Table

The following example uses an embedded PHP script to loop through the associative array and populates the HTML table with the employees’ data.

<html>
    <head>
        <title>Email Sent</title>
    </head>
    <body>
        <table>
            <tr>
                <th>Name</th>
                <th>Age</th>
            </tr>
            <?php
                foreach($employee_csv as $v) {
                    echo '<tr><td>'.$v['Name'].'</td><td>'.$v['Age'].'</td><td>'.$v['Salary'].'</td></tr>';
                }
            ?>
        </table>
    </body>
</html>

Output

upload and save a CSV File in PHP
HTML table

Voila! That’s it. Let’s move to some frequently asked questions.

Which PHP Function is used to Upload and Save Files?

PHP  move_uploaded_file(string $from, string $to): bool function uploads a file using PHP. This function moves the uploaded file to a destination. The following example will use this function to upload & save the CSV file locally.

How to Save the CSV file as UTF-8 in Microsoft Excel?

UTF-8 is a broader set of characters than ASCII and supports languages other than English. So, we recommend using UTF-8 if your CSV file has special symbols and characters. Here’s a tutorial that can help.

How to Store Uploaded CSV files in a Database using PHP

The database adds a layer of complexity to the example that we have seen. Generally, if you’re using a SQL database, you need to make insert queries to pass data to the database. Learn more about Database upload via PHP.

Where is the Temporary Directory & Tmp_name in PHP

The information inside the phpinfo.php page describes the temporary directory when a file is uploaded first as upload_temp_dir. The upload_max_filesize specifies the maximum allowed size afor a file. We set these into a PHP configuration file called php.ini.

We must enable file writing permissions for the file’s temporary and final destinations. If either is disabled, then the upload process will fail.

Wrap Up on Uploading & Saving CSV Files in PHP

This article demonstrates how to upload and save a CSV file in PHP. The article guides setting file uploads in php.ini, followed by an extensive tutorial on uploading and saving a CSV file to a server.

I hope you’ve enjoyed the article. Stay tuned for more at FuelingPHP

PHP Classes and Functions Mentioned

array_key_exists – (PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8) Checks if a key or index exists in the array.

move_uploaded_file – (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) Moves an uploaded file to a target location.

isset – (PHP 4, PHP 5, PHP 7, PHP 8) Checks if a variable in null or empty 

in_array – (PHP 4, PHP 5, PHP 7, PHP 8) Checks if a value exists in array.

pathinfo – (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) Returns a file’s path information

Get deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems