single image to multiple image upload - php

I have the follow script that uploads and image and a thumbnail to a directory and store the img names (img and thumb) to the database.
I originally found this script somewhere on the web while googling but, but now I need to be able to upload more than one image... it works fine for one image as is.
<?php
//error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","400");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{
mysql_query("INSERT INTO `imgs` (`id` ,`user_id` ,`img_name`) VALUES (NULL , '$userID', 'img1.jpg');");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="en-us" http-equiv="Content-Language">
</head><body>
<?php echo $change; ?>
<div id="posts">
<form method="post" action="" enctype="multipart/form-data" name="form1">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
<input type="submit" id="mybut" value="Upload" name="Submit"/>
</form>
</div>
</body></html>
for multiple image I know I can change the html portion to a foreach loop, like:
<form method="post" action="" enctype="multipart/form-data" name="form1">
<?php
$allow_upload = 10;
for($i=0; $i<$allow_upload; $i++) {
echo '<input size="25" name="file[]" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>';
}
?>
<input type="submit" id="mybut" value="Upload" name="Submit"/>
</form>
but I havent been able to figure how and where to put a foreach loop and and adapty the rest for multiple images.
my db setup would be something like id, userID, big img, small img.
any help would be greatly appreciated, im ready to start pulling my hair out!!

if you want to loop multiple file input elements then you need to tell that it is an array unless you have a different name for each input elements.
for($i=0; $i<$allow_upload; $i++) {
echo '<input size="25" name="file[]" type="file"'/>;
}
if you want to select multiple file from one input element then
<input name="filesToUpload[]" type="file" multiple/>

Instead of multiple input files you can use a single input file and save all the files in array, and use foreach to save each file to folder.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_FILES['allimages'] as $files) {
var_dump($files);
}
}
?>
<form id="fileupload" enctype="multipart/form-data" method="post">
<input type="file" name="allimages[]" id="allimages" multiple><!--Use CTRL key to upload multiple images -->
<input type="submit" name="submit" id="submit">
</form>
you need to hold cntrl key to upload multiple files.

Related

Accept uploaded files with the same name?

I Have a form where people can upload a single image. Most people are uploading pictures from their mobile devices. Everyone with an iPhone, has their image uploaded as "image.png". I need to have my form not reject it, and just accept files with the same name without delete the old one or rename them something like "imageupload1.png", "imageupload2.png" or even image.png then "image-Copy.png" then "image-Copy(2).png", etc
I figure something like this might work:
$filename = $_FILES['myfilename']['name'];
$filename = time().$filename;
or
function renameDuplicates($path, $file)
{
$fileName = pathinfo($path . $file, PATHINFO_FILENAME);
$fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);
$returnValue = $fileName . $fileExtension;
$copy = 1;
while(file_exists($path . $returnValue))
{
$returnValue = $fileName . '-copy-'. $copy . $fileExtension;
$copy++;
}
return $returnValue;
}
// 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 "Sucessfully Uploaded - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
I just don't know where to plug it in. I'm a noob so take it easy on me and please be specific. The options I "figured might work" were taken from other questions but they didn't work for me, chances are i'm doing something wrong so please don't mark this as "already asked" Thank you. Sorry for the bother.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "<a href='../pie.html' style='border: 5px solid #3a57af;padding-right:50px;padding-bottom:25px;padding-left:50px;display:inline;font-weight:bold;color:#3a57af';> CLICK HERE TO REGISTER</a>";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
html {
padding-top: 5em;
font-family: trebuchet, sans-serif;
font-size: 24px;
font-weight: bold;
-webkit-font-smoothing: antialiased;
text-align: center;
background: white;
}
body {
padding:0;
margin:0;
text-align:center;
}
div.imageupload {
padding: 5em 5em 5em 5em;
height:100vh;
width:100vh;
text-align:justify
}
<html>
<head>
<title>Image Submission</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="assets/css/image.css">
<style type="text/css"></style>
</head>
<body>
<div class="imageupload">
<p><h1>Step 1</h1><br>
Please submit a recent photograph to be featured on the homepage of this website.<br><br>
We will place your yearbook picture in the lower right hand corner of the image you submit.<br>
<br>This will allow our classmates to see how we look now and how we looked then.<br><br>
Please select an appropriate image for a website of this nature. <br><br>
The image should show you from your head to at least your knees. <br><br>
The image should not be a group picture, please be the only one in the picture.<br><br>
Any pictures that do not meet this criteria will be sent back and will not be posted.<br></p>
<form action="PHPmailer/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></div>
</body>
</html>
Instead of your $target_file definition, plug in your dedup function:
$target_file = renameDuplicates($target_dir, basename($_FILES["fileToUpload"]["name"]));
(I did not check whether the function behaves properly, but at the first glance it should be all right.)
EDIT: The function was a tiny bit broken.
function renameDuplicates($path, $file) {
$fileName = pathinfo($path . $file, PATHINFO_FILENAME);
$fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION);
$returnValue = $path . $fileName . $fileExtension;
$copy = 1;
while(file_exists($returnValue))
{
$returnValue = $path . $fileName . '-copy-'. $copy . $fileExtension;
$copy++;
}
return $returnValue;
}
Check the lines containing $returnValue for changes.
I have come to your rescue, and written the whole thing for you :)
You will need to have this structure:
upload.php
ImageUpload/uploadMe.php
in upload.php:
<html>
<head>
<title>Upload Your image here | SiteName</title>
<!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<?php
$FLAG = $_GET['e'];
if($FLAG == "UPLOAD_FAILED"){ ?>
<div class="col-md-12 alert alert-warning">
Ooops! It looks like an error occured when uploading your image.
</div>
<?php } else if($FLAG == "NOT_IMAGE"){ ?>
<div class="col-md-12 alert alert-warning">
Hey! Thats not an image?<br/>
<pre>We only allow: png, jpg, gif and jpeg images.</pre>
</div>
<?php } else{} ?>
<div class="well col-md-6">
<form action="ImageUpload/uploadMe.php" method="POST" enctype="multipart/form-data">
<legend>
Image Upload
</legend>
<input type="file" name="file" class="form-control btn btn-info"/>
<br/>
<input type="submit" value="Upload" class="btn btn-primary"/>
</form>
</div>
<div class="well col-md-6">
<p><h1>Step 1</h1><br>
Please submit a recent photograph to be featured on the homepage of this website.<br><br>
We will place your yearbook picture in the lower right hand corner of the image you submit.<br>
<br>This will allow our classmates to see how we look now and how we looked then.<br><br>
Please select an appropriate image for a website of this nature. <br><br>
The image should show you from your head to at least your knees. <br><br>
The image should not be a group picture, please be the only one in the picture.<br><br>
Any pictures that do not meet this criteria will be sent back and will not be posted.<br></p>
</div>
</div>
</div>
</body>
</html>
In ImageUpload/uploadMe.php:
<?php
if(isset($_FILES['file'])){
$File = $_FILES['file'];
//File properties:
$FileName = $File['name'];
$TmpLocation = $File['tmp_name'];
$FileSize = $File['size'];
$FileError = $File['error'];
//Figure out what kind of file this is:
$FileExt = explode('.', $FileName);
$FileExt = strtolower(end($FileExt));
//Allowed files:
$Allowed = array('jpg', 'png', 'gif', 'jpeg');
//Check if file is allowed:
if(in_array($FileExt, $Allowed)){
//Does it return an error ?
//No:
if($FileError==0){
$ImageFolder = "uploads";
//Check if exist, otherwise create it!
if (!is_dir($ImageFolder)) {
mkdir($ImageFolder, 0777, true);
}
else{}
//Create new filename:
$NewName = uniqid('', true) . rand(123456789,987654321). '.' . $FileExt;
$UploadDestination = $ImageFolder ."/". $NewName;
//Move file to location:
if(move_uploaded_file($TmpLocation, $UploadDestination)){
//Yay! Image was uploaded!
//Do whatever you want here!
}
//File didnt upload:
else{
//Redirect:
header("Location: /upload.php?e=UPLOAD_FAILED");
}
}
//An error occured ?
else{
//Redirect:
header("Location: /upload.php?e=UPLOAD_FAILED");
}
}
//Filetype not allowed!
else{
//redirect:
header("Location: /upload.php?e=NOT_IMAGE");
}
}
else{
//No file was submitted :s send them back, eh ?
header("Location: /upload.php");
}
OK, i think its done now!
If you want to use your own "Look" just copy and paste the <form></form> stuff and maybe the simple "error" handler ?
Have a good one :)
<input class="uploadGAConnection" #uploadFile type="file" (change)="uploadGAConnectionDetails($event)" placeholder="Upload file" accept=".csv,.json" (click)="uploadFile.value=null">
You can simply give a reference and set its value null on every click.

Error uploading multiple images at the same time

I am trying to upload multiple photos at the same time but there seems to be an error with my script. If for example, I select 10 different photos, one particular image is uploaded 10 times (ignoring the other 9 images). This is the script:
for ($i = 0; $i < count($_FILES["_photo"]["name"]); $i++) {
if (!empty($_FILES['_photo']['name'][$i])) {
if (($_FILES['_photo']['type'][$i] == 'image/jpeg') OR ($_FILES['_photo']['type'][$i] == 'image/png') OR ($_FILES['_photo']['type'][$i] =='image/gif')) {
$upload_folder = "./profile_pix/";
$pic_name = time() . ".jpg";
$pic_path = $upload_folder . $pic_name;
require_once "include/resize.php";
if (move_uploaded_file($_FILES['_photo']['tmp_name'][$i], $pic_path)) {
$image = new Resize($pic_path);
$image->resizeImage(180, 180, 'crop');
$image->saveImage($pic_path);
}
$sql2 = "INSERT INTO photos
(photo, member_id, photo_id)
VALUES
('$pic_name', :session_id, :offer_count)";
$db -> query($sql2, array('session_id' => $_SESSION['id'], 'offer_count' => $offer_count));
}else {
header ("Location: submitoffer.php?err=03");
}
}
HTML:
<input type="file" id="_photo" name="_photo[]" multiple="multiple">
File upload is working fine.
The line
$pic_name = time() . ".jpg";
is always evaluating to same value.
As logically all files are getting uploaded on same time().
Instead use:
$pic_name = $i . '_'. time() . ".jpg";
To add uniqueness.
try this, and you will see what is happening:
<?php
echo "<pre>";
print_r($_FILES);
echo "</pre>";
?>
And in your HTML, make sure you use different names, like this:
<input name="userfile[]" type="file" />
<input name="userfile[]" type="file" />
<input name="userfile[]" type="file" />
Then pick them up by each name. Just inspect the content of $_FILES to understand the structure.
I also advice you serious do some error checking.
100% working and tested code:
upload.php:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $_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_type == "image/jpg" || $file_type == "image/png" || $file_type == "image/jpeg" || $file_type == "image/gif" ) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
}
}
header('location:uploads.html');
}
}
else { header('location:404.html'); }
?>
upload.html
<form id="upload_images" action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple="true" />
<input type="submit" id="btn_upload" value="U P L O A D" />
</form>

Multiple file uploads issue

I have a simple code to upload multiple images that uploads the image to a folder and saves the path to the database. The problem is I have 3 browse buttons. The script only uploads the files and saves the path to the database when all the three browse buttons are selected with images. But when I select only 1 image to upload the script does not works. What is the matter?
Here is my current script.
<?php
include'includes/db.php';
if(isset($_POST['submit'])){
$extension = substr($_FILES['photo1']['name'],
strrpos($_FILES['photo1']['name'], '.'));
$extension = substr($_FILES['photo2']['name'],
strrpos($_FILES['photo2']['name'], '.'));
$extension = substr($_FILES['photo3']['name'],
strrpos($_FILES['photo3']['name'], '.'));
$extension = strtolower($extension);
echo $extension;
if( $extension == ".jpg" || $extension == ".jpeg" || $extension == ".gif" || $extension == ".png" )
{
$img1=$_FILES['photo1']['name'];
$img2=$_FILES['photo2']['name'];
$img3=$_FILES['photo3']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp1=$_FILES['photo1']['tmp_name'];
$temp2=$_FILES['photo2']['tmp_name'];
$temp3=$_FILES['photo3']['tmp_name'];
$limit_size = 1024000;
$size_in_kb = 1024;
$max_size = $limit_size/$size_in_kb;
if($size > $limit_size)
{
echo "<script>location.replace('test.php?err=File size exceeds $max_size KB')</script>";
}
else
{
move_uploaded_file($temp1,"images/".$img1);
move_uploaded_file($temp2,"images/".$img2);
move_uploaded_file($temp3,"images/".$img3);
$sql2="INSERT INTO ad_images(image1, image2, image3)VALUES('$img1', '$img2', '$img3')";
$res2=mysql_query($sql2);
if($res2){
echo "<script>location.replace('test.php?success=Product added successfuly')</script>";
}else{
echo "<script>location.replace('test.php?vlx=Error. Try Again...')</script>";
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Script Testing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<p> Upload Image<br />
<input type="file" name="photo1" id="photo"><br />
<input type="file" name="photo2" id="photo"><br />
<input type="file" name="photo3" id="photo"><br />
<input type="submit" name="submit" id="submit" value="Add Product" style="margin-top: 25px; margin-left: 335px;"/>
</p>
</body>
</html>
I don't get whats wrong in my code everything seems to be fine. Please help.
************ SOLVED ***************
I was using the same variable extension. Now solved.
Here is my new code.
<?php
include'includes/db.php';
if(isset($_POST['submit'])){
$extension1 = substr($_FILES['photo1']['name'],
strrpos($_FILES['photo1']['name'], '.'));
$extension2 = substr($_FILES['photo2']['name'],
strrpos($_FILES['photo2']['name'], '.'));
$extension3 = substr($_FILES['photo3']['name'],
strrpos($_FILES['photo3']['name'], '.'));
$extension1 = strtolower($extension1);
echo $extension1;
$extension2 = strtolower($extension2);
echo $extension2;
$extension3 = strtolower($extension3);
echo $extension3;
if( $extension1 == ".jpg" || $extension1 == ".jpeg" || $extension1 == ".gif" || $extension1 == ".png" ||
$extension2 == ".jpg" || $extension2 == ".jpeg" || $extension2 == ".gif" || $extension2 == ".png" ||
$extension3 == ".jpg" || $extension3 == ".jpeg" || $extension3 == ".gif" || $extension3 == ".png" )
{
$img1=$_FILES['photo1']['name'];
$img2=$_FILES['photo2']['name'];
$img3=$_FILES['photo3']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp1=$_FILES['photo1']['tmp_name'];
$temp2=$_FILES['photo2']['tmp_name'];
$temp3=$_FILES['photo3']['tmp_name'];
$limit_size = 1024000;
$size_in_kb = 1024;
$max_size = $limit_size/$size_in_kb;
if($size > $limit_size)
{
echo "<script>location.replace('test.php?err=File size exceeds $max_size KB')</script>";
}
else
{
move_uploaded_file($temp1,"images/".$img1);
move_uploaded_file($temp2,"images/".$img2);
move_uploaded_file($temp3,"images/".$img3);
$sql2="INSERT INTO ad_images(image1, image2, image3)VALUES('$img1', '$img2', '$img3')";
$res2=mysql_query($sql2);
if($res2){
echo "<script>location.replace('test.php?success=Product added successfuly')</script>";
}else{
echo "<script>location.replace('test.php?vlx=Error. Try Again...')</script>";
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Script Testing</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<p> Upload Image<br />
<input type="file" name="photo1" id="photo"><br />
<input type="file" name="photo2" id="photo"><br />
<input type="file" name="photo3" id="photo"><br />
<input type="submit" name="submit" id="submit" value="Add Product" style="margin-top: 25px; margin-left: 335px;"/>
</p>
</body>
</html>
because u take the same variable $extension and if the third browse field will not be choosen , after submit it will be blank and it will not entered into the upload if condition. If u will browse only from third browse button then that single file will be uploaded.
You can use multiple attribute to upload multiple files throw a single browse button eg
<input type="file" name="img" multiple>
You can use ctrl to select multiple images

Upload Multiple Files in PHP & INSERT path to MySQL

I've setup a form to upload multiple files from a PHP script and then insert it into the Database with path. Here's my code
<form action="" method="post" enctype="multipart/form-data">
<tr class='first'>
<td>Property Image : </td>
<td>
<input type="file" name="pic_upload[]" >
<input type="file" name="pic_upload[]" >
<input type="file" name="pic_upload[]" >
</td>
</tr>
<tr class='first'>
<td> </td><td><input type="submit" name="create" value="Add" /></td>
</tr>
</form>
<?php
if(isset($_POST['create'])) {
$path = "images/";
for ($i=0; $i<count($_FILES['pic_upload']['name']); $i++) {
$ext = explode('.', basename( $_FILES['pic_upload']['name'][$i]));
$path = $path . md5(uniqid()) . "." . $ext[count($ext)-1];
move_uploaded_file($_FILES['pic_upload']['tmp_name'][$i], $path);
}
$sql = "INSERT INTO post (`image`) VALUES ('$path');";
$res = mysqli_query($con,$sql) or die("<p>Query Error".mysqli_error()."</p>");
echo "<p>Post Created $date</p>";
}
?>
The Script runs successfully, but at the database end inside the column it looks like this.
images/8de3581eb72ee7b39461df48ff16f4a3.jpg024fae942ae8c550a4bd1a9e028d4033.jpg380cc327df25bc490b83c779511c015b.jpg
Help me out with this please
Move $path = "images/"; inside the for loop. Otherwise you are appending to the filename without resetting it after each iteration. Actually, you don't need to use a variable for that prefix at all. You can simply write 'images/' . md5(uniqid()) . "." . $ext[count($ext)-1] immediately.
To write the values to the database, you can either run the query in each iteration as well or add the paths to an array which is transformed to the comma-separated insertion list according to the SQL syntax.
Here is what worked for me:everything contained in the for loop then just return the $fileDest
<?php
if(isset($_POST['submit'])){
$total = count($_FILES['files']['tmp_name']);
for($i=0;$i<$total;$i++){
$fileName = $_FILES['files']['name'][$i];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$newFileName = md5(uniqid());
$fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
if($ext === 'pdf' || 'jpeg' || 'JPG'){
move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
}else{
echo 'Pdfs and jpegs only please';
}
}
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form class="" action="test.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<button type="submit" name="submit">Upload</button>
</form>
</body>
</html>
$files = array_filter($_FILES['lamp']['name']);
$total = count($files);
$path = "./asset/save_location/";
// looping for save file to local folder
for( $i=0 ; $i < $total ; $i++ ) {
$ext = explode('.', basename( $_FILES['lamp']['name'][$i]));
$tmpFilePath = $_FILES['lamp']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = $path .date('md').$i.".".$ext[count($ext)-1]; //save lampiran ke folder $path dengan format no_surat_tgl_bulan_nourut
// upload success
if(move_uploaded_file($tmpFilePath,$newFilePath)) {
$success="file uploaded";
}
}
} //end for
//looping for save namefile to database
for ($i=0; $i<count($_FILES['lamp']['name']); $i++) {
$ext = explode('.', basename( $_FILES['lamp']['name'][$i]));
$path = $path .date('md') .$i. "." . $ext[count($ext)-1].";";
$save_dir=substr($path, 22,-1);
}//end for
var_dump($save_dir);die();

Curious problème with images upload in PHP from form

I try to upload pictures from a form in PHP.
I've got a strange problem regarding my images upload:
My form:
<form id="booking-step" method="post" action="add.php" class="booking" autocomplete="off" enctype="multipart/form-data">
<input type="file" id="AddPhotos1" name="AddPhotos[]" />
<input type="file" id="AddPhotos2" name="AddPhotos[]" />
<input type="file" id="AddPhotos3" name="AddPhotos[]" />
<input type="file" id="AddPhotos4" name="AddPhotos[]" />
<input type="file" id="AddPhotos5" name="AddPhotos[]" />
</form>
My PHP:
if($_FILES['AddPhotos']){
$errorAddPhotos = "";
$validAddPhotos = "";
for($x=0;$x<sizeof($_FILES["AddPhotos"]["name"]);$x++){
$fichier = basename($_FILES['AddPhotos']['name'][$x]);
$taille_maxi = 3000;
$taille = filesize($_FILES['AddPhotos']['tmp_name'][$x]);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['AddPhotos']['name'][$x], '.');
if(!in_array($extension, $extensions))
{
$errorAddPhotos .= "Wrong extension.<br />";
}
if($taille>$taille_maxi)
{
$errorAddPhotos .= "Wrong size.<br />";
}
if((in_array($extension, $extensions)) && ($taille<$taille_maxi))
{
$fichier = strtr($fichier,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
if(move_uploaded_file($_FILES['AddPhotos']['tmp_name'][$x], $destin . $fichier))
{
$validAddPhotos = 'Success!';
}
else
{
$errorAddPhotos = 'Wrong';
}
}
}
}
echo $validAddPhotos;
echo $errorAddPhotos
My code looks good, but I cant upload my files...
Error: my files stay in condition "if(!in_array($extension, $extensions))".
Could you please help ?
Thanks.
I think you should use this logic is more perform than yours with testing image type and file size. Also, you can custom it with what you want like you did name of the file :)
multiple upload image function php?

Categories