Whenever I try to move a file it does not work and shows "Image file not uploaded"... I just want to know where the error is...
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if( move_uploaded_file( $target, $destination ) ) {
echo "Image file is successfully loaded";
} else {
echo "Image file not uploaded.";
}
I have checked error log (tail -f /var/log/apache2/error.log) but found nothing.
target and destination both directories have 777 permissions.
Can someone tell me that how to find out the error. Any idea ?
If you are not using HTTP POST upload method then you can use rename()
rename($target, $destination);
Has the file been uploaded in the current request?
move_uploaded_file will refuse to move files that are not uploads. (i.e. $target must equal $_FILES[$field_name]['tmp_name']
If it has been uploaded previously, move_uploaded_file will refuse to work (if it is even still there - PHP will delete it if you don't handle the file on that upload if I remember correctly)
If it is in fact not a file that has been uploaded with this request you'll want to use rename
move_uploaded_file() only works on http post files. http://php.net/manual/en/function.move-uploaded-file.php
to move a file already on the server, you will have to copy the file and unlink the old file
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if (copy($target, $destination)) {
unlink($target);
} else {
echo "Unable to copy $target to $destination.";
}
Related
Greetings anyone who is reading this!
Currently I have a php page that allows the user to upload a file to my server at a specified directory. Here is what I use to do that:
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
chmod($uploadpath, 0777);
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']); // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext); // gets extension
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = ''; // to store the errors
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
chmod($uploadpath, 0777);
echo '<br/><br/>File successfully uploaded:' .$uploadpath.'</b>';
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
The uploading part works like a charm and the file is uploaded fine to the server however once uploaded, I am unable to delete the file as another user. Currently the user uploading the file would be the Apache user "www-data".
I do believe that the issue has to do with permissions being set for the uploaded file which I have tried using:
chmod($uploadpath,0777);
This does not help though.. The file still can't be removed. I can remove it through SSH if I am root using "rm -rf /directorypath" but can't delete it if I browse to it.
Any suggestions? Any help is greatly appreciated!
if you want to remove a file you can use php unlink ! And if thats a directory then rmdir !
you could use unlink('upload_folder/'.$image['file_name']);
Try to allow permission to your image folder too not just the files underneath.
chmod($upload_path, 0777);
before the line
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
Note that 777 is not super safe anyway. Best practice is to manage users with the group www-data
Following is my piece of code which moves file to particular directory.
foreach($files as $dir_file) //Getting Path of XML file
{
echo "\nDir Files: ".$dir_file."\n";
if($dir_file != "." && $dir_file != "..")
{
if(strpos($dir_file,'.xml'))
{
echo "\nXML file found\n";
$xmlPath=$path."/".$dir_file;
// return ReadXML($xmlPath);
}
if(strpos($dir_file,'.JPG'))
{
echo "\n FOund \n";
$ret=move_uploaded_file($dir_file, 'upload/'.$dir_file));
echo "\n retunr values: ".$ret;
}
}
I have checked all permission and it is 777. but move upload file function is not moving my file to particular directory. it is also not returning anything. What i am doing wrong?
If you are to move files from one directory to another, you should use copy() function.
This is the example code:
$source = "YOUR_SOURCE_DIRECTORY/";
$destination = "YOUR_DESTINATION_DIRECTORY/";
foreach ($files as $file) {
if (in_array($file, array(".","..")))
continue;
//If file is copied successfully then mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
//If you want to delete the copied files then include these lines
//Delete all successfully copied files
foreach($delete as $file) {
unlink($file);
}
move_uploaded_file
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
(Emphasis mine.) You can use move_uploaded_file only to move files which have been uploaded, where "uploaded" means "PHP has received the file in the current request and the file is currently in the $_FILES super global". Any other file is not movable by move_uploaded_file. This is exactly on purpose, move_uploaded_file is supposed to protect you from yourself and make sure you're only moving files uploaded by the user.
If you want to move any other file which has not just been uploaded via HTTP POST, use copy or rename.
I am sending image from android apps to server. The problem is image not moving to the correct path, but only at current directory (only in which that php script stored). I tested this codes on local server and webserver, getting same result. Any one can find out whats problems.
Local Server: XAMPP 1.7.7
My PHP Script :
<?php
$base=$_REQUEST['image'];
$Username=$_REQUEST['Username'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen($Username.'.png', 'w');
fwrite($file, $binary);
$uploadFilename = '/htdocs/android/ProfileImage/';
$tr =move_uploaded_file($_FILES[$file]['tmp_name'], $uploadFilename);
if($tr)
echo 'true';
else
echo 'false';
echo 'Successfully Uploaded';
?>
Showing Output and Error in Local Server
Strict Standards: Resource ID#3 used as offset, casting to integer (3) in C:\xampp\htdocs\android\uploadSimage.php on line 12
Notice: Undefined offset: 3 in C:\xampp\htdocs\android\uploadSimage.php on line 12
falseSuccessfully Uploaded
Showing Output and Error in Webserver
Notice: Undefined offset: 3 in C:...\uploadSimage.php on line 12
falseSuccessfully Uploaded
move_uploaded_file() expects the second parameter to be a string representing the new path and filename of upload. Currently, you are passing only a path. I also question whether the path is correct. It must be a full path, or a relative path.
You are also using the $_FILES array incorrectly. Are you uploading the image by encoding it in base64 and passing it via the URL's query string? Or are you actually uploading it using a multipart/form-data file upload field?
If you uploaded a file belonging to the upload field called image then you would get access to the file like this:
$origname = $_FILES['image']['name']; // the name from the client device
$temppath = $_FILES['image']['tmp_name']; // the temp location on the PHP server
$error = $_FILES['image']['error']; // > 0 if there was an error
$size = $_FILES['image']['size']; // size of the file
$type = $_FILES['image']['type']; // mime type, cannot be trusted though
You would then move it like this:
// Be careful using the original file name.
// If the user uploads a file with a .php extension, they may be
// able to run PHP code on your server if they can access the upload folder
// You should either generate a random file name or remove the extension
// IF THE DESTINATION FILE EXISTS, IT WILL BE OVERWRITTEN
$newPath = '/home/yoursite/htdocs/uploads/' . $origname;
$moved = move_uploaded_file($_FILES['image']['tmp_name'], $newPath);
if ($moved) {
echo "File was moved successfully.";
} else {
echo "Failed to move file.";
}
EDIT:
If you are in fact uploading the image by encoding it in base64 and sending it over the URL, then you don't need move_uploaded_file at all; in that case you can just write the decoded contents to a file anywhere you like. Keep in mind, the length of the URL may be limited so sending the image in the URL via base64 may not be a good idea.
EDIT 2:
To comment on the questions in your subsequent answer: The php function move_uploaded_file() should only be used when the file you are trying to move was uploaded to PHP using an HTTP POST method upload. It does an internal check to see if the file you are trying to move was uploaded to PHP. If it was not, then it won't move the file. Therefore you shouldn't be using move_uploaded_file() since you confirmed you were uploading the image through the URL.
Since your PHP script's path is C:\xampp\htdocs\android, this means the root path is C:\. The server root is different from your web root or document root which are both relative to your public directory. Any time you are dealing with reading/writing files in PHP, you use the full server path (relative to C:\ or /).
Given the new facts, try some code like this to "upload" the image:
<?php
$base = (isset($_REQUEST['image'])) ? $_REQUEST['image'] : '';
$Username = (isset($_REQUEST['Username'])) ? trim($_REQUEST['Username']) : '';
$binary = #base64_decode($base);
if (empty($Username)) {
die('no username specified');
}
if (!$binary) {
// data was not in base64 or resulted in an empty string
die('invalid image uploaded');
}
$basePath = 'C:\\xampp\\htdocs\\android\\ProfileImage\\';
$imagePath = $basePath . $Username . '.png';
$file = #fopen($imagePath, 'w+');
if (!$file) {
die('failed to open ' . $imagePath . ' for writing');
}
fwrite($file, $binary);
fclose($file);
echo 'Successfully Uploaded';
Make sure to take the necessary precautions so I can't upload an image for another user.
per to this document http://php.net/manual/en/function.move-uploaded-file.php another reason for this problem is invalid File name if your file Name in
move_uploaded_file ( string $filename , string $destination ) be invalid
this function return false
I accessed my server using file zilla and give write Group permissions to the target folder and then it worked.
If you're using XAMPP:
sudo chmod 777 -R /opt/lampp/htdocs/
Here is a problem.
I have an HTML form with several fields in it.
One of the fields - 'Upload file'.
When I upload a file, everything works properly. But when I choose to submit the form without a file, it gives me the error message: "There was an error uploading the file, please try again". Looks to me that the script thinks that uploading a file is mandatory.
How do I change it?
Here is my PHP:
//File upload
// Where the file is going to be placed
$target_path = "uploads/";
// Add the original filename to our target path.
//Result is "uploads/filename.extension"
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
//End of file upload
Thank you!
You should check using the function is_uploaded_file
try adding the following condition before calling the function move_uploaded_file
if (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
The target path of move_uploaded_files should be a folder, not a file.
You should also check if the folder is_writeable and is_dir.
move_uploaded_file returns a bool, true or false, depending on the success of the operation.
A solution would be to check more rigorously, e.g. if a file was uploaded at all via is_uploaded_file function.
For proper working, the function is_uploaded_file() needs an argument like $_FILES['userfile']['tmp_name'], - the name of the uploaded file on the clients machine $_FILES['userfile']['name'] does not work.
When I upload a file using this code, it puts a copy of the file in the "uploads" folder(which is what I want) but it also puts a copy in my root. I only want the files going to the uploads folder.
define ('GW_UPLOADPATH', 'uploads/');
$upfile= GW_UPLOADPATH . $_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
if(!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) //this is saying if the file isn't moved to $upfile.
{
echo 'Problem: could not move file to destination directory';
exit;
}
}
else
{
echo 'Problem: Possible file upload attack. Filename: '; //this could be an attack b/c it might be from localhost.
echo $_FILES['userfile']['name'];
exit;
}
echo 'File uploaded successfully<br><br>';
What would be your temporary dir? Is it possible that somehow the uploaded file lands in the root but PHP can not delete it? Figuring this out requires a lot more knowledge about your setup.