Jump to content

PHP Script to Upload a .csv File Then Insert into MYSQL


Recommended Posts

  • Administrators

This following will allow you to upload a .csv file via a web form then insert that data into a MYSQL database.


I had a request for it this morning and so now that I have it created I figured I would share. Let me know if you see anything that would be an improvement.


Step 1 - Create Web Form

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />


Step 2 - Create the Uploader.php File

// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
<br><a href="./import.php">Click To Import</a>


Step 3 - Create the Import.php File that will insert the data into MYSQL

/* Edit the entries below to reflect the appropriate values
$databasehost = "localhost";
$databasename = "";
$databasetable = "";
$databaseusername ="";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "n";
$csvfile = "uploads/nameof.csv";
/* Would you like to add an ampty field at the beginning of these records?
/* This is useful if you have a table with the first field being an auto_increment integer
/* and the csv file does not have such as empty field before the records.
/* Set 1 for yes and 0 for no. ATTENTION: don't set to 1 if you are not sure.
/* This can dump data in the wrong fields if this extra field does not exist in the table
$addauto = 0;
/* Would you like to save the mysql queries in a file? If yes set $save to 1.
/* Permission on the file should be set to 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
$save = 0;
$outputfile = "output.sql";

if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.n";
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.n";
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.n";
$csvcontent = fread($file,$size);
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$line = trim($line," t");

$line = str_replace("r","",$line);

This line escapes the special character. remove it if entries are already escaped in the csv file
$line = str_replace("'","'",$line);

$linearray = explode($fieldseparator,$line);

$linemysql = implode("','",$linearray);

 $query = "insert into $databasetable values('','$linemysql');";
 $query = "insert into $databasetable values('$linemysql');";

$queries .= $query . "n";
if($save) {

if(!is_writable($outputfile)) {
 echo "File is not writable, check permissions.n";

else {
 $file2 = fopen($outputfile,"w");

 if(!$file2) {
  echo "Error writing to the output file.n";
 else {

echo "Found a total of $lines records in this csv file.n";



For this to work correctly all you need to do is put all 3 of these .php files in the same directory and create another directory within called "uploads".

Link to comment
Share on other sites

Is there any error checking in the script to see if it really is a csv file and not a trojan/virus or similar that is being uploaded? For privet back-end use i doesn't really matter but if you go live to the public it is fairly easy to exploit. Otherwise a nice useful script, thanks!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...