PHP file upload strange issue - php

While uploading images files on the live server I have stuck in a strange issue that the move_uploaded_files() function returns true but the image does not get uploaded.
if(move_uploaded_file($_FILES["img"]["tmp_name"],'./shot_images/'.$_FILES["img"]["name"])){
echo "Success";
}
Here, when executed, prints "Success" but the file is not being uploaded on the specified location.
Any kind of help is appreciated.

If move_uploaded_file is returning true then that indicates the file was moved successfully. Let's try some debugging. What happens when you use the following code:
$dest = "./shot_images/{$_FILES["img"]["name"]}";
if(move_uploaded_file($_FILES["img"]["tmp_name"],$dest)){
$realpath = realpath($dest);
$filesize = filesize($realpath);
echo "Success! Uploaded a $filesize file to $realpath";
}
I suspect it is working, it's just not going where you expect...
If this is the case, it might be due to `'./shot_images/' -- personally I rarely (if ever) use relative paths like that. I find it eliminates confusion if I reference the path to the script:
$dest = dirname(__FILE__)."/shot_images/{$_FILES["img"]["name"]}";
if(move_uploaded_file($_FILES["img"]["tmp_name"],$dest)){

Related

php move_uploaded_file not creating file

I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}

file_exists returns false even when the path is right

I have seen some similar questions here, but no answer fit my needs.
I have a Wordpress and in the upload dir there is an image, I have the following url for the image: ../../uploads/2016/2/56c3620a9c8af.png I try to access the file from inside the child theme folder:
/home/mydomain/www/wp-content/themes/twentyfifteen_child
I would like to check if the file exists and afterwards unlink() the image, but the file_exists always returns false, even though I can echo the image.
The following simple function outputs the image but returns false.
function checkImageExist($url)
{
echo '<img src = "'.$url.'" /><br>'; //The image is rendered
clearstatcache();
if(file_exists($url))
{
echo 'Image exists '.$url;
}
else
{
echo 'Image does not exist';
}
}
And this is what I CAN'T UNDERSTAND.
What am I missing?
THERE WAS NO QUESTION AT ALL:
The script I was using to upload the files was duplicating the extension names, so 56c3620a9c8af.png was in fact 56c3620a9c8af.png.png this stupid mistake was the responsible of images appearing when called (as the browser was able to parse them even though the duplicated extension) but file_exists was not able to find them.
So everything was working and I was mistaken about the error source.
You are passing a $url when what you really need is a $path. You can get the path like this:
$path = wp_upload_dir(); //This returns an array with URL info
$path['path']. '/2016/2/56c3620a9c8af.png'

How to log errors for move_uploaded_file to a file

I have some code that uploads a file, its the exact same code i had working on another server but its not working on this new server
// Move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"]);
I know i can use:
if(move_uploaded_file($_FILES["file"]["tmp_name"],'./img/myfolder/1/'. $_FILES["file"]["name"])){
echo "success";
} else{
echo "failure";
}
However i have 2 problems, the script is not ran directly from the page, another application which i dont have access to source code to calls that page and sends the image. So i cant do any in page errors i need to log the errors to a file.
The 2nd problem and the main issue is i am not sure how to find out what the error is. Is there an error code i can pull if the else statement is called. I have set it to 777 for the folders and subfolders just for testing purposes to rule out permission issues, ill fix that after getting the problem resolved before pushing to production.
Also i checked the apache server error.log file and it shows nothing
Here i would do something like this.
$debug_file = _DIR_.'/debug.txt';
$source = $_FILES["file"]["tmp_name"];
$dest = './img/myfolder/1/'. $_FILES["file"]["name"];
if(! #move_uploaded_file($source,$dest) ){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ]\n", FILE_APPEND);
exit();
}
Then when you have the source and dest paths you can make sure they actually exist in the right places.
-note- the # sign will suppress the normal PHP warning for failing to move the file, but as we are logging it our self, this just prevents it from getting in the way.
Also I put an exit in, I'm assuming its a requirement of this script to have the file to work properly, and that way it's enough just to fail, no need to check for success.
Most likely, the file path is wrong
Also you could even output buffer the php error as well like this,
ob_start();
$moved = move_uploaded_file($source,$dest);
$message = ob_get_clean();
if(!$moved){
file_put_contents( $debug_file, "ERROR[ ".date('Y-m-d H:i:s')." ] Could not move[ $source ] to[ $dest ] PHP message[ $message ]", FILE_APPEND);
exit();
}
Output buffing works wonders on scripts ran in the background,
http://php.net/manual/en/function.ob-get-clean.php

file_exists and paths that include relative paths ("/../")

When I use file_get_contents on a path like /a/path/to/a/../file.php, it gets the content just fine. If I call file_exists first (or is_file or realpath), the return values indicate that the file does not exist. What seems to be the issue?
Edit: Here is some additional information condensed from comments to answers:
I am running Mac OS X 10.9 with php 5.5.6, so safe mode should not be an issue (it was removed in version 5.4)
I tried clearing the file cash by calling clearstatcache(true, $dir1)
The file in question is 362 bytes in size, but I reproduced this issue with several different files in a medley of locations.
open_basedir is commented out in the php.ini
The file is local (the first file I tried was in the same directory as the script)
The issue exists in the command line (phpUnit) and in the browser.
The permissions on the file in questions are -rwxrwxrwx (I sudo-chmod-777ed the file)
This is a code snippet that creates the behavior:
$dir1 = '/a/path/to/a/../file.php';
$dir2 = '/a/path/to/file.php';
echo "File content dir1:\n";
echo file_get_contents($dir1);
echo "\ndir1 exists: ".(int)file_exists($dir1);
echo "\n\nFile content dir2:\n";
echo file_get_contents($dir2);
echo "\ndir2 exists: ".(int)file_exists($dir2);
the output is:
File content dir1:
The actual content of the file. I promise!
dir1 exists: 0
File content dir2:
The actual content of the file. I promise!
dir2 exists: 1
It sounds like you have safe mode turned on and are attempting to access a file that PHP would consider unsafe when running in safe mode. From the manual:
Warning
This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.
EDIT: You can also reproduce this behavior if /a/path/to/a/ is not a real path. For example:
<?php
$dir1 = '/realDir/realDir2/filetoinclude.php';
echo "File content dir1:\n";
echo file_get_contents($dir1); // outputs file contents
echo "\ndir1 exists: ".(int)file_exists($dir1); // outputs 1
$dir2 = '/realDir/realDir2/realDir3/../filetoinclude.php';
echo "\n\nFile content dir2:\n";
echo file_get_contents($dir2); // outputs file contents
echo "\ndir2 exists: ".(int)file_exists($dir2); // outputs 1
$dir3 = '/realDir/realDir2/NotARealDirectory/../filetoinclude.php';
echo "\n\nFile content dir3:\n";
echo file_get_contents($dir3); // outputs file contents
echo "\ndir3 exists: ".(int)file_exists($dir3); // outputs 0
This is because file_exists needs to traverse the entire path, literally, so it looks for the missing directory and fails. I'm not sure exactly what file_get_contents does that is different, and I can't find much on Google, but it clearly does some parsing of the path that is different from what file_exists does.
I am providing the workaround that I developed with a regex, if others have this same issue. I hate to be using this hack, and I still don't understand why I am having this issue, but hopefully someone will come up with an actual solution.
Before calling file_exists I now call this function:
function resolve($path) {
$regex = "/(.?)(\/[^\/]*\/\.\.)(.*)/";
$result = preg_replace($regex, "$1$3", $path);
if ($result != $path) {
$result = resolve($result);
}
return $result;
}

How to upload file to amazon s3 using MAMP?

I'm trying to push a file to a Amazon s3 filebucket.
I'm posting the file through an html form.
I try to generate a path to the file like this($file is a part of a foreach, because i need to support multiple files in a form-submit.)
$file['tmp_name'].'/'.$file['name'];
this outputs a filepath like this
/Applications/MAMP/tmp/php/phpZDcVQv/pdf.pdf
/Applications/MAMP/tmp/php/ exists, but nothing is inside it. I have set access read and write for everyone to that folder.
I use a library to post the images to Amazon: https://github.com/tpyo/amazon-s3-php-class It also complains that the filepath i have provided doesn't exist. It's running a check like:
if (!file_exists($file) || !is_file($file) || !is_readable($file))
How come the files aren't added?
Am I referencing the wrong folder? The file with the code is in /web/projectname/
Someone on the internet said something unclear about php removing the temp-file directly. Is this after the response has been run? Do I need to address this in some way?
The most simple code that generates the problem:
foreach ($_FILES as $file) {
$filepath = $file['tmp_name'].'/'.$file['name'];
if(file_exists($filepath)){
echo 'true <br />';
}else{
echo 'false <br />';
}
}
This echo:es false even if files have been uploaded.
$filepath contains the path i described above.
as the manual states:
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
and
$_FILES['userfile']['name']
The original name of the file on the client machine.
this means that file_exists($file['tmp_name']) should be true.
The path $file['tmp_name'].'/'.$file['name'] is bogus, since $file['name'] is there only for informing you of the original name, but this name is not used while saving the uploaded file on the server.
So in your example /Applications/MAMP/tmp/php/phpZDcVQv is actually the uploaded file.

Categories