php file not uploading to temp directory - php

//uploadForm.html
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="browseFile">Filename : </label>
<input type="file" name="file" id="browseFile"><br>
<input type="submit" name="submit" value="Submit">
</body>
</html>
//upload_file.php
<?php
$allowedExt = array("png","jpg");
$temp = explode(".",$_FILES["file"]["name"]);
$extension = end($temp);
echo "uploading...";
if((($_FILES["file"]["type"]=="image/png") || ($_FILES["file"]["type"]=="image/jpg")) && ($_FILES["file"]["size"] < 1000000))
{
echo "success";
if($_FILES["file"]["error"] > 0)
{
echo "error in uploading" . $_FILES["file"]["error"]."<br>";
}
else
{
echo "<p>uploaded successfully</p>";
}
}
else
echo "invalid file" ;
echo $_FILES["file"]["name"]."stored in ".$_FILES["file"]["tmp_name"]."<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/".$_FILES["file"]["name"]);
echo "moved Successfully";
?>
When I try to echo the temp directory name , it is blank . The uploaded files are missing .
I dont get it in the MAMP/htdocs folder neither in /tmp/ directory .
I dont have uploads directory in /MAMP/htdocs/ .Wont the program create a directory if it does not exist ?

In your final instructions, you have $_FILES['name']['tmp_name'] instead of $_FILES['file']['tmp_name'].
By the way, you have a few errors in your script:
Even if someone uploads an invalid file, you show them an error message, but you still move it to the final place.
$_FILES["file"]["type"] is a value sent by the browser (ie: the client). A malicious attacker may sent you any kind of file and disguise it as a image/png, and you are trusting it. You cannot trust this value. Instead, you could use getimagesize, which returns you an array that has the mime type of the image (and is detected by the server (ie: by you). To detect the mime-type of non-images, you can use FileInfo, concretely finfo_file.
Also, the php script will not create your uploads folder if it does not exist, and instead will show an error (and do nothing). You must create this folder first, and make sure that the user running your php script (usually the same that is running your http server) has write permissions on that directory.
edit: You don't see any uploaded file in your temp directory because (quoting http://www.php.net/manual/en/features.file-upload.post-method.php):
The file will be deleted from the temporary directory at the end of
the request if it has not been moved away or renamed.

$allowedExt = array("png","jpg");
echo $temp = explode(".",$_FILES["file"]["name"]);
$extension = end($temp);
echo "uploading...";
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}

$_FILES["name"]["tmp_name"] does not exist, it should be $_FILES["file"]["tmp_name"]

Related

php simple upload files not working

I'm currently working on an extremely simplistic PHP file upload, but it fails to do anything at all. There is nothing in the specified directory.
PHP on the submit of my HTML form:
<?php
if ($_FILES["file"]["error"] > 0)
{
//error
echo "Something went wrong";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"/uploads/" . $_FILES["file"]["name"]);
}
?>
I suspect that something may be up with the fact that I'm using GoDaddy, since they've been quirky with php features in the past.
EDIT: Fixed underscore;
now I'm getting an actual error.
Warning: move_uploaded_file(/uploads/asd.docx) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/content/09/11461509/html/php/upload.php on line 11
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpSIA5Jv' to '/uploads/asd.docx' in /home/content/09/11461509/html/php/upload.php on line 11
You're running your code from a different folder "php", from what I've gathered by your error messages. Try running the code from the root of your server, and then use uploads as your uploading folder.
Also make sure the folder has the proper write permissions set. Usually 755 and sometimes 777 although 755 is a safer setting.
As per OP's original posted code
Missing underscore between $ and FILES
move_uploaded_file($FILES["file"]["tmp_name"],
---^
<?php
if ($_FILES["file"]["error"] > 0)
{
//error
echo "Something went wrong";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"/uploads/" . $_FILES["file"]["name"]);
}
?>
Please add the enctype in form tag as multipart/form-data and PHP code should as follows-
First make sure that your files has been uploaded successfully in temp directory, then try to debug upload path and finally file moving functionality to specific directory.
<?php
if ($_FILES["file"]["error"] > 0) {
//error
echo "Something went wrong";
} else {
// try echoing the following codes first-
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
// then try to debug upload path
// move_uploaded_file($_FILES["file"]["tmp_name"],"/uploads/" . $_FILES["file"]["name"]);
// take move_uploaded_file(); in a variable and then print_r($variable);
}
?>
I am referring you to read this post for upload problem the docx file using PHP.
Try this
<html>
<body>
<form action="" method="post"enctype="multipart/form-data">
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
?>
please write in form tag enctype="multipart/form-data"

Image uploading on window server through php error

i got a error in image uploading on window based server where it works well on localhost as well as in linux server.Firstly i manually create a folder named as photos in root directory & two files named as imageupload.php & index.php
where code is
index.php
<html>
<body>
<form enctype="multipart/form-data" action="imageupload.php" method="post">
Choose Picture:<input type="file" name="photo"/>
<input name="submit" type="submit" value="save"/>
</form>
</body>
</html>
imageupload.php
<?php
if(isset($_REQUEST['submit'])){
$target = "photos/";
$finallink = $target.basename($_FILES['photo']['name']);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $finallink))
{
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
}
?>
this code works well on localhost & as well as on linux server but i purchased a window based hosting & where as I'm getting error on running this code on window based web server is .
Sorry, there was a problem uploading your file.
How to fix it ? Is this issue of php code running on window based server or anything else? Thanks for your help in advance.
Try this code hope it will hlp you
if(isset($_REQUEST['submit'])){ move_uploaded_file($_FILES["photo"]["tmp_name"],
"upload/" . $_FILES["photo"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["photo"]["name"]; }
move_uploaded_file($_FILES["companylogo"]["tmp_name"],"companylogo/" . $_FILES["companylogo"]["name"]);
echo "Stored in: " . "companylogo/".$_FILES["companylogo"]["name"];

Cannot See Images Uploaded To A Folder On The Server

Hi, I have a problem with uploading files in my server. This is my code:
<?php
session_start();
$user=$_SESSION['user_level'];
Check if a file has been uploaded
if(isset($_FILES['fileToUpload'])) {
// Make sure the file was sent without errors
if($_FILES['fileToUpload']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('$host', '$username', '$pass', '$tbl_name');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
//$id= mysql_insert_id();
$name = $dbLink->real_escape_string($_FILES['fileToUpload']['name']);
$mime = $dbLink->real_escape_string($_FILES['fileToUpload']['type']);
$data = $dbLink->real_escape_string
(file_get_contents($_FILES['fileToUpload']['tmp_name']));
$size = intval($_FILES['fileToUpload']['size']);
// Create the SQL query
$query = "
INSERT INTO files (email,name,type,size,content)
VALUES ('$user','$name', '$mime', $size, '$data')";
// Execute the query
$result = $dbLink->query($query);}}
?>
<?php
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]);
?>
<?php
if ($_FILES["fileToUpload"]["error"] > 0)
{
echo "Apologies, an error has occurred.";
echo "Error Code: " . $_FILES["fileToUpload"]["error"];
}
else
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]
["name"]);
}
if (($_FILES["fileToUpload"]["type"] == "image/DOC")
|| ($_FILES["fileToUpload"]["type"] == "image/jpeg")
|| ($_FILES["fileToUpload"]["type"] == "image/png" )
&& ($_FILES["fileToUpload"]["size"] < 10000))
{
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]);
ECHO "Files Uploaded Succesfully";
echo'<script type="text/javascript">
window.location.href ="resume2.php"
</script>';
}
else
{
}
echo "Your Resume was Successfully Upload";
?>
I have a folder named "upload" wherein it will store all the files uploaded by the user. My objective is to store the file in mysql and in the "upload" folder. The storing of file works fine with no error messages but I can't see the uploaded file inside the "upload" folder. Thanks for your help!
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]
You are missing a trailing slash / after upload. Change it to:
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]
As it is, the file is being saved as a file name with the prefix upload in the public_html directory.
If possible you should use a relative path for portability, there is a good chance that simply
"upload/" . $_FILES["fileToUpload"]["name"]
...would suffice.
HOWEVER
you should not be using $_FILES["fileToUpload"]["name"] directly like this. Consider what would happen if the user sent the string ../index.php as the file name - the user would be able to overwrite your index.php file. Also, consider what would happen if two users uploaded a file named picture.jpg - the second upload would overwrite the first.
Instead you should use a name for the file that you create yourself - it is not safe to rely on user input like this.
You forget a slash:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload" . $_FILES["fileToUpload"]["name"]);
should be
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"/home/u152912911/public_html/upload/" . $_FILES["fileToUpload"]["name"]);
Also, check the return value for succes, don't assume it.
Please check the permission provided to the folder where you are storing the files.
if its working fine on local host and giving problem in online testing then ask the server-host to change the folder permissions to 777.

How to store photo upload in a PHP session?

I've built this webform wizard, consisting of several PHP pages. In this several pages users can fill in the form and the data gets temporarily stored in a session and at the last page the sessions are used to store all the data in the MYSQL database. Everything works fine with the exception of the uploaded file. Here is my code:
HTML: wizard_page2
<form name="registratieformulier" method="post" enctype="multipart/form-data" action="sw3.php">
<tr><td>Foto winkel uploaden: </td><td><input type="file" name="uploadfoto"/></td></tr><br /><br />
<tr><td><strong>Omschrijving van winkel:</strong></td> </tr><br />
<tr><textarea cols="50" rows="7" name="omschrijvingwinkel"></textarea></tr>
<input name="pkbedrijven" value="<?php echo($pkbedrijven); ?>" type="hidden" />
<input type="submit" name="stuurfoto" value="Verzenden" />
</form>
PHP: wizard_last_page
$_FILES['uploadfoto']['name'] = $_SESSION["naamfoto"];
$_FILES['uploadfoto']['tmp_name'] = $_SESSION["tijdelijk"];
$bn = $_SESSION["wn"];
$target_path = "../../winkels/$bn/";
$target_path = $target_path . basename( $_FILES['uploadfoto']['name']);
move_uploaded_file($_FILES['uploadfoto']['tmp_name'], $target_path)or die("There was an error uploading the file, please try again!");
$foto_path = "http://mywebsite.nl/winkels/$bn/".basename($_FILES['uploadfoto']['name']);
$omschrijving = $_SESSION["omschrijving"];
$add = "UPDATE winkelprofiel SET winkelomschrijving='$omschrijving', winkelfoto='$foto_path' WHERE fkBedrijvenID=$pkbedrijven ";
$query_upload = mysql_query($add) or die("De winkelfoto en omschrijving konden niet worden opgeslagen");
The $_FILES array only holds information about the file that has been uploaded in this request. If you do not save that file elsewhere within the same request, it will be removed by PHP at the end of the request. You cannot simply save $_FILES['uploadfoto']['tmp_name'] into the session and expect the file to still be there later, because it won't be. There's also no point in assigning the values in $_SESSION back into $_FILES, it won't bring the file back.
What you need to do:
if the upload was successful, move $_FILES['uploadfoto']['tmp_name'] somewhere else immediately
save the location you have moved it to into $_SESSION
do something with that file in $_SESSION at the end of your multi-page process (no need for $_FILES anymore at all)
have some mechanism in place to remove old uploaded files, in case the user abandons the session and the file never gets used
I think that the problem is, the file located at $_FILES['uploadfoto']['tmp_name'] will only be available when it is uploaded. Even you store the value in session, the file won't be there when you come to wizard_last_page. You need to handle uploaded files right away in the POST request.
So you need to move the file to $target_path or any certain temporary place when it's uploaded, then store the $target_path in the session so you can access to the file later on wizard_last_page.
Well, you can upload the file in one temporary location first. Then on the last page, once you submit the form, you can transfer the file to the desired location and then delete the temporary one.
$_SESSION['file'] = $_FILES["file"]["name"];
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/temp/" . $_FILES["file"]["name"]);
};
//This for the last page.
$file = file_get_contents("uploads/temp/".$_SESSION['file']);
file_put_contents("uploads/".$_SESSION['file'], $file);
I disagree with the accepted answer. There is a way to store all the images in the session array variable. You can use the "file_get_contents" function for storing the image.
Have a look at this:
$_SESSION['imgArrayFile'][] = $_FILES['file']; //Your file informations
$_SESSION['imgArrayName'][] = $_POST["ImgNewNamePlacowki"]; //new name for img
$_SESSION['ImgArrayAlt'][] = $_POST["ImgAltPlacowki"]; // alt tags if you use them
$_SESSION['obj_image_session'][] = file_get_contents($_FILES['file']['tmp_name']);
//above "file_get_contents" function - store image as a long string.
Regardless of what other think about using it for this purpose it can do the job for you.
There are several issues with storing large amounts of data in a session but if you images are small enough and you are aware of your settings limitation, then you will be just fine.
Save your file with
$file= $destination."/".$filename; //images/new.jpg
$fp=fopen($file,"w");
fwrite($fp,$_SESSION['obj_image_session'][$index]);
EXAMPLE FROM MY (WORKING) PROJECT:
<?php
//$galery_img_folder = "your/new/image/destination";
foreach($_SESSION['imgArrayFile'] as $index => $name){
if($_SESSION['imgArrayName'][$index]!=""
&& $_SESSION['ImgArrayAlt'][$index]!=""
&& $_SESSION['obj_image_session'][$index]!=""
){
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_SESSION['imgArrayFile'][$index]["name"]);
$extension = end($temp);
if ((($_SESSION['imgArrayFile'][$index]["type"] == "image/gif")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/jpeg")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/jpg")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/pjpeg")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/x-png")
|| ($_SESSION['imgArrayFile'][$index]["type"] == "image/png"))
&& ($_SESSION['imgArrayFile'][$index]["size"] < 104857600)
&& in_array($extension, $allowedExts))
{
if(isset($_SESSION['imgArrayName'][$index]) && $_SESSION['imgArrayName'][$index]!=""){
$rename = $_SESSION['imgArrayName'][$index];
$rename = $rename.".".end($temp);
}
if ($_SESSION['imgArrayFile'][$index]["error"] > 0)
{
echo "Return Error Code: " . $_SESSION['imgArrayFile'][$index]["error"] . "<br>";
}
else
{
$size = display_filesize($_SESSION['imgArrayFile'][$index]["size"]);
echo "Upload: " . $_SESSION['imgArrayFile'][$index]["name"] . "<br>";
echo "Type: " . $_SESSION['imgArrayFile'][$index]["type"] . "<br>";
echo "Size: " . ($size) . "<br>";
echo "Temp file: " . $_SESSION['imgArrayFile'][$index]["tmp_name"] . "<br>";
if (file_exists($galery_img_folder."/".$rename))
{
$error[] = ''.$rename.' <span class="error" id="error"> this name exsists </span>';
}
else
{
$_FILES["file"]["tmp_name"]=$_SESSION['imgArrayFile'][$index]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $galery_img_folder."/".$rename);
//now make use of the file_get_content variables
$file= $galery_img_folder."/".$rename;
$fp=fopen($file,"w");
fwrite($fp,$_SESSION['obj_image_session'][$index]);
}
}
}
}
else
{
$error[] = '<span class="error" id="error"> Niewłaściwy plik </span>';
$maxsixe = display_filesize(104857600);
echo "Size: " . ($maxsixe) . "<br>";
}
}
}//end foreach ! ! !
}//end dodawanie zdjecia
?>
Of course you will have to make some small modifications to make it work with your project, but my point was to show you that it's possible.
Have a great day and happy coding !

Issues with uploading PDF files using PHP

I am encountering a strange problem with my script which I am testing to upload PDF files. I can sucessfully upload some pdf files while not the other files, even though they are all pdfs and have .pdf as extension. Can anyone throw some light on this after going thtough my code
HTML PART:
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="file" name="upload" /><br />
<input type="submit" name="submit">
PHP PART:
if(isset($_POST['submit'])){
$output_form = 0;
if (($_FILES["upload"]["type"] == "application/pdf")
&& ($_FILES["upload"]["size"] < 80000)){
if (file_exists("upload/" . $_FILES["upload"]["name"]))
{
echo $_FILES["upload"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["upload"]["tmp_name"],
"upload/" . $_FILES["upload"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["upload"]["name"];
}
}else{
echo 'Invalid File';
}
}
For some files I am getting the output, stored in output. For the others I am getting the message 'Invalid File'.
Thanks
your code above seems to have a condition that if the filesize is greater than 80000 then it should throw the 'Invalid file' error? What size are the ones that fail? I'd be willing to bet if you comment out that condition it'll work
Had the same issues.
Found that the file type could also be application/x-octet-stream
So you need to check for that in the same statement that you are checking the file size.
Something like this:
if (($_FILES['pdfUpload']['type'] == "application/pdf")
|| ($_FILES['pdfUpload']['type'] == "application/x-octet-stream")
&& ($_FILES['pdfUpload']['size'] < 9000000)) //Much larger and we get a timeout during transfer
My 2 cents worth

Categories