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';
}
Related
I'm trying to upload a file but I always get an error:
Notice: Undefined index: file_pdf in C:\xampp\htdocs\FYP2\site_admin\pentadbiran\upload.php on line 10
The example of my code get data from a form and upload to my database for the information given, such as file_reference, file_name, file_location and file_pdf.
But the problem is, the code runs well but does not update on file_pdf column in table. But the file upload into target folder is working.
if (isset($_POST['submit'])) {
$file_reference = $_POST['file_reference'];
$file_name = $_POST['file_name'];
$file_location = $_POST['file_location'];
$file_pdf = $_POST['file_pdf'];
if ($_FILES['file_pdf']['error'] == UPLOAD_ERR_OK)
{
$ext = strtolower(pathinfo($_FILES['file_pdf']['name'],PATHINFO_EXTENSION));
switch ($ext)
{
case'pdf':
break;
default:
throw new InvalidFileTypeException($ext);
}
$targetfolder = "pdf/";
$targetfolder = $targetfolder . basename($_FILES['file_pdf']['name']);
if (move_uploaded_file($_FILES['file_pdf']['tmp_name'], $targetfolder)) {
echo "The file " . basename($_FILES['file_pdf']['name']) . " is uploaded";
} else {
echo "Problem uploading file";
}
$sql = "INSERT INTO file (file_reference,file_name,file_location,file_pdf)
VALUES ('$file_reference','$file_name','$file_location','$file_pdf')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
The code is run but on my database the file_pdf does not update.Why is this?
The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.
$_FILES['userfile']['name'] The original name of the file on the client machine.
$_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] The error code associated with this file upload.
Change this...
$file_pdf = $_POST['file_pdf'];
to
$file_pdf = $_FILES['file_pdf']['name'];
I need to know code how to rename file before it gets uploaded to my server in php script.Ill post the php code of mine.
I need it because I am uploading an image from phone and I don't want it to be overwritten.
Can I achieve that?
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
For renaming file in Android, you can do :
String file_path = <file path off your existing file you want to rename>
File from = new File(file_path,"from.txt");
File to = new File(file_path,"to.txt");
from.renameTo(to);
This code will work for both file stored in internal or external storage. Just for writing to external storage remember you need to have android.permission.WRITE_EXTERNAL_STORAGE to be added to your Android manifest.
write your code like below.
$filename = $_FILES['upload_file']['name'];
$newname = 'alteredtext'.$filename; // you can also generate random number and concat on start.
$tmp_path = $_FILES['upload_file']['tmp_name'];
if(move_uploaded_file($mp_path, $newname)) {
echo "success";
} else{
echo "fail";
}
You don't need to use the name passed in the $_FILES array when moving the file. You can create any name you want (assuming the path is valid) and pass it as the second argument of move_uploaded_file. If you want a semi-random name, you could generate a random number and then hash it or something to create the filename.
If you want to check first, if the file exists, then rename it to have a numeric suffix, you could do this:
<?php
$base_path = "uploads/";
$file_path = $base_path . basename( $_FILES['uploaded_file']['name']);
if(file_exists($file_path)) {
$ctr = 0;
do { // increment an index to append to the filepath
$ctr++;
$file_path = $base_path . basename( $_FILES['uploaded_file']['name']) . "_$ctr";
} while(file_exists($file_path));
}
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
The above snippet will keep incrementing until it finds a filename that doesn't exist. Of course, you'd want to add some bounds and error checking, while the above snippet demonstrates the concept, it isn't entirely production ready.
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.
My scenario, user is posting data and image via android device on to server. I would like the script that handles upload to wait with the response until image is uploaded 100%.
Actually it's not clear to me, since I'm still a beginner, if this script does that already.
When posting item via android, I receive the response pretty fast and image is between 1 and 2MB.
This is the script I'm using now:
<?php
/************************************************
Required PHP Files
************************************************/
require_once("../models/funcs.php");
require_once("../models/db-settings.php");
/************************************************
Functionality
************************************************/
$image_path = "../images/items/";
$image_name = $_FILES['uploaded_file']['name'];
$user_id = $_POST['user_id'];
$query = ...
$result = $my_db->query($query);
$image_path = $image_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $image_path) && !$my_db->error) {
echo 200;
} else{
echo 400;
echo $my_db->error;
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploaded_file']['name']);
echo "target_path: " .$target_path1;
}
?>
This is how PHP has always worked. Your script is run only once upload is finished.
Only recently it's possible to monitor file upload progress.
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...).