Hello friend developers,
I have a question for upload file with multiple input in php.
This is my code for that.
if(isset($_FILES['images'])){
$dateinsert = Carbon::now();
$success = false;
$valid_formats = array("jpg", "png", "jpeg");
$max_file_size = 10000000;
$path = 'var/www/html/test/picture/'; // Upload directory
$count = 0;
$folder = $path . 'picture/user' . '.' . $_SESSION["user"] . "/picture";
$time = date("m/d/y");
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
foreach ($_FILES['images']['name'] as $f => $name) {
if ($_FILES['images']['error'][$f] == 4) {
$this->flash->addMessage('ErrorFile', error');
return;
}
if ($_FILES['images']['error'][$f] == 0) {
if ($_FILES['images']['size'][$f] > $max_file_size) {
$this->flash->addMessage('ErrorSize', 'error');
// error
} elseif (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) {
$this->flash->addMessage('ErrorFormat', 'error');
// error
} else {
$fichier = strtr($name,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$namea = preg_replace('/([^.a-z0-9]+)/i', '', $fichier);
$namePic = explode('.', $namea);
$name = strtolower(uniqid(rand()) . '_' . $time . '.' . $namePic[1]);
$destination = $folder . "/" . $name;
if (move_uploaded_file($_FILES["images"]["tmp_name"][$f], $destination))
$count++;
$success = true;
if ($success === true) {
$stmt = $this->getDB()->prepare("INSERT INTO insert_annonce
(img_nom,img_taille,img_type,img_desc,date_creat,id_user,id_front)
VALUES(?,?,?,?,?,?,?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $_FILES['images']['size'][$f]);
$stmt->bindParam(3, $namePic[1]);
$stmt->bindParam(4, $destination);
$stmt->bindParam(5, $dateinsert);
$stmt->bindParam(6, $_SESSION['user']);
$stmt->bindParam(7, $last_id);
$result = $stmt->execute();
return $response->withRedirect($this->router->pathFor('home'));
}
}
}
}
}
and this is html
<input type="file" name="images[]" class="file" data-show-upload="false" data-show-caption="false" data-show-remove="false" accept="image/jpeg,image/png" data-browse-class="btn btn-blue" data-browse-label="browse">
<input type="file" name="images[]" class="file" data-show-upload="false" data-show-caption="false" data-show-remove="false" accept="image/jpeg,image/png" data-browse-class="btn btn-blue" data-browse-label="browse">
<input type="file" name="images[]" class="file" data-show-upload="false" data-show-caption="false" data-show-remove="false" accept="image/jpeg,image/png" data-browse-class="btn btn-blue" data-browse-label="browse">
<input type="file" name="images[]" class="file" data-show-upload="false" data-show-caption="false" data-show-remove="false" accept="image/jpeg,image/png" data-browse-class="btn btn-blue" data-browse-label="browse">
The script works but it loads me a single file and not the others in my database.
Thank you in advance for the explanations
Related
$(document).ready(function(){
$("#add_small").click(function(event){
event.preventDefault();
$(".add_small").append('<div class="form-group">\
<label for="product_small_image">Product Image:</label>\
<input type="file" name="product_image[]" class="product_image" value=""/>\
Remove\
<div>');
});
jQuery(document).on('click', '.remove_small', function() {
jQuery(this).parent().remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" name="user_registration" class="register" enctype="multipart/form-data">
<div class="form-group">
<label for="product_small_image">Product Image:</label>
<input type="file" name="product_image[]" class="product_image" value=""/>
Add
</div>
<div class="add_small"></div>
<br/>
<input name="submit" type="submit" class="submit" value="Submit" />
</form>
<?php
if(isset($_POST['submit']))
{
$file_ary = reArrayFiles($_FILES['product_images']);
foreach ($file_ary as $file)
{
//print 'File Name: ' . $file['name'];
//print 'File Type: ' . $file['type'];
//print 'File Size: ' . $file['size'];
$folder_Path = "../images/product_image/";
$banner_image_name = str_replace(" ", "", strtolower(basename($file['name'])));
$banner_image_name_upload = $folder_Path.$banner_image_name;
//$banner_image_tmp = $_FILES['product_image']['tmp_name'];
$imageFileType = strtolower(pathinfo($banner_image_name,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
$msg = "<div class='alert alert-success'>Sorry, only JPG, JPEG, PNG & GIF files are allowed.</div>";
}
else
{
if (move_uploaded_file($banner_image_name_upload))
{
$set_width = 600;
$set_height = 600;
$banner_image_source_file = $banner_image_name_upload;
$banner_image_save_file = $banner_image_name_upload;
list($width_orig, $height_orig) = getimagesize($banner_image_source_file);
$image_p = imagecreatetruecolor($set_width, $set_height);
$image = imagecreatefromjpeg($banner_image_source_file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $set_width, $set_height, $width_orig, $height_orig);
imagejpeg($image_p, $banner_image_save_file, 75);
$query = "insert into inventory_add_in_stock(`product_image`)values('".$file['name']."')";
echo $query;
$result = mysqli_query($con,$query);
if($result==true)
{
$msg = "<div class='alert alert-success'>Record Save Successfully</div>";
}
else
{
$msg = "<div class='alert alert-danger'>Unable to Save Please Try Again !!!</div>";
}
}
else
{
$msg = "<div class='alert alert-danger'>Unable to Proceeed Please Try Again !!!</div>";
}
}
}
}
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
?>
This is my duplicate question. I have create add and remove more file using jQuery. Now, What happen when I click on add button it show me to choose another file similarly again and again. I am able to upload multiple file like this. But the problem is that when I click on submit button to insert into the database and move image to the folder it show me error i.e.
I found the reason in your code:
$banner_image_tmp = $_FILES['product_image']['tmp_name'];
The $banner_image_tmp will return an array. So, there will be an error
move_uploaded_file() expects parameter 1 to be string, array given
http://php.net/manual/en/features.file-upload.multiple.php. Your code should be:
if(isset($_POST['submit']))
{
$file_ary = reArrayFiles($_FILES['product_image']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
//Your custom code here
}
}
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
I have two form submitting buttons in one form, and I want to use $uploaded array in elseif() {...} like this $data ['pic_path'] = $uploaded;, but it doesn't work. I can only print out $uploaded inside of if () {...}, or inside the html body. What should I do to save the $uploaded in $data array? Thanks!
Here's the code:
<?php
if (isset($_POST[submit_image])) {
if (!empty($_FILES["files"]["name"][0])) {
$files = $_FILES["files"];
//arrarys to include files uploaded successfully and failed
$uploaded = array();
$failed = array();
//access tmp_name arrary
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files["tmp_name"][$position];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$file_name_new = uniqid("", true) . "." . $file_ext;
$file_destination = "uploads/" . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
} else {
$failed[$position] = "error";
}
}
print_r($uploaded);
}
} elseif (isset($_POST[submit_post])) {
$data = array();
$data['comments'] = $_POST['comments'];
//$data ['pic_path'] = $uploaded;
//print_r($uploaded);
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple />
<input type="submit" name="submit_image"/>
<textarea name="comments"></textarea>
<button type="submit" name="submit_post">Submit Your Post</button>
</form>
</body>
</html>
That's because $uploaded only exists in the if statement you declared it in. You will need to loop through files again in the elseif or move your declaration of $uploaded and $failed as well as the for loop that populates them out of that if block so the variables are accessible in both paths.
Edit - Try this:
if (!empty($_FILES["files"]["name"][0]) ) {
$files = $_FILES["files"];
//arrarys to include files uploaded successfully and failed
$uploaded = array();
$failed = array();
//access tmp_name arrary
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files["tmp_name"][$position];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$file_name_new = uniqid("", true) . "." . $file_ext;
$file_destination = "uploads/" . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
} else {
$failed[$position] = "error";
}
}
print_r($uploaded);
}
if (isset($_POST[submit_post])) {
$data = array();
$data['comments'] = $_POST['comments'];
$data ['pic_path'] = $uploaded;
}
I'm trying to upload multiple files from multiple input element for an online application form. I can upload one image using the below script please share how I can upload multiple image using multiple input??
if(!empty($_FILES)){
include 'config.php';
$file = $_FILES['image_file'];
$file_name = $file['name'];
$error = ''; // Empty
$ext = strtolower(substr(strrchr($file_name, "."), 1));
if($validation_type == 1)
{
$file_info = getimagesize($_FILES['image_file']['tmp_name']);
if(empty($file_info)) // No Image?
{
$error .= "The uploaded file doesn't seem to be an image.";
}
else // An Image?
{
$file_mime = $file_info['mime'];
if ($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2')
{
$extension = $ext;
}
else
{
$extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime];
}
if(!$extension)
{
$extension = '';
$file_name = str_replace('.', '', $file_name);
}
}
}
else if($validation_type == 2)
{
if (!in_array($ext, $image_extensions_allowed))
{
$exts = implode(', ',$image_extensions_allowed);
$error .= "You must upload a file with one of the following extensions:".$exts;
}
$extension = $ext;
}
if($error == "") // No errors were found?
{
$new_file_name = strtolower($file_name);
$new_file_name = str_replace(' ', '-', $new_file_name);
$new_file_name = substr($new_file_name, 0, -strlen($ext));
$new_file_name .= $extension; // File Name
$move_file = move_uploaded_file($file['tmp_name'],
$upload_image_to_folder.$new_file_name);
if($move_file)
{
$done = 'The image has been uploaded.';
}
}
else
{
#unlink($file['tmp_name']);
}
$file_uploaded = true;
}
You might be looking for multiple browse buttons, try your field name like this:
<input type="file" name="image_file1[]" />
<input type="file" name="image_file1[]" />
<input type="file" name="image_file1[]" />
<input type="file" name="image_file2[]" />
<input type="file" name="image_file2[]" />
<input type="file" name="image_file2[]" />
and then
if(!empty($_FILES['image_file1']['name'])){
$uploaded_file = $_FILES['image_file1'];
for($fi=0; $fi<count($_FILES['image_file1']['name']); $fi++){
$file_name= $uploaded_file['name'][$fi];
$file_type= $uploaded_file['type'][$fi];
$tmp_name= $uploaded_file['tmp_name'][$fi];
$file_size= $uploaded_file['size'][$fi];
}
}
if(!empty($_FILES['image_file2']['name'])){
$uploaded_file = $_FILES['image_file2'];
for($fi=0; $fi<count($_FILES['image_file2']['name']); $fi++){
$file_name= $uploaded_file['name'][$fi];
$file_type= $uploaded_file['type'][$fi];
$tmp_name= $uploaded_file['tmp_name'][$fi];
$file_size= $uploaded_file['size'][$fi];
}
}
I want to upload images using a browse button, but when I click, an infinite loop generates. I want that every file is loaded, the name is : 001 then 002 then 003...
Here are the codes :
Index.php
<?php
require('class/Image.php');
if(!empty($_FILES)){
$image = new Image();
$images = $image->upload($_FILES);
}
if($images === true){
$msg_success = 'Le chargement a réussi';
} else {
$msg_error = 'Le chargement a échoué';
}
?>
<h1>Ajouter une image</h1>
<?php
if(isset($msg_success)){
echo $msg_success;
}
if(isset($msg_error)){
echo $msg_error;
}
?>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" value="" name="upload[]" multiple="multiple">
<input type="submit" name="uploadFormSubmit" value="Ajouter">
</form>
Image.php
<?php
class Image{
public function upload($files){
$upload_dir = '/Applications/MAMP/htdocs/Devoir/PHP/Avancé/1/images/';
foreach($files['upload']['error'] as $key => $error){
$error = 0;
if(!isset($i)){
$i = 1;
}
if($error == UPLOAD_ERR_OK){
$tmp_name = $files['upload']['tmp_name'][$key];
$name = $files['upload']['name'][$key];
$tab_name = explode('.', $name);
$format = '%1$03d';
$file_nbr = sprintf($format, $i);
while(file_exists($upload_dir . $file_nbr . '.' . $tab_name[1])){
$i++;
}
}
if(move_uploaded_file($tmp_name, $upload_dir . $file_nbr . '.' . $tab_name[1]) == false){
$error += 1;
}
if($error == 0){
return true;
} else {
return false;
}
}
}
}
You probably should include $file_nbr = sprintf($format, $i); in your while loop as well:
while (file_exists($upload_dir . $file_nbr . '.' . $tab_name[1])){
$i++;
$file_nbr = sprintf($format, $i);
}
i'm a very big newbie # php. Hope you are considerate :)
i have this script and a litte problem. I want to check in the first foreach part if the select files are images. If the files are images and not to large it should give an ok for upload!
but it's important to check first all images!
the problem i have is for example:
in inputfield 1 i put an image with 1mb
in inputfield 2 i put an textfile
when i press submit the first image from the input is moving into the folder and than stopping on the textfile with an error <- no php ERROR just my own error (no image file or image is too big)
edit: it seems that the if ($upload_ok == true) part doesn't work
first i want that all input fields getting checked (validextension,fileextension,size) and when all inputfields ok the images can move to the folder ( starting with if ($upload_ok == true) ).
if (!empty($_FILES))
{
$upload_ok=array();
foreach($_FILES as $key => $file)
{
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
$fileExtension = strtolower(strrchr($file['name'], "."));
if ((in_array($fileExtension, $validExtensions) && ($file['error'] == 0))||$file['error'] == 4)
{
$upload_ok=true;
echo('true');
}
else
{
$upload_ok=false;
$result=false;
echo('false');
}
}
// if(!in_array(false ,$upload_ok))
if ($upload_ok == true)
{
foreach($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$newNamePrefix = $picName . '_';
$CounterPrefix = sprintf("%02d",(preg_replace("/[^0-9]/","", $key)));
$fileExtension = strtolower(strrchr($file['name'], "."));
$manipulator = new ImageManipulator($file['tmp_name']);
$newImage = $manipulator->resample(1024, 1024);
$manipulator->save($imgRoot . $maschineFolder . $picFolder . $newNamePrefix . $CounterPrefix . $fileExtension);
}
}
}
}
i made a small pastebin with the hole script here
if I understand you correctly...
select this
$upload_ok=array();
foreach($_FILES as $key => $file)
{
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
$fileExtension = strtolower(strrchr($file['name'], "."));
if ((in_array($fileExtension, $validExtensions) && ($file['error'] == 0))||$file['error'] == 4)
{
$upload_ok=true;
echo('true');
}
else
{
$upload_ok=false;
$result=false;
echo('false');
}
}
// if(!in_array(false ,$upload_ok))
and replace it with
$error = false;
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
foreach(array_keys($_FILES['fileToUpload']['name']) as $key){
if($_FILES['fileToUpload']['error'][$key] == 4) continue;
$fileExtension = strtolower(strrchr($_FILES['fileToUpload']['name'][$key], "."));
$error |= ! in_array($fileExtension, $validExtensions);
$error |= ! $_FILES['fileToUpload']['error'][$key] == 0;
if($error){
$result=false;
break;
}
}
also find this code:
// if(!in_array(false ,$upload_ok))
if ($upload_ok == true)
{
foreach($_FILES as $key => $file)
{
if ($file['error'] == 0)
{
$newNamePrefix = $picName . '_';
$CounterPrefix = sprintf("%02d",(preg_replace("/[^0-9]/","", $key)));
$fileExtension = strtolower(strrchr($file['name'], "."));
$manipulator = new ImageManipulator($file['tmp_name']);
$newImage = $manipulator->resample(1024, 1024);
$manipulator->save($imgRoot . $maschineFolder . $picFolder . $newNamePrefix . $CounterPrefix . $fileExtension);
}
}
}
and replace it with:
if ($error === 0){
foreach(array_keys($_FILES['fileToUpload']['name']) as $key){
if ($_FILES['fileToUpload']['error'][$key] == 0){
$newNamePrefix = $picName . '_';
$CounterPrefix = sprintf("%02d",(preg_replace("/[^0-9]/","", $key)));
$fileExtension = strtolower(strrchr($_FILES['fileToUpload']['name'][$key], "."));
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name'][$key]);
$newImage = $manipulator->resample(1024, 1024);
$manipulator->save($imgRoot . $maschineFolder . $picFolder . $newNamePrefix . $CounterPrefix . $fileExtension);
}
}
}
and change your inputs from
<input type="file" name="fileToUpload1" id="fileToUpload1" accept="image/*" />
<input type="file" name="fileToUpload2" id="fileToUpload2" accept="image/*" />
<input type="file" name="fileToUpload3" id="fileToUpload2" accept="image/*" />
to this
<input type="file" name="fileToUpload[]" accept="image/*" />
<input type="file" name="fileToUpload[]" accept="image/*" />
<input type="file" name="fileToUpload[]" accept="image/*" />
or this when you need the reference to the image
<input type="file" name="fileToUpload[1]" accept="image/*" />
<input type="file" name="fileToUpload[2]" accept="image/*" />
<input type="file" name="fileToUpload[3]" accept="image/*" />
When checking images, it's best not to rely on the extension. You can do the following to verify the image type:
$info = getimagesize($_FILES['image']['tmp_name']);
$mime = $info['mime'];
$mime should now contain a string such as "image/jpeg". Here's a link to a list of the mime type values.
Well you can use break; and continue; to navigate loops. Not sure what's your desired outcome though.