i want to upload an image file from my client PC (i.e. localhost) to a directory located on remote server (i.e. godaddy.com). How can i do that using PHP ?
i have tried uploading from localhost to directory on the localhost itself. it works fine there but doesn't works for remote server.
below is html code:
<html>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data">
Browse for File to Upload : <br>
<input name="file" type="file" id="file"><br>
<input type="submit" id="u_button" name="u_button" value="Upload the file">
</form>
</body>
And below is my PHP code:
<?php
$file_result = "";
if($_FILES['file']['error'] > 0){
$file_result .= "No File uploaded or invalid File ";
$file_result .= "Error Code: ".$_FILES["file"]["error"]."<br>";
}
else{
$file_result .=
"Upload:" . $_FILES["file"]["name"]."<br>".
"Type:" . $_FILES["file"]["type"] . "<br>" .
"Size:" . ($_FILES["file"]["size"]/1024) . " Kb<br>" .
"Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],
"onenetwork.ddns.net/api/profile_images/" . $_FILES["file"]["name"]);
$file_result .= "File uploaded successfully";
}
?>
Below is the error i get:
Warning: move_uploaded_file(onenetwork.ddns.net/api/profile_images/hala-
madrid-wallpaper-hd-wallpapers.jpg): failed to open stream: No such file
or directory in C:\xampp\htdocs\upload_file.php on line 16
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpBFF0.tmp'
to 'onenetwork.ddns.net/api/profile_images/hala-madrid-wallpaper-hd-
wallpapers.jpg' in C:\xampp\htdocs\upload_file.php on line 16
i expect out to be file successfully uploaded.please help me out.
You can't move the file to onenetwork.ddns.net/api/profile_images/hala-madrid-wallpaper-hd-wallpapers.jpg. That is a URL, you need to specify a proper directory PATH on the server. Usually it would be something like
dirname(__FILE__).'/api/profile_images/'.$_FILES["file"]["tmp_name"]
You cant just run the script on your local xampp install and expect it to be able to upload to a server on the internet. You need to upload your upload_file.php script to the server behind onenetwork.dns.net and run it from http://onenetwork.dns.net/upload_file.php
There are a lot of security concerns with doing this - you need to block people from being able to upload the wrong type of file (check the MIME type of the file) and you need to make sure they can't upload to directories that you dont want them to. To use this on an internet server, you will have to spend some time making it secure first unless you want to be hacked.
I'm trying make a file upload using PHP. To do it I'm using $_FILE but I can't understand why does not works. Looking for solutions I'm found some suggestion to use $_FILE, but still can't do this works. To I see if upload works I'm using Postman of Chrome. I'm using Ubuntu with LAMP.
How could I do it ?
<?php
$arquivo = isset($_FILES["file"]) ? $_FILES["file"] : FALSE;
if(!$arquivo) {
echo "You can not access this file directly!";
}else{
$diretorio = "/home/fernando/Imagens/";
if (move_uploaded_file($arquivo["tmp_name"], $diretorio.$arquivo["name"])) {
echo "File upload ok!";
}else{
echo "File not upload!";
}
}
?>
Exception
<br />
<b>Warning</b>: move_uploaded_file(/home/fernando/Imagens/avatar_empresa.jpg): failed to open stream: Permission denied in
<b>/var/www/TelefonesUteis/ws/add_file.php</b> on line
<b>12</b>
<br />
<br />
<b>Warning</b>: move_uploaded_file(): Unable to move '/tmp/phpq9AlVw' to '/home/fernando/Imagens/avatar_empresa.jpg' in
<b>/var/www/TelefonesUteis/ws/add_file.php</b> on line
<b>12</b>
<br />
Postman
Your script doesn't have permissions to add and/or execute files in /home/fernando/Imagens/. Your will have to use chmod:
chmod -R 775 /home/fernando/Imagens
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
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
Warning: move_uploaded_file(/home/site/public_html/wp-content/themes/mytheme/upgrader.zip) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/site/public_html/wp-content/themes/mytheme/uploader.php on line 79
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phptempfile' to '/home/site/public_html/wp-content/themes/mytheme/upgrader.zip' in /home/site/public_html/wp-content/themes/mytheme/uploader.php on line 79
There was a problem. Sorry!
Code is below for that line...
// permission settings for newly created folders
$chmod = 0755;
// Ensures that the correct file was chosen
$accepted_types = array('application/zip',
'application/x-zip-compressed',
'multipart/x-zip',
'application/s-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type)
{
$okay = true;
break;
}
}
$okay = strtolower($name[1]) == 'zip' ? true: false;
if(!$okay) {
die("This upgrader requires a zip file. Please make sure your file is a valid zip file with a .zip extension");
}
//mkdir($target);
$saved_file_location = $target . $filename;
//Next line is 79
if(move_uploaded_file($source, $saved_file_location)) {
openZip($saved_file_location);
} else {
die("There was a problem. Sorry!");
}
It seems that you will need to add write permissions to the folder that the zip file is being moved to. I am assuming you are using Linux and apache. You can change the owner of the upload folder to apache and give it 770 permissions. An INSECURE alternative is to not change the owner of the folder and change the permission to 777, which like I said is not secure.
The following article provides some more info in addition to some techniques to secure the second alternative I provided:
http://www.mysql-apache-php.com/fileupload-security.htm
If you have access to your server, have a look at you .htaccess file and php.ini folder to check what files are allowed to be uploaded. If you are hosting through a company, you should have access to an online control panel that has a php settings section.
Try to use the chmod function before the move script, and add write permission to that folder.