uploading image to server using php - php

in the following code ,i am trying to upload an image to server . there is a folder 'images ' on the server. whenever i am clicking the 'ok' button ...it gives an error " there is problem in uploading file"... where is the problem in my code?
html-----------------------------------------
<form method="post" action="newproduct.php" enctype="multipart/form-data">
Item Image:<input type="file" name= "photo" size="40" />
Description:<textarea name="description" cols="40" rows="1"></textarea>
<input name="submit" type="submit" value = "Submit" />
</form>
php-------------------------------------------------------
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
$description =$_POST["description"];
//checking for empty values
if (empty($pic) || empty($description))
{
echo "Please enter all field values.";
}
else
{
//Connecting to database server
//Connecting to database
//INSERT Query
$SQLstring = "INSERT INTO items VALUES(null,'$pic' ,'$description')";
$QueryResult = #mysqli_query($DBConnect, $SQLstring)
or die ("<p> Unable to execute the query. </p>".
"<p> Error code " . mysqli_errno($DBConnect) . ":" . mysqli_error($DBConnect))."</p>";
if(move_uploaded_file($_FILES['photo']['name'], $target))
{
echo "The file has been added to the directory";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
mysqli_close($DBConnect);
}
?>

The images folder needs to have 777 permissions on it. By default the permissions are 655, and PHP does not have permissions to upload/move/copy a file outside the current folder it is in (subdirectories count as different folder)

you can't do that... you don't update a photo like that in Javascript... (with ajax..)
It is not going to work like that...
But... you can fake this...
You have to submit that post somehow...
You have several solutions: use a flash to fake upload ajax or an iframe..
You can also use jQuery .. he will do all the stuff for you..
Here are some demo & download links:
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/
http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/
http://www.fyneworks.com/jquery/multiple-file-upload/
If you want to move the uploaded file you have to move the "tmp_name" with the new name.. like
if (!move_uploaded_file($_FILES['photo']['tmp_name'], $path.$_FILES['photo']['name']))
echo 'CANNOT MOVE {'.$_FILES['photo']['name'].'}' . PHP_EOL;
When you upload your file, apache takes care of it and by default is in /tmp (if you use linux... I don't know in windows case)..
P.S: for your script's performance you should use ' ' instead of " " for strings.. when you use " " PHP is checking every " "(string) for variables == more operations to do.. and ' ' are skipped

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"

php file not uploading to temp directory

//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"]

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.

Get name of Multiple File upload files

I have been trying to upload multiple files into a folder and save the names in a database table. Here's the code: I need to get the names of those uploaded files. I know my code is crap :(
Is there a way to loop through uploading those files and still return the file names?
I need those names to be able to insert them into mysql table.
Thanks for your assistance.
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="pic1" type="file" /><br />
<input name="pic2" type="file" /><br />
<input name="pic3" type="file" /><br />
<input name="pic4" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And the PHP script is below:
<?php
$target = "uploads/";
$target = $target . basename( $_FILES['pic1']['name']);
$target = $target . basename( $_FILES['pic2']['name']);
$target = $target . basename( $_FILES['pic3']['name']);
$target = $target . basename( $_FILES['pic4']['name']);
$pic1 =($_FILES['pic1']['name']);
$pic2 =($_FILES['pic2']['name']);
$pic3 =($_FILES['pic3']['name']);
$pic4 =($_FILES['pic4']['name']);
$con = mysql_connect("localhost", "root", "");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("people", $con);
$sql="INSERT INTO mtpupload (name, age, pic1, pic2, pic3, pic4 )
VALUES('$_POST[name]','$_POST[age]','$pic1', '$pic2', '$pic3', '$pic4')";
//---------Here, I want to insert all the pictures----------//
if(move_uploaded_file($_FILES['pic1']['tmp_name'], $target)) {
//do nothing
}
if(move_uploaded_file($_FILES['pic2']['tmp_name'], $target)) {
//do nothingelse{
}if(move_uploaded_file($_FILES['pic3']['tmp_name'], $target)) {
//do nothing echo "Sorry, the image was not moved from temp folder.";
}if(move_uploaded_file($_FILES['pic4']['tmp_name'], $target)) {
//do nothing
echo "The was a problem uploading one of your images.";
}
//--------------Ends here---------------------//
if (!mysql_query($sql,$con)){
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
UPDATE: turns out that this code is working but only saving one image in the folder. I think my move_uploaded_file is wrong. Any pointers?
Thanks again for your help.
Maybe this is helpful, using an array with the files field names and foreach:
$fields = array('pic1', 'pic2', 'pic3', 'pic4');
$fileNames = array();
foreach($fields as $field)
{
$file = $_FILES[$field];
# you can now process each file on it's own.
$fileNames[$field] = $file['name']; # store all names into an array
...
}
Thanks folks for your suggestions, I finally got it working. I was using $target variable in many places. Renaming it to different variable helped.
What about this:
foreach ($_FILES as $file) {
echo $file['name']; // File name of file on user's computer
echo $file['tmp_name']; // Full path to the file on the server
}

Categories