How to upload a CSV file to php

Updated March 23, 2017

The PHP scripting language allows you to execute functions on a web server. One of the things that you can do with PHP is to upload files to the server. CSV, or comma-separated values, is a file that holds several rows of data. It can be imported or exported into a database and usually holds the data that corresponds with the PHP coding. To upload CSV files with PHP, create a form that will be used as an interface to search and select the files for upload. Specify in the PHP coding that only CSV files are allowed.

Start a new web page in a program like Notepad (text-editing) or Dreamweaver (web-authoring). For web-authoring programs, switch to "HTML" or "code" view to input the code needed to complete this task.

Type in the code to create the user interface for uploading the CSV files. A HTML form is sufficient.


Choose a CSV file to upload:


Do not type in the quotation marks that starts and ends the line of code; you will receive an error message if you do. This is a simple form with two fields; one to browse for the CSV file that you want to upload and a "Submit" button to start the PHP code within the same document that will handle the uploading of the file.

Type in the coding that checks to make sure that the file is in the acceptable file type, which is a CSV file type.


$allowed Extension = array("csv");

foreach ($_FILES as $file) {

} "

This code checks to see if the file that the user is trying to upload is a CSV file. If it is not, the user will see an error message.

Type in the PHP code that continues handling the CSV file once it has been certified as a valid file type.

"$target_path = "CSV_Files/";

$target_path = $target_path . basename( $_FILES['upload_file']['name']);

if(move_uploaded_file($_FILES['upload_file']['tmp_name'], $target_path)) {

} else{




The code starts off setting the folder on the server that the CSV files will be kept. Change the "CSV_Files" to the name of the folder on your server that you want to save the uploaded CSV files to.

Save the document with a .php file extension. Upload it to your web server in the same directory that holds the folder that the CSV files will be uploaded to. For instance, if the folder is found at "/CSV_Files," upload the PHP file to the root directory folder.

Cite this Article A tool to create a citation to reference this article Cite this Article

About the Author

Tiesha Whatley has been writing for over 10 years. She has been published in "Marie Claire," "Ebony" and "Modern Bride" magazines. She holds a Bachelor of Science in English from the University of Alabama at Birmingham and has been working in the wedding planning industry for over 13 years.