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
}
Related
I have a form from which I gather quite a bit of information and am then required to upload Multiple Files.
All other aspects of the form are now working perfectly thanks to Devi on this forum. And to try and focus on only the one problem I now have I have decided to start the new thread: The previous / old thread can be viewed Insert into one Table, while updating another & File Upload
My problem now is to actually get the files to upload. My form is working in two parts. Part one is the basic HTML layout which then has the method pointing to the PHP file which handles the writing of info to the database tables.
The form has the following code for each file upload (There are 4 uploads, each for a different file reference, ie. License Document, Renewal Document, Identity Document, Other Documents):
<div class="form-group">
<label>Permit Renewal :</label>
<div class="input-group">
<label>
<input type="radio" class="minimal" value="0" <?php echo ($permit_renewal=='No')?'checked':'' ?> name="permit_renewal">
No
</label>
<label>
<input type="radio" class="minimal" value="1" <?php echo ($permit_renewal=='Yes')?'checked':'' ?> name="permit_renewal">
Yes
</label>
</div>
</div>
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="scanned_permit_renewal">Attach File</label>
<input type="file" id="scanned_permit_renewal" name="scanned_permit_renewal">
<p class="help-block">Select a file to link to this outlet, the file name must be prefixed with the Outlet. E.g. 102987 - License 2016</p>
</div>
</div><!-- /.form-group -->
And the relevant processing part is
if (isset($_FILES["file"]["name"])) {
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name){
$file_name = $key.$_FILES['file']['name'][$key];
$file_size =$_FILES['file']['size'][$key];
$file_tmp =$_FILES['file']['tmp_name'][$key];
$file_type=$_FILES['file']['type'][$key];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
}
if($res1){
echo "Records added / updated successfully.";
}
header("refresh:2;url=../outlet_capture.php");
// close connection
$link->close();
I have also confirmed my rot directory and ensured that there is an /uploads/ folder present.
If don't see the definition, but it MUST have the enctype like
The $_FILES variable works with the name of the field in the form.
On your example it should be scanned_permit_renewal. And for access it from the PHP when the form was sent you should use $_FILES['scanned_permit_renewal'].
You uses on the foreach
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name)
Which seems to be the problem.
IMHO you should use this:
foreach($_FILES as $fieldNameInTheForm => $file)
{
$file_name = $fieldNameInTheForm .$file['name'];
$file_size =$file['size'];
$file_tmp =$file['tmp_name'];
$file_type=$file['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
You have done everything right, you are simply not pointing to the right input names...
$_FILES['file'] does not exist. You should use $_FILES['scanned_permit_renewal'] instead just like when you access $_POST, the key is the name of the form field.
Actually, you are looping through the $_FILES['file'] as if you had put many inputs with the name file[*something*]. If you question is complete, you should simply be using
if (isset($_FILES["scanned_permit_renewal"])) {
$file_name = $_FILES['scanned_permit_renewal']['name'];
$file_size =$_FILES['scanned_permit_renewal']['size'];
$file_tmp =$_FILES['scanned_permit_renewal']['tmp_name'];
$file_type=$_FILES['scanned_permit_renewal']['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
To answer your comment, an efficient way of doing it could be 2 ways. First, which will require no PHP changes, rename your input fields to file[scanned_permit_renewal] this will let you use the foreach as you seem to intend.
Another way could be to use an array of possible inputs:
$file_inputs = array('scanned_permit_renewal','my','other','documents');
foreach($file_inputs as $input_name){
if (isset($_FILES[$input_name])) {
$file_name = $input_name.$_FILES[$input_name]['name'];
$file_size =$_FILES[$input_name]['size'];
$file_tmp =$_FILES[$input_name]['tmp_name'];
$file_type=$_FILES[$input_name]['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
}
A third way could be to just loop through the $_FILES array. But I wouldn't do that, as there could be anything there. You'll prefer to filter on your wanted files.
For uploading multiple files, input field should be:
<input type="file" id="scanned_permit_renewal" name="scanned_permit_renewal[]" multiple="multiple">
processing part:
if (count($_FILES["scanned_permit_renewal"]["name"]) > 0) {
foreach($_FILES['scanned_permit_renewal']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['scanned_permit_renewal']['name'][$key];
$file_size =$_FILES['scanned_permit_renewal']['size'][$key];
$file_tmp =$_FILES['scanned_permit_renewal']['tmp_name'][$key];
$file_type=$_FILES['scanned_permit_renewal']['type'][$key];
$file_to_save = date("Ymd_his") . "_" . $file_name;
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" .$file_to_save;
//echo $new_file;
if(move_uploaded_file($file_tmp,$new_file)){
// update database
$query = "UPDATE `table` SET `field_name` = '".$file_to_save."' WHERE ..... ";
}
}
}
I recently noticed on my website that users weren't able to upload profile pictures on mobile. So I copied all of the required HTML and PHP code from the root directory. The location where the profile pictures are moved was also modified so the pictures get uploaded to the right place. Now when I test it out and try to upload a profile picture using Safari for iOS, I get this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /home5/bobcatss/public_html/mobile/profile.propic.php on line 18
Here is the form the user submits:
<div class="propic"><form method="post" action="profile.propic.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Upload a profile picture <br><input name="file" type="file" id="file"/><br>
<input type="submit" value="Upload">
</form></div>
And this is the script that processes the image:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("../config.php");
session_start();
// Where the file is going to be placed
$target_path = "../propics/";
$filename = $_FILES["file"]["name"];
$limit_size=100000;
$temp = explode(".", $filename);
$extension = end($temp);
$info = getimagesize($_FILES["file"]["tmp_name"]); //Line 18
$allowed_types = array(IMG_GIF, IMG_JPEG, IMG_PNG, IMG_JPG);
if (in_array($info[2], $allowed_types))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
exit;
}
else
{
if (file_exists("../propics/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../propics/" . $_FILES["file"]["name"]);
try {
//insert into database
$stmt = $db->prepare('UPDATE users SET propic = :propic WHERE username = :username') ;
$stmt->execute(array(
':propic' => $filename,
':username' => $_SESSION["USER"]
));
//redirect to profile page
header("Location: profile.php?msg=Profile picture upload complete");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
}
else
{
echo "Invalid file";
}
?>
I emailed the image to myself and tried uploading it from my laptop but it gave me the same error.
I know this is old but this has just happened to me as well and I have bumped into this trying to figure out what happened. If you were using 3G connection the request may have taken longer than MAX_REQUEST_TIMEOUT so it probably failed ( duplicate here )
//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"]
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 !
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