I'm trying to upload 3 files using html and PHP, in local server it is working but when I host it, this code is not working. What may be the problem?
Here is my HTML and PHP Code:
HTML CODE:
<form name="test" id="test" action="pet_up.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="5097152" />
Upload File 1:<input type='file' id='f1' name='f1'/>
Upload File 2:<input type='file' id='f2' name='f2'/>
Upload File 3:<input type='file' id='f3' name='f3'/>
<input type="submit" value="Update"/>
</form>
PHP CODE:
if(isset($_FILES['f1']['name']))
{
$image1 = $_FILES['f1']['name'];
$tmp1 = $_FILES['f1']['tmp_name'];
$pathAndName1 = "uploads/".$image1;
if(!empty($_FILES) && file_exists($tmp1) && is_uploaded_file($tmp1))
{
move_uploaded_file($tmp1,$pathAndName1);
}
else
{
$pathAndName1="";
}
echo"<script>alert(".$pathAndName1.");</script>";
$qry="update petition set f1='".$pathAndName1."'";
$result=mysql_query($qry);
}
if(isset($_FILES['f2']['name']))
{
$image2 = $_FILES['f2']['name'];
$tmp2 = $_FILES['f2']['tmp_name'];
$pathAndName2 = "uploads/".$image2;
if(!empty($_FILES) && file_exists($tmp2) && is_uploaded_file($tmp2))
{
move_uploaded_file($tmp2,$pathAndName2);
}
else
{
$pathAndName2="";
}
echo"<script>alert(".$pathAndName2.");</script>";
$qry="update petition set f2='".$pathAndName2."'";
$result=mysql_query($qry);
}
if(isset($_FILES['f3']['name']))
{
$image3 = $_FILES['f3']['name'];
$tmp3 = $_FILES['f3']['tmp_name'];
$pathAndName3 = "uploads/".$image3;
if(!empty($_FILES) && file_exists($tmp3) && is_uploaded_file($tmp3))
{
move_uploaded_file($tmp3,$pathAndName3);
}
else
{
$pathAndName3="";
}
echo"<script>alert(".$pathAndName3.");</script>";
$qry="update petition set f3='".$pathAndName3."'";
$result=mysql_query($qry);
}
by default, you can upload a file with 2Mb size, if you want bigger file to upload then change your php.ini file and set your value that you want to upload.
Please use this simplified version of your query.. This will help you debug more easily...
$count = count($_FILES);
for ($i = 1; $i <= $count; $i++)
{
if (isset($_FILES['f' . $i]['name']))
{
$image . $i= $_FILES['f' . $i]['name'];
$tmp . $i= $_FILES['f' . $i]['tmp_name'];
$pathAndName . $i= "uploads/" . $image . $i;
if (!empty($_FILES) && file_exists($tmp . $count) && is_uploaded_file($tmp . $count))
{
move_uploaded_file($tmp . $i, $pathAndName . $i);
echo 'error uploading file'.$i;
}
else
{
$pathAndName . $i= "";
}
}
if ($pathAndName . $i!= '')
{
echo"<script>alert(" . $pathAndName . $i. ");</script>";
}
$qry = mysql_query("update petition set f" . $i. "='" . $pathAndName . $i. "'");
if(!$qry)
{
echo 'error in query'.$i;
}
}
Related
The strangest thing happened to me, I was developing a simple file upload script, and it worked, but then it stopped working?
So I have troubleshooted and isolated the problem to the fact that the server is not accepting the fact that a specific folder actually exists. The basic gist of the code is shown below (please forgive the messiness of the code, it is just a rough draft at this point...):
BASIC FILE CREATION:
$date = date("y-m-d");
$category = "tech";
$url_m = $_SERVER['DOCUMENT_ROOT']. "/" . $category . "/articles/" . $date . "/images/";
if(!file_exists($url_m)){
mkdir($url_m, 0777, true);
$segment = "/" . $category . "/articles/" . $date . "/";
}
else{
for($i = 1; $i <= 100; $i++){
$url_new = $_SERVER['DOCUMENT_ROOT']. "/" . $category . "/articles/" . $date . "-" . $i . "/images/";
$segment = "/" . $category . "/articles/" . $date . "-" . $i . "/";
if(!file_exists($url_new)){
echo $segment;
$url_m = $url_new;
mkdir($url_m, 0777, true);
echo $url_m;
break;
}
else{
continue;
}
}
}
$name = $_FILES['file']['name'];
$url = "http://" . $_SERVER['SERVER_NAME'] . $segment;
$upload_url = str_replace("/images/", "", $url_m);
$pic_url = uploadFile($segment, $name, $_FILES['file']['type']);
Now the UPLOAD script
function uploadFile($dir, $name, $type){
if(isset($_POST['submit'])){
$allowed = array('gif','png','jpg','JPG','jpeg');
$filename = $name;
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if (isset ($name)) {
if (!empty($name)) {
$location ="<br>". $_SERVER['DOCUMENT_ROOT'].$dir. "images/";
echo $location. "<br>";
if(!file_exists($location)){echo "no";}
if (!is_writeable($location.$name)) {
die("Cannot write to destination file");
}
if (move_uploaded_file($tmp_name, $location.$name)){
$path = "http://" . $_SERVER['SERVER_NAME'] . $dir ."/images/". $name;
return $path;
}
else { return "WRONG";}
} else {
echo 'please choose a file';
}
}
}
else{return 0;}
}
As always, please know that I would not be asking this question if I hadn't already struggled with it for hours first and all help is very much appreciated!
EDIT:
Here is the HTML CODE for the form:
<form method="post" action="../site-resources/db-config/db-post.php" enctype= "multipart/form-data">
News Category:
<select name = "category" id = "category" required>
...
</select><br>
Subcategory:
<select name = "subcategory" required >
...
</select>
<br>
Article Title: <input type="text" name="title" placeholder="Article Title" required /><br>
Article Subtitle: <input type="text" name="subtitle" placeholder="Article Subtitle" required /><br>
Author's Name: <input type="text" name="author_name" placeholder="Author Name" required /><br>
Upload Image for Article: <input type = "file" name = "file" id = "image"><br>
Main Text:<br><textarea cols = "100" rows = "30" name = "article_body">Article Body Goes Here</textarea>
<br><br>
<h4>Security Question: Please Enter your Editor Code to post to this website</h4>
<input type = "text" name = "security_question" placeholder="Security Question" required />
<input type="submit" name = "submit" value="Post Article" />
Don't know whether this is the actual proble. So Need to see the HTML form, usually most forget to write enctype.
Add enctype="multipart/form-data" to form to enable upload of files
<form id="someform" action="" enctype="multipart/form-data">
This works! Tested
$date = date("y-m-d");
$category = "tech";
$url_m = $_SERVER['DOCUMENT_ROOT'] . $category . "/articles/" . $date . "/images/";
if(!file_exists($url_m)){
mkdir($url_m, 0777, true);
$segment = $category . "/articles/" . $date . "/";
}
else{
for($i = 1; $i <= 100; $i++){
$url_new = $_SERVER['DOCUMENT_ROOT'] . $category . "/articles/" . $date . "-" . $i . "/images/";
$segment = $category . "/articles/" . $date . "-" . $i . "/";
if(!file_exists($url_new)){
echo $segment;
$url_m = $url_new;
mkdir($url_m, 0777, true);
echo $url_m;
break;
}
else{
continue;
}
}
}
$name=isset($_FILES['file']['name'])?$_FILES['file']['name']:"";
$type=isset($_FILES['file']['type'])?$_FILES['file']['type']:"";
$url = "http://" . $_SERVER['SERVER_NAME'] . $segment;
$upload_url = str_replace("/images/", "", $url_m);
$pic_url = uploadFile($segment, $name, $type);
//Now the UPLOAD script
function uploadFile($dir, $name, $type){
if(isset($_POST['submit'])){
$allowed = array('gif','png','jpg','jpeg');
$filename = $name;
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
echo $ext;
if(!in_array($ext,$allowed) ) {
echo 'error';
}
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if (isset ($name)) {
if (!empty($name)) {
$location =$_SERVER['DOCUMENT_ROOT'].$dir. "images/";
echo "location:".$location. "<br>";
if(file_exists($location.$name))
{
echo "file exists";
if(!is_writeable($location.$name)) {
die("Cannot write to destination file. its not writable");
}
}
else
{
echo "file doesn't exist";
}
if (move_uploaded_file($tmp_name, $location.$name)){
$path = "http://" . $_SERVER['SERVER_NAME'] . $dir ."/images/". $name;
echo "file moved";
return $path;
}
else { return "WRONG";}
} else {
echo 'please choose a file';
}
}
}
else{return 0;}
}
I have a script that uploads and display a CSV file into HTML table.
My problem is that I have an error when I try to open big files.
My file is about 4.5 Mo with 80000 lines. It works fine with small files but I get
Warning: fopen(upload/test.csv): failed to open stream: No such file or directory in /var/www/cvs/PHP charts/sb-admin-v2/test.php on line 45
with big files
Here is my code
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" />
</form>
<?php
//upload
// for set memory limit & execution time
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "test.csv";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
//display
$row = 1;
if (($handle = fopen("upload/test.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
Well when I ran into this problem I resorted to a client side solution with https://github.com/knrz/CSV.js. Works very well and takes the load off my server. Only thing is I did not need the entire CSV to be uploaded to my server, once parsed only selective portions were sent using ajax.
If you are only trying to display the data in HTML table this can be a very good solution.
how can i get image path on server using "browse" button in a html form, select the file (double clicking the file returning its full path), and put the result image path into variable $img_path?
let's say the image dir in my server is /images, i'd like to get path of "foo.jpg", the full image path should be "/images/foo.jpg"
so, all i have to do is :
1. create form which contain "browse" button or something like that - that allow me to explore "images" directory at my server
2. exploring "images" dir, all files listed and clickable, locate "foo.jpg", select it, and voila, i get the image path "/images/foo.jpg"
any lil' help would be appreciated..
Thanks
#CodeCaster thanks for your respond.. but this is all i want (at least closer) :
<?php
$dir = '/images';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' .
$file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' .
'</form>';
} else {
exit('No files found.');
}
} else {
if (isset($_POST['files'])) {
foreach ($_POST['files'] as $value) {
echo $dir . $value . '<br />';
}
} else {
exit('No files selected');
}
}
?>
using "dir" you can achieve your goal.
<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
You could use dir:
echo "<ul>";
$d = dir("images");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo "<li>" . $entry . "</li>";
}
$d->close();
echo "</ul>";
It's gonna be hard for me to explain the whole situation, but I'll try...
I made a script for my image host that unZips a Zip package with images in it to a certain location, renames the files to a random file name and outputs multiple links to the images. The last part is not working properly! I am unable to output multiple links to the images - It simply outputs one link to the image (the first one) and the rest is in the uploaded folder, but not listed as a link.
Same goes with generating a thumbnail for the just renamed images. Only one thumbnail is generated for the first image, and the rest of the images if being ignored.
This is how my code looks like:
<?php
session_start();
include('includes/imgit.class.php');
$IMGit = new imgit();
/**
* #ignore
*/
if (!defined('IN_IMGIT'))
{
exit;
}
$IMGit->error_report(true);
$IMGit->disable(false);
$IMGit->ieNote(true);
if (isset($_POST['zipsent']) || $_POST['zipsent'] == true && isset($_FILES['archive']))
{
if ($_FILES['archive']['size'] <= MAX_ZIPSIZE)
{
// Main variables
$key = $IMGit->random_key(10);
$move_zip = move_uploaded_file($_FILES['archive']['tmp_name'], ZIP_PATH . $key . $_FILES['archive']['name']);
$zip = ZIP_PATH . $key . $_FILES['archive']['name'];
$extension = substr($zip, -3);
$filename = $IMGit->zipContent($zip); // array
$url = str_replace('www.', '', $IMGit->generate_site_url());
// ZIP limit is 100 images
if (sizeof($filename) <= 100)
{
// Only ZIP archives
if ($extension == 'zip')
{
if ($filename)
{
foreach($filename as $key => $value)
{
// Get extension
$image_extension = substr($value, -3);
$image_extension = (strtoupper($image_extension)) ? strtolower($image_extension) : $image_extension;
$image_extRule = $image_extension == JPG || $image_extension == JPEG || $image_extension == GIF || $image_extension == PNG ||
$image_extension == BMP || $image_extension == ICO;
if ($image_extRule)
{
// Set variables and do some processing
$unZip = $IMGit->unZip($zip, IMAGES_PATH);
$url = str_replace('www.', '', $IMGit->generate_site_url());
$image_name = $IMGit->random_key(7) . $value;
$image_name = (strpos($image_name, ' ') !== false) ? str_replace(' ', '', $image_name) : $image_name;
if (file_exists(IMAGES_PATH . $filename[$key]))
{
// Rename extracted files
$rename = rename(IMAGES_PATH . $filename[$key], IMAGES_PATH . $image_name);
if ($rename && file_exists($zip) && sizeof($image_name))
{
// Delete ZIP
unlink($zip);
// Set URL variables
$image_urls = $url . IMAGES_PATH . $image_name;
$image = IMAGES_PATH . $image_name;
// Generate a thumbnail
$IMGit->generate_thumbnail($image_urls, $image_name, THUMBNAIL_SIZE, THUMBNAIL_SIZE, true, 'file', false, false, THUMBS_PATH);
$thumb_urls = $url . THUMBS_PATH . $image_name;
$filename[] = array('direct' => $image_urls, 'thumb' => $thumb_urls);
}
}
}
}
}
}
}
}
}
else
{
header('Location: index.php');
}
include('includes/header.php');
{
if ($_FILES['archive']['size'] > MAX_ZIPSIZE) { echo '<span id="home-info">The ZIP archive is bigger than 100 MB.</span>'; }
else if ($extension != 'zip') { echo '<span id="home-info">Only ZIP archives are upload ready.</span>'; }
else if (sizeof($filename) > 100) { echo '<span id="home-info">The number of the images inside the archive was more than 100.</span>'; }
else if (!$image_extRule) { echo '<span id="home-info">The extensions inside the ZIP did not match our allowed extension list.</span>'; unlink($zip); } // unlink zip if failed
else { echo '<span id="home-info">Image(s) was/were successfully uploaded!</span>'; }
}
?>
</div>
<br /><br /><br />
<img src="css/images/site-logo.jpg" id="logo" />
<br /><br /><br /><br /><br />
</div>
<div id="box">
<?php
global $filename, $image_urls, $thumb_urls;
echo '<br />';
echo '<div id="links">';
echo '<table>';
echo LINKS_DIRECT;
for($i = 0; $i < sizeof($filename); $i++) { echo $filename[$i]['direct'] . "\n"; }
echo LINKS_CLOSE;
echo LINKS_THUMB;
for($i = 0; $i < sizeof($filename); $i++) { echo $filename[$i]['thumb'] . "\n"; }
echo LINKS_CLOSE;
echo LINKS_BBCODE;
for($i = 0; $i < sizeof($filename); $i++) { echo '[IMG]' . $filename[$i]['direct'] . '[/IMG]' . "\n"; }
echo LINKS_CLOSE;
echo LINKS_HTML;
for($i = 0; $i < sizeof($filename); $i++) { echo '<img src="' . $filename[$i]['thumb'] . '" />' . "\n"; }
echo LINKS_CLOSE;
echo '</table>';
echo '<br />';
echo '<input type="reset" id="resetbtn-remote" class="button-sub" value="« Upload more" />';
echo '<br />';
echo '</div>';
?>
</div>
<?php include('includes/footer.php'); ?>
</div>
</body>
</html>
I guess the problem is inside the foreach loop (it was a for loop a few days ago, but faced the same problems), but I can't seem to fix it. I'll reexplain in a short version:
I upload a Zip archive
Script unZips the archive
Script renames the extracted files
Thumbnail must be generated for all images that were in the Zip (fails)
Multiple links should be outputted matching every image the was in the Zip (fails)
Ideas?
You are re-using a variable ($filename) for two different purposes. At the top, add a line like this:
$file_list = array();
Later in the code, where you do this:
$filename[] = array('direct' => $image_urls, 'thumb' => $thumb_urls);
... change it to this:
$file_list[] = array('direct' => $image_urls, 'thumb' => $thumb_urls);
Later in your code where you loop, use foreach instead:
echo LINKS_DIRECT;
foreach ($file_list as $this_file)
echo $this_file['direct'] . "\n";
echo LINKS_CLOSE;
echo LINKS_THUMB;
foreach ($file_list as $this_file)
echo $this_file['thumb'] . "\n";
echo LINKS_CLOSE;
echo LINKS_BBCODE;
foreach ($file_list as $this_file)
echo '[IMG]' . $this_file['direct'] . '[/IMG]' . "\n";
echo LINKS_CLOSE;
echo LINKS_HTML;
foreach ($file_list as $this_file)
echo '<img src="' . $this_file['thumb'] . '" />' . "\n";
echo LINKS_CLOSE;
You've got a lot of other odd things going on in there, like using constants for HTML fragments. I think you should take another look at your process there and eliminate some of the unnecessary steps and variables. I see several global keywords used... none appear to be necessary.
I fixed this problem just by removing the following code part:
file_exists($zip)
I want to upload a csv file with php. After the file is uploaded, I want to display the data of the CSV file. I would like an example how to accomplish this task.
This can be done in a much simpler manner now.
$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));
This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.
untested but should give you the idea. the view:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>
upload.php controller:
$csv = array();
// check there are no errors
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$col_count = count($data);
// get the values from the csv
$csv[$row]['col1'] = $data[0];
$csv[$row]['col2'] = $data[1];
// inc the row
$row++;
}
fclose($handle);
}
}
}
Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...
HTML:
<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>
</form>
</table>
PHP:
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
//Print file details
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.
if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {
echo "File opened.<br />";
$firstline = fgets ($file, 4096 );
//Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
$num = strlen($firstline) - strlen(str_replace(";", "", $firstline));
//save the different fields of the firstline in an array called fields
$fields = array();
$fields = explode( ";", $firstline, ($num+1) );
$line = array();
$i = 0;
//CSV: one line is one record and the cells/fields are seperated by ";"
//so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
while ( $line[$i] = fgets ($file, 4096) ) {
$dsatz[$i] = array();
$dsatz[$i] = explode( ";", $line[$i], ($num+1) );
$i++;
}
echo "<table>";
echo "<tr>";
for ( $k = 0; $k != ($num+1); $k++ ) {
echo "<td>" . $fields[$k] . "</td>";
}
echo "</tr>";
foreach ($dsatz as $key => $number) {
//new table row for every record
echo "<tr>";
foreach ($number as $k => $content) {
//new table cell for every field of the record
echo "<td>" . $content . "</td>";
}
}
echo "</table>";
}
So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.
I have created below snippet with the help of #Thomas Clowes answer
$tmpName = $_FILES['csv']['tmp_name'];
$csv_data = array_map('str_getcsv', file($tmpName));
array_walk($csv_data , function(&$x) use ($csv_data) {
$x = array_combine($csv_data[0], $x);
});
/**
*
* array_shift = remove first value of array
* in csv file header was the first value
*
*/
array_shift($csv_data);
// Print Result Data
echo '<pre/>';
print_r($csv_data);
It will get result like below
Array
(
[0] => Array
(
[make] => Audi
[model] => S4
[grade] =>
[chassis] => WAUZZZ8K9DA076529
[year] => 2012
[kms] => 127000
[color] => White
[doors] => 4
[cc] => 3000
[engineno] =>
[trans] => FAT
[fueltype] => P
[condition] => 4
[price] => 15753
)
)
You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().
I feel str_getcsv — Parse a CSV string into an array is the best option for you.
You need to upload the file to the server.
Parse the file using str_getcsv.
Run through the array and align as per u need on your website.
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
public function uploadCsvFile(){
try{
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$request = $this->post();
$fileName = $request->file;
$file = fopen($fileName, "r"); //open the file
// $fileName = $_FILES["file"]["tmp_name"];
while(($column = fgetcsv($file)) !== FALSE){
$num = count($column);
$this->dbw->query("insert into csv_upload(first_name,last_name,email,phone,address,pin) values('".$column[0]."','".$column[1]."','".$column[2]."','".$column[3]."','".$column[4]."','".$column[5]."')");
}
fclose($file);
}
}catch (Exception $e) {
$this->responseErr($e->getMessage(), 500);
}
}
You can try with this:
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}