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.
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;
}
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
This question already has an answer here:
Multiple Picture Upload Problems
(1 answer)
Closed 6 years ago.
I have a simple script that can upload files on my server and insert the details into database.
With code below I am getting two errors..
"Notice: Undefined variable: sExt in" ..
I tried to fix the issue with if empty statement, but without sucess..
Script import numbers (1,2,3...) into Mysql if the upload filed is empty....
I tried to fix the issue with the code below, but also without success..
"if($_FILES['files']['name']!="")"...
Any advice?
Thank you..
My code:
<?php
include_once('db.php');
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$query = "INSERT into user_pics (`person_id`,`pic_name`,`pic_type`) VALUES('1','$file_name','$sExt')";
$result = mysqli_query($link,$query);
$desired_dir = "user_data/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Files Uploaded !" . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
print_r($errors);
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key+1) . ' = $row[0];';
eval ($codestr);
} else {
$codestr = '$file' . ($key+1) . ' = NULL;';
eval ($codestr);
}
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" accept="image/*"> <br/>
<input type="file" name="files[]" accept="image/*"> <br/><br/>
<input type="submit"/>
</form>
instead of this
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
You should do
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}else{
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
Checking the extension you are setting is redundant, and this avoids the error when your varible $sExt is not set, by providing a default ( with else ). This should give you the desired behaviour.
I would also move these lines
$query = "INSERT into user_pics (`person_id`,`pic_name`,`pic_type`) VALUES('1','$file_name','$sExt')";
$result = mysqli_query($link,$query);
$desired_dir = "user_data/";
if (empty($errors)) {
To the inside of this code block
if (empty($errors)) {
$query = "INSERT into user_pics (`person_id`,`pic_name`,`pic_type`) VALUES('1','$file_name','$sExt')";
$result = mysqli_query($link,$query);
$desired_dir = "user_data/";
That way you don't do the insert when you have something in errors...
Not sure the purpose of this
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key+1) . ' = $row[0];';
eval ($codestr);
} else {
$codestr = '$file' . ($key+1) . ' = NULL;';
eval ($codestr);
}
}
But eval can be very very bad, I would suggest doing this another way such as using an array, however this probably could be accomplished in the first loop. For example the null or false value could be in the else part of the check for empty($errors) so that if there is an error, that one is put in false like.
$files = array();
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$files['$file' . ($key+1)] = $row[0];
} else {
$files['$file' . ($key+1)] = false; //id use false instead of null in an array
}
}
You should also be careful of sql injection, although it looks like you are setting the variables, its still wise to use a prepared query just in case changes are made latter, that could open you up to SQL injection attacks.
and:
// double slash
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
// file was successfuly moved
echo "Files Uploaded !" . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
foreach ($uploadedFiles as $key => $row) {
if ($row[1]) { // $row[1] is never empty
${'file' . ($key+1)} = $row[0];
} else {
${'file' . ($key+1)} = NULL;
}
}
better will be:
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
echo "Files Uploaded !" . $_FILES['files']['name'][$key];
$uploadedFiles[] = $file_name . $sExt;
}
//instead of variable $file1 etc..
foreach($uploadedFiles as $filename){
}
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];
}
}