Multiple file upload in PHP - rename files - php

I'm a beginner in php and now doing a project in php. I want to upload images(maximum four image files only).I used the following code to upload images.
<script type="text/javascript">
count=1;
function add_file_field()
{
if(count<4)
{
var container=document.getElementById('file_container');
var file_field=document.createElement('input');
file_field.name='images[]';
file_field.type='file';
container.appendChild(file_field);
var br_field=document.createElement('br');
container.appendChild(br_field);
count++;
}
}
</script>
<div id="file_container">
<input name="images[]" type="file" id="file[]" />
<br />
</div>
<br>Add
I used the following code for single file upload.It's working
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 100000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "File Error : " . $_FILES["file"]["error"] . "<br />";
}else {
echo "Upload File Name: " . $_FILES["file"]["name"] . "<br />";
echo "File Type: " . $_FILES["file"]["type"] . "<br />";
echo "File Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "File Description:: ".$_POST['description']."<br />";
if (file_exists("images/".$_FILES["file"]["name"]))
{
echo "<b>".$_FILES["file"]["name"] . " already exists. </b>";
}else
{
$tmpname=$_FILES["file"]["tmp_name"];
$name=$_FILES["file"]["name"];
$new="jun.jpg";
rename($name,$new);
move_uploaded_file($_FILES["file"]["tmp_name"],"images/".$new);
echo "Stored in: " . "images/" .$new."<br />";
?>
Uploaded File:<br>
<img src="images/<?php echo $new; ?>" alt="Image path Invalid" >
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["file"]["type"]." , file size::: ".$_FILES["file"]["size"];
}
?>
I need help to modify this code to upload maximum of 4 images.
Can rename function be used to rename a selected file for upload on moving to a specified folder?
but it was showing error
Please do help me

You should allow multiple file selection in your file input, so you do not have to add a new input over and over again:
<input id="file" type="file" name="images[]" multiple>
After submitting the form you can iterate over $_FILES array like that:
foreach($_FILES['images'] as $file) {
//your code here --> replace $_FILES['file'] with $file
}
I hope this helps.

<?php
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/pjpeg"))
&& ($_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("public/images/".$_FILES["images"]["name"][$i] ))
{
echo "<b>".$_FILES["images"]["name"][$i] . " already exists. </b>";
}
else
{
move_uploaded_file($_FILES["images"]["tmp_name"][$i] ,"public/images/". $_FILES["images"]["name"][$i] );
echo "Stored in: " . "public/images/" . $_FILES["images"]["name"][$i] ."<br />";
?>
Uploaded File:<br>
<img src="public/images/<?php echo $_FILES["images"]["name"][$i] ; ?>" alt="Image path Invalid" >
<?php
}
}
}else
{
echo "Invalid file detail ::<br> file type ::".$_FILES["images"]["type"][$i] ." , file size::: ".$_FILES["images"]["size"][$i] ;
}
}
}?>
image uploaded using for loop..foreach was showing error

Here is an example of multi-file upload in PHP
https://github.com/hemantrai88/html5-php_multi-file-upload

I have one example which is working, I think this will help you
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" />
<input type="submit"/>
</form>
In php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}

Related

PHP - How can I insert the new filenames of uploading to MySQL

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
}
}

Invalid File on file upload PHP

upload_file.php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma", "MP4");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_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";
}
?>
html
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
So my problem is I get the message "Invalid File". This only happens when I try to upload video type files. However when I try to upload an image it works like a charm. I've searched all over stackoverflow for other video file upload codes and still couldn't find any that worked. Anyone that could refer another question/solution to me and/or fix this problem will greatly be appreciated.
EXTRA NOTE
I've already tried adding echo "Its type is " . $_FILES["file"]["type"]; to debug what file type is being given however it just returns a nice white space.
Change this part
else
{
echo "Invalid file";
}
to
else
{
echo "Invalid file";
echo "Its type is " . $_FILES["file"]["type"];
}
Now upload the files that don't work and add those types to your list
Apparently the problem only was because the php.ini was set to only accept 10M the file I was uploading was over 15MB and so I guess it gave me the error. But shouldn't that give me the error file-size is too much or something? But that's basically the reason I got the error. :)

PHP Upload Script Not Working

My PHP upload script is not getting anything from my form. Here is my form:
<small>Must be JPG, max 200kb</small>
<input id="image" type="checkbox" name="image" value="yes">
<input type="file" name="file" id="file">
Here is the section of PHP that handles the upload, I know that $image does infact = 'yes', so it looks like the problem is with the $_FILES array, as $_FILES["file"]["size"] is empty:
if ($image=="yes" && $_FILES["file"]["size"]>0) {
if ((($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
{
if ($_FILES["file"]["error"] > 0)
{
$picstuff="Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$picstuff= "Upload: " . $_FILES["file"]["name"] . "<br />
Type: " . $_FILES["file"]["type"] . "<br />
Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br /><br><br>
<center>Please note it can take a couple of minutes for the image to be processed.</center><br><br>";
move_uploaded_file($_FILES["file"]["tmp_name"], "images/$id.jpg");
$query="UPDATE content SET image='yes' WHERE `id`='$id'";
$result=mysql_query($query);
}
}
else
{
$picstuff = "Image too large or incorrect format. Please upload a jpeg less than 200kb.";
$image= "no";
$query="UPDATE content SET image='No' WHERE `id`='$id'";
$result=mysql_query($query);
}
} else
{
$picstuff = 'No File found';
$image= "no";
$query="UPDATE content SET image='No' WHERE `id`='$id'";
$result=mysql_query($query);
};
Every time I try upload I just get the 'No File found'.
Would appreciate any help!
I put enctype="multipart/form-data" into my form tag and it fixed my problem.

Upload files in PHP doesn't work

I am new to PHP and I'm trying to make an upload script. But it doesn't work completely.
The thing that doesn't work is that when I have uploaded the photo it doesn't store the photo in the folder "uploads". (The folder location is: Applications > MAMP > htdocs > Marjolein)
Also I want to show the photo that has been uploaded in the browser, but this also doesn't work.
I work with a Mac and use MAMP to run my php code. Can you please help me so I can show the picture in the browser and that it will be stored in the folder "uploads"?
The code I have is:
uploader.php
<style>
.sucess{
color:#088A08;
}
.error{
color:red;
}
</style>
<?php
$file_exts = array("jpg", "bmp", "jpeg", "gif", "png");
$upload_exts = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($upload_exts, $file_exts))
{
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>";
// Enter your path to upload file here
if (file_exists("://Applications/MAMP/htdocs/Marjolein/uploads/" .
$_FILES["file"]["name"]))
{
echo "<div class='error'>"."(".$_FILES["file"]["name"].")".
" already exists. "."</div>";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"://Applications/MAMP/htdocs/Marjolein/uploads/" . $_FILES["file"]["name"]);
echo "<div class='sucess'>"."Stored in: " .
"://Applications/MAMP/htdocs/Marjolein/uploads/" . $_FILES["file"]["name"]."</div>";
}
}
}
else
{
echo "<div class='error'>Invalid file</div>";
}
?>
<?php
if(isset($_REQUEST['show_image']) and $_REQUEST['show_image']!='')
{
?>
<p><img src="uploads/<?php echo $_REQUEST['show_image'];?>" /></p>
<?php
}
?>
uploadform.html
<html>
<body>
<form action="uploader.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>
</body>
</html>
The webbrowser shows after I click on the submit button:
Upload: 0_8caab_996cc75d_orig.jpg
Type: image/jpeg
Size: 538.166992188 kB
Temp file: /Applications/MAMP/tmp/php/phptpCA8B
Stored in: ://Applications/MAMP/htdocs/Marjolein/uploads/0_8caab_996cc75d_orig.jpg
Try to echo the image after uploading: (DonĀ“t know about the storage of the image)
echo '<img src="://Applications/MAMP/htdocs/Marjolein/uploads/" . $_FILES["file"]["name"]" border=0>';
Place it here:
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"://Applications/MAMP/htdocs/Marjolein/uploads/" . $_FILES["file"]["name"]);
echo "<div class='sucess'>"."Stored in: " .
"://Applications/MAMP/htdocs/Marjolein/uploads/" . $_FILES["file"]["name"]."</div>";
echo '<img src="://Applications/MAMP/htdocs/Marjolein/uploads/" . $_FILES["file"]["name"]" border=0>';
}
Maybe the path to the file is not correct. i think you can try this instead of your previous path:
move_uploaded_file($_FILES["file"]["tmp_name"],
"../uploads/" . $_FILES["file"]["name"]);
or if the folder "uploads" is located at in the same as the uploader.php you can use this:
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);

simple file upload script [duplicate]

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 .

Categories