Purpose
The purpose of this project is to demonstrate how to upload a CSV file with PHP and read the contents of the CSV file.
The HTML Form
<form method="post" action="/php-script-to-process-form-upload" enctype="multipart/form-data">
<input type="file" name="csvfile" id="csvfile"> CSV File To Upload<br />
<input type="submit" />
</form>
The PHP Script
$csv_mimetypes = array('text/csv', 'text/plain', 'application/csv', 'text/comma-separated-values', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel', 'text/anytext', 'application/octet-stream', 'application/txt');
if (in_array($_FILES['csvfile']['type'], $csv_mimetypes)) {
/* Grab the location of this PHP script and change the path to a different location where we can save the data */
$filePathRaw = dirname(__FILE__);
$filePathSegments = explode("/", $filePathRaw);
for ($x = 1; $x < (sizeof($filePathSegments) - 3); $x++) {
$filePath = $filePath . "/" . $filePathSegments[$x];
}
$filePath = $filePath . "/thecsvfiles";
/* Generate a filename for the CSV file */
$token = date("YmdHis");
/* Save the CSV data */
$rawCSV = file_get_contents($_FILES['csvfile']['tmp_name']);
$fileCSV = fopen($filePath . "/" . $token . ".txt", "w");
fwrite($fileCSV, $rawCSV);
fclose($fileCSV);
chmod($filePath . "/" . $token . ".txt", 0644);
}
Read the CSV File
$rawCSV = fopen($filePath . "/" . $token . ".txt", "r");
while(!feof($rawCSV)) {
$linearr = fgetcsv($rawCSV, 1000, ',', '"');
$column1 = trim($linearr[0]);
$column2 = $linearr[1];
$column3 = $linearr[2];
$column4 = trim($linearr[3]);
$column5 = trim($linearr[4]);
}
fclose($rawCSV);
Send the CSV to the Web Browser
/* Get the content of the CSV file */
$fCSV = $filePath . "/" . $token . ".txt";
if (file_exists($fCSV)) {
$fcnt = fopen($fCSV, "r");
$fsize = filesize($fCSV);
$csvresults = fread($fcnt, $fsize);
fclose($fcnt);
/* Send the CSV */
header("Content-Transfer-Encoding: UTF-8");
header("Cache-Control: public");
header("Pragma: no-cache");
header("Expires: 0");
header("Content-Type: text/plain");
echo $csvresults;
}