PHP move_uploaded_file() issue - php

I have the PHP script (testupload.php):
<?php
error_reporting(E_ALL);
ini_set('log_errors',1);
ini_set('error_log','/root/work/inputs/log_file');
$target_path = "/work/inputs";
$target_path = $target_path . basename( $_FILES['frag3']['name']);
echo "Received File: " . $_FILES['frag3']['name'] . " and moving it to " . $target_path . "<br>";
if(move_uploaded_file($_FILES['frag3']['name'], $target_path)) {
echo "The file ". basename( $_FILES['frag3']['name']) . " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
And the HTML file to call it:
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form action = "http://localhost:8081/testupload.php" method="post" enctype="multipart/form-data">
<span>Value : </span><input type="text" name="Value" value="Hello world"/><br />
<span>Fragment File : </span><input type="file" name="frag3" /><br />
<input type="submit" value="Send"/>
</form>
</body>
</html>
However, I continually recieve the response:
There was an error uploading the file, please try again!
So it's clear that move_uploaded_file() is not correctly functioning. Plus, it doesn't actually move the file. However, I can't seem to diagnose the issue.
My first thought was that the directory was not writable. But my permissions for the folder are drwxrwxrwx (as determined by ls -l)
Also, the line:
ini_set('error_log','/root/work/inputs/log_file');
doesn't seem to write a log file to that location.
Has anyone had any experience with this? How can I diagnose whats going on here?
I am almost at a loss here, so any help would be greatly appreciated.
I am using OpenSUSE 11.2, Apache 2.2, and PHP 5.3.
Many thanks,
Brett

You should do move_uploaded_file($_FILES['frag3']['tmp_name'], $target_path)

Here are some things to check:
Ensure that your file upload and post limits are not reached by editing upload_max_filesize and post_max_size in your .htaccess or php.ini file. If you have error reporting on, you should see an error when they're reached. See this: http://drupal.org/node/97193
Check for file upload error codes. See the documentation for these: http://www.php.net/manual/en/features.file-upload.errors.php
Ensure that your memory_limit has not been reached. Again, with error logging enabled, you should receive an error message about this. http://drupal.org/node/207036
Check PHP's common pitfalls documentation and make sure there's nothing there that helps: http://www.php.net/manual/en/features.file-upload.common-pitfalls.php
If none of this helps, enable error reporting and post what you receive so we can tailor our answers better to your situation.

the php stores the file in server with temporary name
which you can get by
$_FILES['frag3']['tmp_name'] and not by $_FILES['frag3']['name']

I believe it's move_uploaded_file($_FILES['frag3']['tmp_name'], $target_path), as the files aren't actually stored by the name they're uploaded with (though you can, of course, rename them by setting their target path to such).

Related

failed to open stream: Permission denied for php move upload file [duplicate]

I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:
<?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Dump Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
Select the File:<br /><input type="file" name="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
I'm getting these errors:
Warning: move_uploaded_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4
PHP version 4.4.7
Running IIS on a Windows box. This particular file/folder has 777 permissions.
Any ideas?
OMG
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
Don't do that. $_FILES['file']['name'] could be ../../../../boot.ini or any number of bad things. You should never trust this name. You should rename the file something else and associate the original name with your random name. At a minimum use basename($_FILES['file']['name']).
As it's Windows, there is no real 777. If you're using chmod, check the Windows-related comments.
Check that the IIS Account can access (read, write, modify) these two folders:
E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\
C:\WINDOWS\Temp\
Try adding a path. The following code works for me:
<?php
if ( !empty($_FILES['file']) ) {
$from = $_FILES['file']['tmp_name'];
$to = dirname(__FILE__).'/'.$_FILES['file']['name'];
if( move_uploaded_file($from, $to) ){
echo 'Success';
} else {
echo 'Failure';
}
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './people.xml' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
is the important line it says you can't put the file where you want it and this normally means a permissions problem
check the process running the app (normally the webservers process for php) has the rights to write a file there.
EDIT:
hang on a bit
I jumped the gun a little is the path to the file in the first line correct?
Another think to observe is your directory separator, you are using / in a Windows box..
Add the IIS user in the 'dump' folders security persmissions group, and give it read/write access.
Create a folder named "image" with folder permission 777
<?php
move_uploaded_file($_FILES['file']['tmp_name'],"image/".$_FILES['file']['name']);
?>
We found using below path
{['DOCUMENT_ROOT'] + 'path to folder'
and giving everyone full access to the folder resolved the issue.
Make sure to not reveal the location in the address bar. No sense in giving the location away.

Uploading a image to a server + inserting filename to dB

The php:
//This is the directory where images will be saved
$target = "/images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$strListItemPic=(mysql_real_escape_string($_FILES['photo']['name']));
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). "
has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
The html:
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
It's breaking out and giving "Sorry, there was a problem uploading your file.";
I'm inserting $strListItemPic later in a MySQL statement, so I can echo the picture in a variable elsewhere.
Any glaring errors in this code? Does my $target have to be absolute paths?
PHP errors:
Warning: move_uploaded_file(/xxxxxx/lists/images/test.gif):
failed to open stream: No such file or directory in
/home/virtual/site48/fst/var/www/html/xxxxxx/lists/itemedit.php on line 22
Warning: move_uploaded_file(): Unable to move '/tmp/phpJ3v7HV' to
'/xxxxxx/lists/images/test.gif'
in /home/virtual/site48/fst/var/www/html/xxxxxx/lists/itemedit.php on line 22
Fixed:
Added enctype="multipart/form-data" to <form>
Removed / before images in $target
Errors don't have to glare in the code.
Errors being raised at the time the code gets executed.
And these errors have to be noted and investigated.
at least add these 2 lines into your code and run it again.
ini_set('display_errors',1);
error_reporting(E_ALL);
or get the error message produced by move_uploaded_file any other way.
Trying to answer your question without an actual error message would be useless waste of time.
Your apache sub directory where you write (move)images must be writable i.e have permissions to write files. since it looks like you are on Linux cd to the directory and change permissions with:
cd /the/parent/directory/to/directory/where/files/are/supposed/to/be
chmod 777 theimagefilesdir/
Be sure to read permissions and choose one that fits you as 777 is very permissive and can be impractical to production but I use it in my local machine :)
Please check that you are using enctype in form tag

Http File upload - Files over 25mb fail - PHP uploading script

I've been banging my head against this for 20+ hours now I would really appreciate some help!
I have simplified the problem here so the code is very simple. Basically this upload script works perfectly until I try to upload a file bigger than 25MB then it fails. PHP gives no errors.
index.htm
<form enctype="multipart/form-data" action="upload.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
upload.php
<?php
$target_path = "uploaded/";
$target_path = $target_path.basename( $_FILES['uploadedfile']['name']);
/***/highlight_string(print_r($_FILES, true)); //check array
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!";
}
?>
php.ini
[PHP]
post_max_size = 32M
upload_max_filesize = 32M
My host informed me that the upload limit on the server is 32MB. Ran phpinfo() & the variables in the ini are being changed. It is not a timeout issue (ran a 16mb upload when downloading a file - it took several minutes longer than the 25MB upload but still worked).
I have been spittin out the $_Files array as a string for error checking, heres what I get when it fails:
Array
(
[uploadedfile] => Array
(
[name] => 30.tif
[type] =>
[tmp_name] =>
[error] => 7
[size] => 0
)
)
There was an error uploading the file, please try again!
Any ideas? Tried it on different servers with the same problem.
According to this, it failed to write files to disk. Can you check quota/disk space/etc.?
memory_limit might also restrict the size of uploadable files.
Your error don't is for the size, the error code 7 is because the file "can't be save in the disk."
to more errors read: Upload code errors
Try change the directive "upload_tmp_dir" in php.ini file and check if is allow the upload of file: 'file_uploads = On'.
Thanks everybody, I'm sure now that it is a host problem, not a problem on my end - even though I've tried it on several hosts - I think it's pretty common for http post to be limited to around 25MB.
I have now set my uploader to take a maximum file size of 20MB, that should make it pretty safe on most hosts.

PHP move_uploaded_file() error?

I using following code and it is successfully uploading files on my local machine. It is showing "Successfully uploaded" on my local machine.
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded";
}
But when I used this code on my online server then it is not uploading file and just showing message "Not uploaded".
How can I know that what is the problem and how can I get the actual problem to display to the user ?
Edit the code to be as follows:
// Upload file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . "myFile.txt" );
if( $moved ) {
echo "Successfully uploaded";
} else {
echo "Not uploaded because of error #".$_FILES["file"]["error"];
}
It will give you one of the following error code values 1 to 8:
UPLOAD_ERR_INI_SIZE =
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE =
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL =
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE =
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR =
Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE =
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION =
Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.
Try this:
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/images/';
if (is_dir($upload_dir) && is_writable($upload_dir)) {
// do upload logic here
} else {
echo 'Upload directory is not writable, or does not exist.';
}
This will instantly flag any file permission errors.
Check that the web server has permissions to write to the "images/" directory
How can I know that what is the problem
Easy. Refer to the error log of the webserver.
how can I get the actual problem to display to the user ?
NEVER do it.
An average user will unerstand nothing of this error.
A malicious user should get no feedback, especially in a form of very informative error message.
Just show a page with excuses.
If you don't have access to the server's error log, your task become more complicated.
There are several ways to get in touch with error messages.
To display error messages on screen you can add these lines to the code
ini_set('display_errors',1);
error_reporting(E_ALL);
or to make custom error logfile
ini_set('log_errors',1);
ini_set('error_log','/absolute/path/tp/log_file');
and there are some other ways.
but you must understand that without actual error message you can't move. It's hard to be blind in the dark
move_uploaded_file() will return:
FALSE if file name is invalid
FALSE and issue a warning in the error log if the apache process does not have read/write permissions to source or destination directories
PHP Error Log
My php error log was at: /var/log/httpd/error_log and had these errors:
Warning: move_uploaded_file(images/robot.jpg): failed to open stream: Permission denied in /var/www/html/mysite/mohealth.php on line 78
Warning: move_uploaded_file(): Unable to move '/tmp/phpsKD2Qm' to 'images/robot.jpg' in /var/www/html/mysite/mohealth.php on line 78
move_uploaded_file() tries to move files from a temporary directory to a destination directory. When apache process tried to move files, it could not read the temporary or write to the destination dir.
Find which user is running Apache (Web Server)
Check which user is running the apache service by this command: ps aux | grep httpd. The first column is the user name.
Check Read Permission at Temporary Dir: Your can find the path to your temp dir by calling echo sys_get_tmp_dir(); in a php page. Then on the command line, issue ls -ld /tmp/temporary-dir to see if the apache user has access to read here
Check Write Permission at Destination Dir: issue ls -ld /var/www/html/destination-directory to see if the apache user has access to write here
Add permissions as necessary using chown or chgrp
Restart Apache using sudo service httpd restart
Do you checks that file is uploaded ok ? Maybe you exceeded max_post_size, or max_upload_filesize. When login using FileZilla you are copying files as you, when uploading by PHP wiritng this file is from user that runs apache (for exaplme www-data), try to put chmod 755 for images.
or run suexec and never have to change permissions again.
In php.ini search for upload_max_filesize and post_max_size. I had the same problem and the solution was to change these values to a value greater than the file size.
Please check that your form tag have this attribute:
enctype="multipart/form-data"
$uploadfile = $_SERVER['DOCUMENT_ROOT'].'/Thesis/images/';
$profic = uniqid(rand()).$_FILES["pic"]["name"];
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
{
$moved = move_uploaded_file($_FILES["pic"]["tmp_name"], $uploadfile.$profic);
if($moved)
{
echo "sucess";
}
else
{
echo 'failed';
}
}
On virtual hosting check your disk quota.
if quota exceed, move_uploaded_file return error.
PS : I've been looking for this for a long time :)
Please check permission "images/" directory
I ran into a very obscure and annoying cause of error 6.
After goofing around with some NFS mounted volumes, uploads started failing.
Problem resolved by restarting services
systemctl restart php-fpm.service
systemctl restart httpd.service

PHP Error - Uploading a file

I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:
<?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Dump Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000000" />
Select the File:<br /><input type="file" name="file" /><br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
I'm getting these errors:
Warning: move_uploaded_file(./test.txt) [function.move-uploaded-file]: failed to open stream: Permission denied in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './test.txt' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
Warning: Cannot modify header information - headers already sent by (output started at E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php:3) in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 4
PHP version 4.4.7
Running IIS on a Windows box. This particular file/folder has 777 permissions.
Any ideas?
OMG
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
Don't do that. $_FILES['file']['name'] could be ../../../../boot.ini or any number of bad things. You should never trust this name. You should rename the file something else and associate the original name with your random name. At a minimum use basename($_FILES['file']['name']).
As it's Windows, there is no real 777. If you're using chmod, check the Windows-related comments.
Check that the IIS Account can access (read, write, modify) these two folders:
E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\
C:\WINDOWS\Temp\
Try adding a path. The following code works for me:
<?php
if ( !empty($_FILES['file']) ) {
$from = $_FILES['file']['tmp_name'];
$to = dirname(__FILE__).'/'.$_FILES['file']['name'];
if( move_uploaded_file($from, $to) ){
echo 'Success';
} else {
echo 'Failure';
}
header('Location: http://www.mywebsite.com/dump/');
exit;
}
?>
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\phpA30E.tmp' to './people.xml' in E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\upload.php on line 3
is the important line it says you can't put the file where you want it and this normally means a permissions problem
check the process running the app (normally the webservers process for php) has the rights to write a file there.
EDIT:
hang on a bit
I jumped the gun a little is the path to the file in the first line correct?
Another think to observe is your directory separator, you are using / in a Windows box..
Add the IIS user in the 'dump' folders security persmissions group, and give it read/write access.
Create a folder named "image" with folder permission 777
<?php
move_uploaded_file($_FILES['file']['tmp_name'],"image/".$_FILES['file']['name']);
?>
We found using below path
{['DOCUMENT_ROOT'] + 'path to folder'
and giving everyone full access to the folder resolved the issue.
Make sure to not reveal the location in the address bar. No sense in giving the location away.

Categories