I have a file upload form set up with the HTML5 multiple attribute.
However, the form still only uploads a single file. Do i need to create some sort of a looping function in the php or is there another way of doing this?
Here's my code...
form:
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="file[]" id="file" />
<input name="submit" type="submit" value="Submit" />
</form>
php:
<?php
if(isset($_POST['submit'])) {
foreach($_FILES['newsImage'] as $file){
if ((($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
}
}
?>
I believe your field should be
<input type="file" multiple="multiple" name="files[]" />
And then in PHP:
<?php
foreach($_FILES['files'] as $file){
// Handle one of the uploads
}
?>
for ($i = 0; $i < count($_FILES['newsImage']['name']); $i++) {
// handle upload
}
I believe this code could serve the purpose.
It loops through the $_FILES array and creates an array with key => value pair of all the attributes for for each file.
$temp = array();
foreach ($_FILES['file'] as $key => $value) {
foreach($value as $index => $val){
$temp[$index][$key] = $val;
}
}
<?php
include 'db.php';
extract($_POST);
extract($_POST);
if(isset($submit))
{
$count = count($_FILES['image']['name']);
for($i=0;$i<$count;$i++)
{
$fname = $_FILES['image']['name'][$i];
$file_tmp = $_FILES['image']['tmp_name'][$i];
$file_size = $_FILES['image']['size'][$i];
$file_type=$_FILES['image']['type'][$i];
echo $file_size,$file_type;
$target = "img/".$fname;
move_uploaded_file($file_tmp,$target);
echo "uploaded succ !"."<br>";
}
}
?>
Related
I'm doing the upload multimage files and rename it successfully.
However, I don't know, How to get the name of file that I rename it with function move_uploaded_file(). I want to get the newname to insert to mySQL
if(isset($_POST['submit']))
{
$count=count($_FILES["images"]["name"]);
for($i=0;$i<$count;$i++)
{
if ((($_FILES["images"]["type"][$i] == "image/gif")
|| ($_FILES["images"]["type"][$i] == "image/jpeg")
|| ($_FILES["images"]["type"][$i] == "image/png"))
&& ($_FILES["images"]["size"][$i] < 100000))
{
if ($_FILES["images"]["error"][$i] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
// echo "Upload File Name: " . $_FILES["images"]["name"][$i] . "<br />";
// echo "File Type: " . $_FILES["images"]["type"][$i] . "<br />";
//echo "File Size: " . ($_FILES["images"]["size"][$i] / 1024) . " Kb<br />";
if (file_exists("images/location/".$_FILES["images"]["name"][$i] ))
{
echo "<b>".$_FILES["images"]["name"][$i] . " already exists. </b>";
}
else
{
move_uploaded_file($_FILES["images"]["tmp_name"][$i] ,"images/location/"."NEW_NAME!!!".$i.".jpg" );
// echo "Stored in: " . "images/location/" . $_FILES["images"]["name"][$i] ."<br />";
?>
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["images"]["type"][$i] ." , file size::: ".$_FILES["images"]["size"][$i] ;
}
}
}
..
<form action = "" method="POST" enctype="multipart/form-data">
<input type="file" name="images[]" size="20" />
<input type="file" name="images[]" size="20" />
<input type="file" name="images[]" size="20" />
<input type="submit" name="submit"/>
</form>
I have used this in my project
$temp = explode(".", $_FILES['image']['name']);
$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
move_uploaded_file($_FILES['image']['tmp_name'], $name);
//this is for single image upload
//Here $name is the new image name. You can then use your mysql_insert function to insert new image name to the database
//to upload multiple file just pass the file name as an array,tmp_name as an array
public function __attachments_upload($name, $tmp_name) {
foreach ($name as $key => $value) {
$temp = explode(".", $value);
$name = round(microtime(true)) . substr(md5(rand()), 0, 4) . '.' . end($temp);
move_uploaded_file($tmp_name[$key], $name);
//here you can use mysql_insert
}
}
Hi so I have this upload script, that can upload one file at the time but I need to upload more than one file at the same time and then name every uploaded file as 1 and the next file as 2 and the next one as 3 and so on.
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png","JPG");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if (in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1032) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("i/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "i/" . $_FILES["file"]["name"]);
echo "Stored in: " . "i/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
Just use several inputs on your html:
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
And in your PHP
<?php
for ($i=0; $i < count($_FILES['name']); $i++) {
$new_file = $_FILES['name'][$i] . '.' . $i+1;
}
?>
The later will create the filenames appending the index +1 so you'll have:
myfile1.txt.1
myfile1.txt.2
Adjust as needed.
Edit: Check this link.
You should be able to do like this:
$files = array();
$allowed_filetypes = array('jpg','jpeg','gif','bmp','png','tif','pdf');
$max_filesize = 15242880;
$upload_path = 'images/image_uploads/';
for ($i = 0; $i < count($_FILES['files']['name']); $i++){
if($_FILES['files']['name'][$i] != "") {
$filename = $_FILES['files']['name'][$i];
$file_info = pathinfo($_FILES['files']['name'][$i]);
$ext = strtolower($file_info['extension']);
//echo "<span style='font-size: 20px; color: #ff3333;'>".$ext."</span>";
if(!in_array($ext,$allowed_filetypes))
die("The file you attempted to upload ($filename) is not allowed.");
if(filesize($_FILES['files']['tmp_name'][$i]) > $max_filesize)
die("The file you attempted to upload ($filename) is too large.");
if(!is_writable($upload_path))
die("You cannot upload to the specified directory, please CHMOD it to 777.");
$filename = ($i+1).".".$ext;
if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$upload_path.$filename)) {
$result = mysql_query("Insert Into image_uploads_images (upload_id, image, original_name) Values ('$id', '$filename', '".$_FILES['files']['name'][$i]."');");
if($result){
array_push($files, "http://www.site.com/images/image_uploads/$filename => ".$_FILES['files']['name'][$i]);
}else{
echo "<p style=\"color:#cc3333;\">Unable to upload ".$_FILES['files']['name'][$i]."</p>";
}
}else{
echo "<p style=\"color:#cc3333;\">Unable to upload ".$_FILES['files']['name'][$i]."</p>";
}
}
}
Edit
Just as a brief explanation, all file inputs would have the same name, in this case files. But when you do that, you need to add [] behind the name in the form element, like <input type="file" name="files[]" /> so that it comes through as an array.
Once you have the $_FILES array you can go through it recursively for each file uploaded and do with it what you need.
I am using xampp on Windows 7. My problem is that the image isn't appearing when I clicked the submit button.
Here's my php code:
<?php
$fileLocation = 'C:\xampp\htdocs\images';
$name = $_FILES["file"]["name"];
$tempName = $_FILES["file"]["tmp_name"];
$size = $_FILES["file"]["size"];
$fileType = $_FILES["file"]["type"];
if ($fileType == "images/jpeg" && $size < 2000000)
{
if ($_FILES['file']['error'] > 0)
{
echo "File error! : " . $_FILES['file']['error']. "</br>";
}
else
{
echo "File Name: " . $name . "</br>";
echo "File Type: " . $fileType . "</br>";
echo "File Size: " . $size . "</br>";
}
if (file_exists($file_location, $name))
{
echo "File already exists!" . $name . "</br>";
}
else
{
move_uploaded_file($tempname, $fileLocation.$name);
echo "Stored in: " . $fileLocation . "</br>";
}
}
?>
HTML CODE:
<form enctype="multipart/form-data" action="uploadFile.php" method="POST">
Send this file: <input name="file" type="file" id='file'/>
<input type="submit" value="Send File" name="submit"/>
</form>
Thank you for your response.
Also, check if Your HTML form has enctype='multipart/form-data' attribute set. It's easy to forget about it (at least I do almost every time).
I am trying to upload an image to server using PHP and the save inside a dir, and then returning the image url.
HTML:
<input name="photo" type="file" />
PHP
save_string_to_database( upload_img($_POST['photo']));
I have not much idea of PHP, I got a code from SO, but it did not do anything. Kindly help me to fix this code, or give a simple code to perform an upload:
function upload_img($img){
if ((($_FILES[$img]["type"] == "image/gif")
|| ($_FILES[$img]["type"] == "image/jpeg")
|| ($_FILES[$img]["type"] == "image/pjpeg")
|| ($_FILES[$img]["type"] == "image/jpg")
|| ($_FILES[$img]["type"] == "image/png"))
&& ($_FILES[$img]["size"] < 20000)
&& (strlen($_FILES[$img]["name"]) < 51)){
if ($_FILES[$img]["error"] > 0){
echo "Return Code: " . $_FILES[$img]["error"];
}
else{
// echo "Upload: " . $_FILES["image"]["name"] . "<br />";
// echo "Type: " . $_FILES["image"]["type"] . "<br />";
// echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
// echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists(THEME_DIR."/images/" . $_FILES[$img]["name"])){
echo $_FILES[$img]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES[$img]["tmp_name"],THEME_DIR."/images/" . $_FILES[$img]["name"]);
return THEME_DIR."/images/" . $_FILES[$img]["name"];
}
}
}
}
Here's a simple one.
HTML form to upload image
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Your PHP file that does the Upload
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Source
First you need a multipart/form-data form for uploading. This is a must :)
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
The PHP part is fairly simple:
This would result your file stored in "upload/{filename}"
The main part you want to consider is how to get the filename and back to your write_string_to_database procedure, you could do a simple script after the upload page like
save_string_to_database("upload/" . $_FILES["file"]["name"]);
would do the trick.
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
for file upload try this
<?php if(isset($_POST['submit']))
{
$ImageName = $_FILES['photo']['name'];
$fileElementName = 'photo';
$path = 'images/';
$location = $path . $_FILES['photo']['name'];
move_uploaded_file($_FILES['photo']['tmp_name'], $location);
} ?>
<form name="form1" id="form1" method="post" action="" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" name="submit">
</form>
This my function, variable $ten_anh is name of file image in html.
function upload_anh($ten_anh){ //$ten_anh la ten tren html vi du "avatar"
if(isset($_FILES[$ten_anh])){
$errors= array();
$file_name = $_FILES[$ten_anh]['name'];
$file_size =$_FILES[$ten_anh]['size'];
$file_tmp =$_FILES[$ten_anh]['tmp_name'];
$file_type=$_FILES[$ten_anh]['type'];
$file_ext=strtolower(end(explode('.',$_FILES[$ten_anh]['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="Không chấp nhận định dạng ảnh có đuôi này, mời bạn chọn JPEG hoặc PNG.";
}
if($file_size > 2097152){
$errors[]='Kích cỡ file nên là 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../images/".$file_name);
echo "Thành công!!!";
}
else{
print_r($errors);
}
}
}
Example:
- html code:
<input type="file" id="avatar" name="avatar"accept="image/png, image/jpeg" required/>
call function php: upload_anh('avatar');
<form method='post' action='' enctype='multipart/form-data'>
Name : <input type="text" name="name" required=""/><br><br>
Code : <input type="text" name="code" required=""/><br><br>
Price : <input type="text" name="price" required=""/><br><br>
Image : <input type="file" name="image" required=""/><br><br>
<button type='submit' class='buy' name="submit">Add Now</button>
</form>
<!--insert data -->
<?php
session_start();
include('db.php');
if(isset($_POST["submit"]));
{
/*echo "<pre>";
print_r($_POST);
print_r($_FILES);*/
$name = $_POST["name"];
$code = $_POST["code"];
$price = $_POST["price"];
$image = $_FILES["image"]["name"];
/* folder image save */
// $target_dir = "/var/www/html/shivam/new/upload/";
// $target_file = $target_dir.basename($_FILES["image"]["name"]);
// /*echo "1121".$target_file;*/
// $name = basename($_FILES["image"]["name"]);
// mysqli_query($con,$qry);
// /* move file */
// move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$name);
/* move_uploaded_file($tmp_name, "$target_dir/$name");*/
/* end */
$uploaddir = '/var/www/html/uploads/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
echo '44'.$uploadfile;
echo "<p>";
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';enter code here
print_r($_FILES);
print "</pre>";
}
?>
This question already has answers here:
File not uploading PHP
(11 answers)
Closed 2 years ago.
I have written a simple file upload script but it gives me the error of undefined index file1.
<html>
<body>
<form method="post">
<label for="file">Filename:</label>
<input type="file" name="file1" id="file1" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
if ($_FILES["file1"]["error"] > 0) {
echo "Error: " . $_FILES["file1"]["error"] . "<br />";
} else {
echo "Upload: " . $_FILES["file1"]["name"] . "<br />";
echo "Type: " . $_FILES["file1"]["type"] . "<br />";
echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file1"]["tmp_name"];
}
}
?>
What is the problem in code?
You lack enctype="multipart/form-data" in your <form> element.
Another solution for simple php file upload script is here :
(make a yourfile.php and insert the below code. then put that yourfile.php on your website)
<?php
$pass = "YOUR_PASSWORD";
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1256" /></head><body>
<?php
if (!empty($_GET['action']) && $_GET['action'] == "logout") {session_destroy();unset ($_SESSION['pass']);}
$path_name = pathinfo($_SERVER['PHP_SELF']);
$this_script = $path_name['basename'];
if (empty($_SESSION['pass'])) {$_SESSION['pass']='';}
if (empty($_POST['pass'])) {$_POST['pass']='';}
if ( $_SESSION['pass']!== $pass)
{
if ($_POST['pass'] == $pass) {$_SESSION['pass'] = $pass; }
else
{
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post"><input name="pass" type="password"><input type="submit"></form>';
exit;
}
}
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
Please choose a file: <input name="file" type="file" /><br />
<input type="submit" value="Upload" /></form>
<?php
if (!empty($_FILES["file"]))
{
if ($_FILES["file"]["error"] > 0)
{echo "Error: " . $_FILES["file"]["error"] . "<br>";}
else
{echo "Stored file:".$_FILES["file"]["name"]."<br/>Size:".($_FILES["file"]["size"]/1024)." kB<br/>";
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
}
}
// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {$dirArray[] = $entryName;} closedir($myDirectory);
$indexCount = count($dirArray);
echo "$indexCount files<br/>";
sort($dirArray);
echo "<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks><TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n";
for($index=0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != ".")
{
echo "<TR>
<td>$dirArray[$index]</td>
<td>".filetype($dirArray[$index])."</td>
<td>".filesize($dirArray[$index])."</td>
</TR>";
}
}
echo "</TABLE>";
?>
Make the following changes and try.
<form method="post" action="" enctype="multipart/form-data" >
Html
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
<html>
<body>
<form action="" method="post" ectype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"></br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}enter code here
}
?>
</body>
</html>
Primary issue is your form does not have option to send file content over http .
To send binary data along with the text data from input elements you need to add an extra attribute in form tag .
<form method="post" enctype="multipart/form-data">
Then in php code
try this line
<?php
print_r($_FILES);
?>
above code will display all information regarding file uploading from your form .