PHP move_uploaded_file() failing on host - php

I have a script that uploads some files through php's move_uploaded_file().
Tested on my localhost it works fine. The problem arises when trying to do the same thing on a host. I already red all the topics in that matter here - but none of them solved my problem.
CODE:
<?php
$folder = 'img';
if (isset($_FILES['test'])) {
if (is_writable($folder))
echo 'Writable';
else
echo 'IMG is not writable';
$tmp_name = $_FILES['test']['tmp_name'];
$name = $_FILES['test']['name'];
if (move_uploaded_file($tmp_name, $folder . '/' . $name)) {
echo 'File was uploaded';
}
else {
echo 'File was not uploaded';
}
}
else {
echo 'No file - no operation';
}
?>
<html>
<body>
<form action="" enctype="multipart/form-data" method="POST">
<input type="file" name="test" />
<input type="submit" value="Test" />
</form>
</body>
</html>
MESSAGE is as follows:
Writable
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\WINDOWS\Temp\php9E75.tmp' to 'img/20130113_114901.jpg' in F:\hshome\ctc-ultralife\ultralife.com\new\admin\index_files\function\test2.php on line 11
File was not uploaded
Folder seems writable. Even if the file is not uploaded, it is created with the specified name in the folder (even if it is an empty file).
I do not know the absolute path of the server - it is not mine.
Your help will be much appreciated.
Thanks in advance.

Warning: complete stab in the dark. I don't know if this is the case, as I don't work on Windows servers.
It may be that the / needs to be a \. I don't think Windows handles the slash being the other way. That would explain why it can find your directory, but not the file within it.

I think you have to give an absolute path to the move_uploaded_file function.
EDIT:
If you don't know the absolute path, you can use the __DIR__ constant to make up an absolute path.
Assuming you've the img folder in the function folder, you can write something like this:
$fullPath = __DIR__ . '/img/' . $name;
if (move_uploaded_file($tmp_name, $fullPath)) {
echo 'File was uploaded';
} else { // ... }
In order to understand the real problem, you've to look into the error log.

Related

PHP move_uploaded_file results in error #1

I try to upload a file to an external server based on this code: https://www.w3schools.com/php/php_file_upload.asp .
On my local machine everything works fine but when uploading the exact same script to an external server it won't work anymore. When debugging with:
$_FILES["fileToUpload"]["error"]
I get an Error #1 in return altough im running the same php.ini as on my local machine. The uploads/ folder exists and the user www-data has also permissions to write it. I proofed this by running file_put_contents("uploads/test.txt", "working");. The only thing I could think of is the PHP Version difference (Local: 7.2.5; External: 7.2.19) or maybe a missing php module?!
It would be great if someone could help me solving this.
Try with full path using $_SERVER['DOCUMENT_ROOT'] also try to create recursively your folders using mkdir with 3rd parameter set to true (if not exists your path), increments your upload_max_filesize as suggested by Andreas into comments... here is a pseudo working example...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form name="form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Upload File: <input type="file" size="30" id="fileToUpload" name="fileToUpload">
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/var/www/html/";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, 0755, true);
}
if ((isset($_FILES['fileToUpload']['name'])) && (!empty($_FILES['fileToUpload']['name']))) {
$temp_name = $_FILES['fileToUpload']['tmp_name'];
$file_name = $_FILES['fileToUpload']['name'];
$file_path = $upload_dir.$file_name;
$upload_process = move_uploaded_file($temp_name, $file_path);
#chmod($file_path,0755);
}
if ((isset($upload_process)) && ($upload_process == TRUE)) {
echo "File Uploaded With Success...";
}
if ((!isset($upload_process)) || ($upload_process == FALSE)) {
echo "Please, Upload some File...";
}
?>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
I hope this helps.
OK, i was dumb. I changed the wrong php.ini file. For anyone who experiences similar issues you can check the location of the php.ini file and if it's loaded by PHP with:
$inipath = php_ini_loaded_file();
if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
Hope this helps.

File upload in php not working on remote server

Here is the code which I am using
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br><br>
<input type="submit" value="submit" name="submit">
</form>
PHP code :
<?php
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$location = "/var/www/tmp/";
if(move_uploaded_file($tmp_name, $location.$name)){
echo 'File uploaded successfully';
} else {
echo 'You should select a file to upload !!';
}
?>
I checked the permissions of the folder as well as checked the php.ini file but still always I am getting 'You should select a file to upload '
Can anybody please help me out on this issue ?
Thank you so much!
Give the full path of your file here
$location = "var/www/tmp/";
I think it will work. If its ok then store your servername in a variable and pass there.
Your Location should be like this:
// document root will give you the server root then you can add any directory after that (in your case its tmp I guess)
$location = $_SERVER['DOCUMENT_ROOT'] . '/your_preferred_dir/'
note: when you mention your preferred location you will have to make
sure that this location should exists otherwise it will cause error.
And not hardcoded as yours because it can change from server to server.
Hope this helps...

move_uploaded_file() showing successful but not working

I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';

PHP Upload Script not Functioning Properly with New Host

I have set up a php script which creates a directory and uploads a file to that directory. My issue is that when I use the script to create the directory, the file will not upload entirely. I ran the exact same script on a different host and the upload process works just fine. Plus, if I manually create the upload directory and apply chmod 777 via ftp then the transfer works just fine. Could there be some sort of a setting with the hosting provider that needs to be altered to allow the function to work just right?
Here is the upload form:
<form action="/uploadFile.php" method="post"
enctype="multipart/form-data">
<label for="img_preview">Preview Image:</label>
<input type="file" name="img_preview" id="img_preview" />
<br />
<input type="hidden" name="id" value="newDirectory" />
<input type="submit" name="submit" value="Upload Flyer" />
</form>
Here is my PHP script (uploadFile.php):
$thisdir = getcwd();
$new_dir = $_POST['id'];
$full_dir = $thisdir . "/upload/" . $new_dir;
function chk_dir($full_dir) {
if(is_dir($full_dir)) {
echo 'welcome back';
} else {
return mkdir($full_dir);
}
}
chk_dir($full_dir);
chmod($full_dir, 0777);
?>
<?php
//upload image
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
}
//set image restrictions
?>
<?php
if ((($_FILES["img_preview"]["type"] == "image/gif")
|| ($_FILES["img_preview"]["type"] == "image/jpeg")
|| ($_FILES["img_preview"]["type"] == "image/pjpeg"))
&& ($_FILES["img_preview"]["size"] < 80000))
{
if ($_FILES["img_preview"]["error"] > 0)
{
echo "Please only upload an image for previewing (jpg or gif)...<br>
Also, check to make sure the filesize is less than 8MB" . $_FILES["img_preview"]["error"] . "<br />";
}
else
{
//check the image into new directory
if (file_exists("upload/". $new_dir ."/". $_FILES["img_preview"]["name"]))
{
echo "It seems that " . $_FILES["img_preview"]["name"] . " already exists.";
}
else
{
move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"]);
echo "image file has transferred successfully!";
}
}
}
else
{
echo "Invalid file please contact for assistance.";
}
?>
Also, when I run the script no errors are produced and the file echos "image file has transferred successfully!" but then when I check for the file in the new location it is completely void. Thank you for your time in this issue.
First of all, your script has a security hole. Never use passed $_POST data to create system directories. And never use 0777 for anything.
The move_uploaded_file() returns false on a failure and you would still get your success message even if it failed (in your code)
Turn on display_errors and error logging and try again.
Looks like your question already contains the answer(the upload works when you create the directory via FTP).
I guess the new server has safe_mode enabled, so it will check the UID of the fileowners on file-operations.
What happens:
your script creates a directory, owner will be the webserver
your script(owner of the script usually is the ftp-user) tries to chmod the directory
the script(owner:ftp) cannot chmod the directory(owner:webserver) , because the UIDs are different.
solution: use ftp_mkdir() for creation of directories.
you have used move_uploaded_file() independently. If it returns false then also sucsess message will be printed.
Try
if ( move_uploaded_file($_FILES["img_preview"]["tmp_name"],
"upload/" . $_POST['id'] . "/" . $_FILES["img_preview"]["name"])) {
echo "sucess";
}else{
echo "fail";
}
After that you will get what is the main problem. Also use debugging point by
print_r($_FILES) before move_uploaded_file().
This may not be the answer to your question, but still it's worth your attention, I hope. Don't rely on the type of the file sent via $_FILES, this is just the mime-type sent by the browser as far as I remember, it can be easily compromized. Use getimagesize() function to get true image type as well as height/width.
Same goes for the source file name, but that shouldn't pose a security hole.

upload image in php by its url

i have this form to upload images:
<form method="post" action="upld.php" name="insertForm" enctype="multipart/form-data">
Image name:<br />
<input type="text" name="iname" /><br />
<input type="file" name="file" />
<input type="submit" name="upload" value="Upload" />
</form>
and here is the upld.php
<?php
$db_name = "DB_name";
$table_name = "tble";
$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
$db = mysql_select_db($db_name, $connection) or die(mysql_error());
if(isset($_POST['upload'])){
if (($_FILES["file"]["error"] > 0))
{
echo "<h3> Error in File! </h3>";
}
else
{
if ((file_exists("images/" . $_FILES["file"]["name"])) )
{
echo "<h3> file not exsists!</h3>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images/" . $_FILES["file"]["name"]);
//$id=mysql_insert_id();
$time=strftime("%Y-%m-%d %H:%M:%S", time());
$img_name=$_POST['iname'];
$img=$_FILES["file"]["name"];
$sql="INSERT INTO $table_name VALUES('{$img}','{$time}','{$img_name}')";
$result=mysql_query($sql,$connection);
mysql_close($connection);
echo "<h3>uploaded successfully</h3>";
}
}
}
echo "<br><br><a href='GalleryAdmin.php'>GO back to Admin Gallery</a>
";
?>
the problem is:
when i run it always say me file not exsist, acording to this if
if ((file_exists("images/" . $_FILES["file"]["name"])) )
{
echo "<h3> file not exsists!</h3>";
i have the images folder with upld.php in the same folder
what would you guess is the problem?
I think you have a slight logical error
file_exists("images/" . $_FILES["file"]["name"])
Will return true if the file exists in the images folder (my guess would me if somebody already uploaded it). But, based on your log statement, what you want is
!file_exists("images/" . $_FILES["file"]["name"])
OK so you uploaded your file. But, what you checked was if it was in say "images/my.jpg". At this point its in tmp_name, in your tmp directory, most likely so, no it would always not exist at this point as the file is only in a temporary name, you need to check its in your temp location, move it, and then check if its in images surely?
First:
PHP uploads the file to a temp directory. This is the file you need to move to your images/ folder. You find the file in this location on your server:
$_FILES['file']['tmp_name']
This is the file on which you want to run file_exists to make sure the upload completed successfully. So:
if (file_exists($_FILES['file']['tmp_name']) {
// File upload successful. Now move file to your directory.
move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]);
// Now do the database stuff here.
// ...
} else {
// Nothing was uploaded and something is wrong!
}
Secondary:
Your code
file_exists("images/" . $_FILES["file"]["name"])
will return TRUE, and therefore (in your code) it will say that there are no file. That's a logical error on your part.
Try:
!file_exists("images/" . $_FILES["file"]["name"])
instead.
Third:
Make sure that the file to which you move the file (images/) have the proper chmod. It needs 775 for it to be possible to create files into. This is made via the ftp program.
Read more here: CHMOD tutorial
You will also need to move the file from the tmp dir to images before checking if it's there with file_exists.
Please use move_uploaded_file before you check if the file exists;)
Otherwise try this:
1.) error_reporting(E_ALL);
2.) chmod the images directory (775), right mouse click on directory

Categories