Upload file, verify file, rename file, get data and delete file from folder php script – example for CSV/Excel file

IT Tutorials

Today we are showing you how to create a php script for uploading, verify right file type before uploading, rename the file, get data from csv/excel file and then delete it .

At first you need to create the html form, bellow is a basic one :

<form method=’POST’ enctype=’multipart/form-data’>
<input type =’file’ name=’file’ id=’file’>
<input type=’submit’ value=’submit file’/>

Then you need to check is post is triggered for file : if(isset($_FILES[‘file’])){ .

Define the uploading folder : $targetfolder = “uploads/test.csv”; at the end the file will be deleted .

Then define the file type, in this case CSV/Excel :

$file_type=$_FILES[‘file’][‘type’];

if ($file_type==”application/vnd.ms-excel” || $file_type==”text/csv” || $file_type==”text/plain”) {

Move file and rename it to upload folder : if(move_uploaded_file($_FILES[‘file’][‘tmp_name’], $targetfolder)){

Get data from csv file :

if (($handle = fopen(‘uploads/test.csv’, ‘r’)) !== FALSE) {
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE) {

for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . “<br />\n”;
}
}
fclose($handle);
}

Then delete the file from uploaded folder unlink(‘uploads/test.csv’); .

At the end add some elses if the file is different than csv .

Bellow you can find the hole php script :

if(isset($_FILES[‘file’])){
$targetfolder = “uploads/test.csv”;
$file_type=$_FILES[‘file’][‘type’];
if ($file_type==”application/vnd.ms-excel” || $file_type==”text/csv” || $file_type==”text/plain”) {
if(move_uploaded_file($_FILES[‘file’][‘tmp_name’], $targetfolder))
{
if (($handle = fopen(‘uploads/test.csv’, ‘r’)) !== FALSE) {
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE) {
for ($i = 0; $i < count($data); $i++) {
echo $data[$i] . “<br />\n”;
}
}
fclose($handle);
}
unlink(‘uploads/test.csv’);
}
else {
echo “Uploading file error”;
}
}
else {
echo “Only CSV files are allowed.<br>”;
}
}

Good luck !

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet - Rate this article !)
Loading...


Lost Password