I want to import excel data into mysql using php. My program works without any error if I have written path of excel file as hardcoded. But if I am trying to use it using upload function at that time I am facing one error. My error is as follws. :
filename C:\wamp\tmp\php1FC.tmp is not readable
I am also providing my code for reference :
include 'config.php';
require_once 'Excel/reader.php';
$allowedExts = array("xls","xlsx");
$temp = explode(".", $_FILES["file"]["name"]);
if (in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$filename=$_FILES["file"]["name"] ;
$filetype=$_FILES["file"]["type"] ;
$filesize=$_FILES["file"]["size"] ;
$filetemp=$_FILES["file"]["tmp_name"];
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
$handle = fopen($filetemp, "r");
$data = new Spreadsheet_Excel_Reader();
$data->read($filetemp);
$numr=$data->sheets[0]['numRows'];
for ($i = 2; $i <= $numr ; $i++)
{
$gender=$data->sheets[0]['cells'][$i][1];
$txtname=$data->sheets[0]['cells'][$i][2];
$txtusername = $data->sheets[0]['cells'][$i][3];
$txtphone=$data->sheets[0]['cells'][$i][4];
$txtlandno=$data->sheets[0]['cells'][$i][5];
$txtwing=$data->sheets[0]['cells'][$i][6];
$txtemail=$data->sheets[0]['cells'][$i][7];
$txtflat=$data->sheets[0]['cells'][$i][8];
$intercom=$data->sheets[0]['cells'][$i][9];
$userstatus=$data->sheets[0]['cells'][$i][10];
$livestatus=$data->sheets[0]['cells'][$i][11];
$flattype=$data->sheets[0]['cells'][$i][12];
$area1=$data->sheets[0]['cells'][$i][13];
$txtbuilding=$data->sheets[0]['cells'][$i][14];
$housingloan=$data->sheets[0]['cells'][$i][15];
$txtparking=$data->sheets[0]['cells'][$i][16];
$principalopBal=$data->sheets[0]['cells'][$i][17];
$interestBal=$data->sheets[0]['cells'][$i][18];
$servicetax=$data->sheets[0]['cells'][$i][19];
$txtgym=$data->sheets[0]['cells'][$i][20];
$txtcable=$data->sheets[0]['cells'][$i][21];
$txtswim=$data->sheets[0]['cells'][$i][22];
$txtclub=$data->sheets[0]['cells'][$i][23];
$unittype=$data->sheets[0]['cells'][$i][24];
I dont understand whats the problem. I want to perform this importing excel data functionality. And I want user can upload its own excel file for this. So please help me in this problem.
You're trying to open the temporary file that doesn't exist anymore after move_uploaded_file is called.
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
You need to open "upload/" . $_FILES["file"]["name"]. (Why not use $filename that you created it ?)
In addition, you're passing the same filename that doesn't exist to $data->read(), why create the handler then ? $data->read() should use $handle or the $filename ? Check that too.
Just to add another option, MySQL has a neat Excel tool/plugin that connects the tables directly to the file called MySQL for Excel.
More information: http://dev.mysql.com/doc/refman/5.7/en/mysql-for-excel.html
Is ".tmp" in the $allowedExts array? Please include the rest of the script and identify what line is outputting "filename C:\wamp\tmp\php1FC.tmp is not readable".
Related
Im having issues with my code being able to open a zip file that i have uploaded and moved into a folder, the zip file uploads fine and you can open it in any Zip program however, when i attempt to open it with ZipArchive to extract the data it errors.
$path = "../"; // Upload directory
$count = 0;
foreach ($_FILES['files']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $name))
$count++; // Number of successfully uploaded file
}
$kioskFile = $_FILES['files']['name'][0];
$kioskFile = explode(".", $kioskFile);
$kioskFile = $kioskFile[0];
$zipFile = "../" . $kioskFile . ".zip";
$zip = new ZipArchive;
$res = $zip->open($zipFile);
if ($res === true) {
$zip->extractTo("./");
$zip->close();
} else {
echo "Error Cannot Open Zip File - Error Code: ";
}
When i run the code it shows me a Error Code 19
ZIPARCHIVE::ER_NOZIP - 19
This is the error im getting, however the file exists and if i use zip_open, it returns that it can open the zip file.
Any help would be very greatful
EDIT1
If i upload a zip file that i manually create (using a zip program) then the upload works fine. However if i use a ZipArchive created zip file, then it instantly errors with a error 19.
EDIT2
I have now added a check to make sure the file exists in the right directory and also put a print of the location also, both match, however still the same issue. Error 19
$path = "../"; // Upload directory
$count = 0;
foreach ($_FILES['files']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path . $name))
$count++; // Number of successfully uploaded file
}
$kioskFile = $_FILES['files']['name'][0];
$kioskFile = explode(".", $kioskFile);
$kioskFile = $kioskFile[0];
$realpath = realpath("../");
$zipFile = $realpath . "\\" . $kioskFile . ".zip";
if (file_exists($zipFile)) {
$extract = zip_extract($zipFile, "../");
if ($extract === TRUE) {
} else {
echo "The file " . $zipFile . " cannot be opened";
}
} else {
echo "The file " . $zipFile . " does not exist";
die();
}
UPDATE1
So i think ive narrowed it down to either this bit of code, or the download script that i use to download the .zip file from the system, if i leave the zip on the system and use the exact same bit of code it works fine.
Here is my download code, maybe ive missed something on this that is causing the issue.
$fileID = $_GET['id'];
$backupLoc = "backups/";
$sql = "SELECT * FROM backups WHERE id = '" . addslashes($fileID) . "' LIMIT 1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$backupFile = $row['backupFile'];
$zipFile = $backupLoc . "/" . $backupFile . ".zip";
$zipSize = filesize($zipFile);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($zipFile). '"');
ob_end_flush();
readfile($zipFile);
exit;
die();
Open the archive with a text or hex editor and make sure you have the 'PK' signature at the start of the file.
If you have any HTML before that signature, it would suggest that your buffers are not being cleaned or are being flushed when they should not be, meaning that PHP ZipArchive will assume an invalid archive.
It was the download.php file that was causing the issue, here is the solution. which was to do a OB CLEAN rather than a Flush
///echo "<div style='padding: 50px;'>Please Wait .....</div>";
$fileID = $_GET['id'];
$backupLoc = "backups/";
$sql = "SELECT * FROM backups WHERE id = '" . addslashes($fileID) . "' LIMIT 1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$backupFile = $row['backupFile'];
$zipFile = $backupLoc . "/" . $backupFile . ".zip";
$zipSize = filesize($zipFile);
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($zipFile). '"');
//ob_end_flush();
ob_end_clean();
readfile($zipFile);
exit;
die();
This is part of a php/ajax upload script.
Anyone know how to upload into a directory ?
<?php
if(isset($_FILES["imageNameHere"]) && !empty($_FILES["imageNameHere"])) {
// Random name
$name= rand(10, 20).'.png';
// Move the file
//move_uploaded_file($_FILES["imageNameHere"]['tmp_name'], $name);//orginal
move_uploaded_file( $_FILES["imageNameHere"]["tmp_name"],$name, "uploads/" .
$_FILES['imageNameHere']['tmp_name'][$name]); // My Try
// Return name
echo $name;
}
?>
This should work, Change:
move_uploaded_file( $_FILES["imageNameHere"]["tmp_name"],$name, "uploads/" . $_FILES['imageNameHere']['tmp_name'][$name]); // My Try
To:
move_uploaded_file( $_FILES["imageNameHere"]["tmp_name"], "uploads/" . $name);
You will run into problems when rand() generates the same number twice however.
My script has a user upload a pdf. I have found a pdf parser that then displays the first part of the plain text. The user will then verify that the data is the correct data. If it is, then the user submits the data and it saves it to a file. For data that isn't a file, I've always passed the info using invisible form fields to an execute page. However with a file I'm not sure the best way to do it.
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else{
$uploadedFile = $_FILES["file"]["tmp_name"];
$result = pdf2text($uploadedFile);
echo substr($result, 0, 200);
echo "<BR>";
}
Based on the POST method uploads manual
The file will be deleted from the temporary directory at the end of
the request if it has not been moved away or renamed.
You will want to move your tmp_file to a cache directory inside your app, and then based on your validation being true or false remove it, or move it to a permanent directory.
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else{
$uploadedFile = $_FILES["file"]["tmp_name"];
$tmp_file = PATH_TO_CACHE_FOLDER . time(). $_FILES["file"]["name"]
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $tmp_file)) {
$result = pdf2text($uploadedFile);
echo substr($result, 0, 200);
echo "<BR>";
}
}
and in the next script
if(isValid() === true)
{
$tmp_file = $_POST['tmp_file_name'];
$file_name = $_POST['file_name'];
move_uploaded_file($tmp_file, PERMANENT_PATH . $file_name);
}
this is just mock code, but should give you a better idea.
Move the uploaded file with:
move_uploaded_file( $uploadedFile, "some/where/temp.pdf" );
...and create a hidden form field containing the new filename (some/where...).
I am running a PHP script to upload files from a HTML form, rename them and place them on my server. It is uploading and renaming, however every file name now starts with the word "Array"
ie: ArrayTest Document v1.0.pdf
I am fairly confident it isn't my $newfn variable as I display that in a table and it doesnt show up.
//This gets all the other information from the form
$name=$_POST['docname'];
$version=$_POST['docver'];
$date=$_POST['docdate'];
$type=$_POST['doctype'];
$author=$_POST['docauth'];
$file=$_FILES['uploaded']['name'];
//target directory is assigned
$target = $directory;
$target = $target . basename($file) ;
//grab file extension
$filetypes = array(
'image/png' => '.png',
'image/gif' => '.gif',
'image/jpeg' => '.jpg',
'image/bmp' => '.bmp',
'application/pdf' => '.pdf');
$ext = $filetypes[$_FILES['uploaded']['type']];
//generate new filename variable "name v??.xxx"
$newfn = $name . ' ' . 'v' . $version . $ext;
//Check to see if file exists
if (file_exists($directory . $file))
{
echo $_FILES["uploaded"]["name"] . " already exists. ";
}
else
{
//if its a new file, change name and upload
if (move_uploaded_file($_FILES["uploaded"]["tmp_name"],
$directory . $_FILES["uploaded"] . $newfn))
{
echo "The file ". basename($file). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
I feel like it's related to my $FILES['uploaded'] section in the move_uploaded_file command. I've tried googling but as soon as I mention "Array" my google results are nothing remotely the same.
Ok so thanks to below I solved it. For anyone in the future I removed the entire $_FILES array so the code reads as
//if its a new file, change name and upload
if (move_uploaded_file($_FILES["uploaded"]["tmp_name"],
$directory . $newfn))
Everything now uploads with the correct name structure. Thanks.
Should be
move_uploaded_file($_FILES["uploaded"]["tmp_name"],$directory . $_FILES["uploaded"]["name"] . $newfn)
You forgot to include ["name"] after $_FILES["uploaded"]
In your move_uploaded_file you are using the whole $_FILE['uploaded'] array as the name, not just the filename. A small tweak:
if (move_uploaded_file($_FILES["uploaded"]["tmp_name"],
$directory . $_FILES["uploaded"]["name"] . $newfn))
{
And you should be all good.
I am trying to upload an image to the server (with a path in mysql table) twice through php with different names. One version of the image as "xxxx.png" and the other version of the image as "xxxxt.png".
My php is:
<?php
if ($_FILES['photo']) {
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
} else {
echo "Error uploading new image - please check the format and size";
}
}
?>
The above code inserts the image into the mysql database and uploads the file to the server correctly.
I am however trying to upload the same image twice with a different naming convention on a "thumbnail" version. The slideshow script in my html only recognises the thumbnails if there are named with a "t" at the end of the filenames hence my problem.
I have been advised to look at the php copy() function to achieve this but am incredibly unclear as to how to incorporate such a function into my existing code.
Happy to provide the html or any other info if required.
Any help much appreciated. I did have another thread attempting to find out the same thing but I wasn't very clear!
Thanks
JD
If I correctly understand you, you do not need to upload this file twice. You already have this file on your server. So you should copy it (optionally do some transitions to make it more like a thumbnail) on your server's hard drive and update database.
Your code should like similar to this:
<?php
if($_FILES['photo'])
{
$target_dir = "images/properties/";
$upload_file_name = basename( $_FILES['photo']['name']);
$upload_file_ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . $upload_file_name . '.' . $upload_file_ext;
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.' . $upload_file_ext);
$target_thumb = $target_dir . $upload_file_name . 't.' . $upload_file_ext;
$target_thumb_sql = $target_dir . mysql_real_escape_string($upload_file_name . 't.' . $upload_file_ext);
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_file_sql' )");
echo "The new image has been added successfully";
if (copy($target_file, $target_thumb))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_thumb_sql' )");
echo "The new thumb image has been added successfully";
} else
{
echo "Error copying thumb file";
}
} else
{
echo "Error uploading new image - please check the format and size";
}
}
Again, the idea is that you do not need to upload file twice in a row. All you need to do is just copy it on server.
As you've been advised you should use copy(). I didn't fully test this but give it a try:
<?php
if ($_FILES['photo'])
{
$target = "images/properties/";
$ext = array_pop(explode('.', $_FILES['photo']['name']));
$copy = $target . basename($_FILES['photo']['name'], '.' . $ext) . 't.' . $ext;
$target = $target . basename($_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
copy($target, $copy);
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
}
else
{
echo "Error uploading new image - please check the format and size";
}
}
?>