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...).
Related
How can I check only file name not extension like jpeg, jpg, doc, xls. and then copy its complete name like example.jpeg or example.doc
and if possible can we store its upper two parent directory like
if example.jpeg stored in
main_dir/second_dir/example.jpeg
so I want to store this path in php variable.
I know I can use glob()
$result = glob ("./uploads/filename.*");
and check $result value.
But I want to store complete file name and possible its two parent directory path.
Below is my code
$filename = '/www/test1/'. $file . '*' ;
if (count(glob($filename)) > 0) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
Edit
Updated query as per luweiqi solution
foreach(glob("/uploads/".$productnumber."/". $productnumber."b.*", GLOB_NOSORT) as $file) {
echo "Filename: " . $file . "<br />";
$image2 = "/uploads/".$productnumber."/".$file;
}
Last letter of image varies like a to f . so can you make some correction in it.
I want to check image is exist on uploads/productnumber/productnumber (a/b/c/d/e/f).jpg or png or jpeg etc. and store that file name in php variable.
You can use file_exists() function.
$pngFile = '/path/to/foo.png';
$docFile = '/path/to/foo.doc';
// Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
if (file_exists($filename) || file_exists($docFile)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
OR
Use glob function
$files=[];
$result = glob ("/path/to/foo.*");
foreach ($result as $file) {
echo "$file size " . filesize($file) . "\n";
$files[] = $file;
}
echo '<pre>'; print_r($files);
You can use:
<?php
foreach(glob("../directory/*{a,b,c,e,f}.*", GLOB_BRACE) as $file) {
echo "Filename: " . $file . "<br />";
}
?>
This code would get the file name and echo it, you can change it accordingly if you want to assign it to a variable.
I use this script to upload files via POST from my android app to my server. 95% of the time it works ok, but sometimes the upload folder of my clients is empty. The file is sent definitely, because I get the name and phone numbers (without a file selected the app will not pass any data), but the uploaded file is not written to disk on the server. I am not an expert in php, maybe I have missed something:
My upload php script:
$file_path = "uploads/{$_POST['name']}/";
if (!file_exists("uploads/{$_POST['name']}")) {
mkdir("uploads/{$_POST['name']}", 0777, true);
} else {
echo 'folder already exists!';
}
$newfile = $_POST['name'] . "_" . date('m-d_H-i-s') . '.zip';
$filename = $file_path . $newfile;
if(!file_exists($filename)) {
if(move_uploaded_file($_FILES['zipFile']['tmp_name'], $filename)) {
echo "success";
}
} else {
echo 'file already exists';
}
I am a newbie to programming, and this is my first exposure to PHP. I am building a mobile web app where users can upload pictures to the site while at the social event.
I used the PHP script from W3schools (don't hate me please, but it works for my limited knowledge).
Because it is a mobile app I need to add extra functionality but cannot figure out how with the multitude of scripts and my lack of knowledge.
Before the image is uploaded in the script, I would like first do the following.
1) Reduce the dimension to 500px wide and 'auto' the height to retain picture ratio.
2) Compress the file so it is more appropriately filesized for resolution on mobile devices (it will never be printed) and to speed up the upload over cell network.
3) Ensure that the display is correct by way of EXIF data. Right now, iOS, Android and Windows all display portrait and landscape images differently,...I need consistency
Here is my code,...I have remarked where I think it should go but I am not entirely sure.
This code comes up in a pop-up div tag over the page that displays the images.
<?php
$target_dir = "uploads/";
$target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]);
$target_dir1 = $target_dir . basename( $_FILES["uploadFile"]["tmp_name"]);
$fileTmpLoc = $_FILES["uploadFile"]["tmp_name"];
$uploadOk=1;
// Check if Upload is done without file.
if (!$fileTmpLoc) { // if file not chosen
echo '<script language="javascript">';
echo 'alert("Please browse for a file before clicking the upload button")';
echo '</script>';
echo '<script language="javascript">';
echo 'window.history.back()';
echo '</script>';
}
// Check if file already exists
if (file_exists($target_dir . $_FILES["uploadFile"]["name"])) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($uploadFile_size > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
//Check no php files
if ($uploadFile_type == "text/php") {
echo "Sorry, no PHP files allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
//Reduce file to 500px wide
//Compress file
//Rotate file with EXIF data to properly display.
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir1)) {
echo header( 'Location: gallery.php' ) ;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Thanks for any help and as mentioned this is my first exposure to PHP.
There is a free utility called SimpleImage.php, available at http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php that will handle resizing and compression and might be a good starting point. There are great examples on their page on how to use it, below is an example of how I use it to resize uploaded images to a certain width:
require_once("SimpleImage.php");
function createThumbnail($cat_code) {
// Check for full size product image
$fname = $this->getImageFilename($cat_code);
if($fname === "") {
echo "<b>createThumbnail: No image file found for " . $cat_code . "!</b><br>";
return false;
}
$thumb = "images/t/" . $cat_code . ".100.jpg";
if($fname !== "") {
$image = new SimpleImage();
$image->load($fname);
$image->resizeToWidth(100);
$image->save($thumb);
}
return true;
}
function process_upload($file, $cat_code, $format, $price=NULL) {
$imageFileExtensions = array('jpg', 'gif', 'png');
$target_path = "uploads/";
$target_path1 = $target_path . basename($file['name']);
$path_info1 = pathinfo($target_path1);
$ext = $path_info1['extension'];
if(move_uploaded_file($file['tmp_name'], $target_path1)) {
if(rename($target_path1, $main_path1)) {
echo "File ". $file['name'] . " verified and uploaded.<br>";
//Create thumbnail if this is an image file
if(in_array($ext, $imageFileExtensions))
$createThumbnail($cat_code);
} else {
echo "<b>ERROR renaming " . $file['name'] . "</b><br>";
}
}
else
echo "<b>move_uploaded_file(" . $file['tmp_name'] . ", $target_path1) failed</b><br>\n";
}
To do a rotate just add another function to the SimpleImage class that uses imagerotate(), for example the following:
function rotate($angle, $bgd_color, $ignore_transparent=0) {
imagerotate($this->image, $angle, $bgd_color, $ignore_transparent);
}
The php.net page for imagerotate has more details on the function parameters.
To work with EXIF data, I use another free utility called PelJpeg.php, available at http://lsolesen.github.io/pel/. There are many examples on how to use this if you google PelJpeg.php. It can get kind of complicated, because as you mention, every platform handles images and meta data a little differently, so you have to do a lot of testing to see what things are handled the same on various platforms, what things are different, and how to bridge across those gaps.
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".
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";
}
}
?>