Multi image upload validate by php - php

i modified my upload code based on this post https://stackoverflow.com/a/30074716/14787718 (its working code)
but my code does not work, please help.
my full code here: https://sandbox.onlinephpfunctions.com/code/c62b6bdf6fadd5aff63b2e7e65e75c1075d1dbb0
<?php
if (isset($_POST['upload']) && $_FILES['image']['error']==0) {
$j = 0; //Variable for indexing uploaded image
for ($i = 0; $i < count($_FILES['image']['name']); $i++) {//loop to get individual element from the array
$allow_ext = array('png','jpg','gif','jpeg','bmp','tif');
$allow_type = array('image/png','image/gif','image/jpeg','image/bmp','image/tiff');
$image_name = $_FILES['image']['name'][$i];
$image_type = getimagesize($_FILES['image']['tmp_name'][$i]);
$image_name = explode('.',$image_name);
$ext = end($image_name);
$j = $j + 1;//increment the number of uploaded images according to the files in array
if(in_array($ext, $allow_ext) && in_array($image_type['mime'], $allow_type)){
list($width, $height, $mime) = getimagesize($_FILES['image']['tmp_name'][$i]);
if ($width>0 && $height>0) {
$upload = move_uploaded_file($_FILES['image']['tmp_name'][$i], "uploads/".$_FILES['image']['name'][$i]);
if ($upload) {
echo '<p>File Uploaded: View Image</p>';
}
} else {
echo 'Error: Only image is allowed!';
}
} else {
echo 'Error: Invalid File Type!';
}
}
}
?>
thank you!

first move the Jquery call to place it before bootstrap:
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/js/bootstrap.min.js'></script>
And at your first test : if (isset($_POST['upload']) && $_FILES['image']['error']==0). $_FILES['image']['error'] is an array.
Delete this test to keep only if ( isset($_POST['upload']) )
Add this test in you for step:
for ($i = 0; $i < count($_FILES['image']['name']); $i++) {//loop to get individual element from the array
if ($_FILES['image']['error'][$i]==0) {
Tested, it works fine!

Related

Display uploaded file or image in grid in php

I have successfully uploaded some images to the server. Im thinking to display them in my admin page in grid view.. currently it displayed vertically.
Can anyone help?
Thanks in advance for you kind assistance.
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
if($files[$i] !='.' && $files[$i] !='..')
{
// get file name
echo "File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}
}
}
}
?>
This code works fine but I just don't know to display it in grid or table..
You can achieve that by echoing each table part inside the loop:
<?php
$dir_path = "../../img/gallery/";
$extensions_array = array('jpg','png','jpeg');
$numCol = 3;
if(is_dir($dir_path))
{
$files = scandir($dir_path);
for($i = 0; $i < count($files); $i++)
{
$n = 0;
echo '<table>';
echo '<tr>';
if($files[$i] !='.' && $files[$i] !='..')
{
$n ++;
// get file name
echo "<td>File Name: $files[$i]<br>";
// get file extension
$file = pathinfo($files[$i]);
$extension = $file['extension'];
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'></td>";
if($n % $numCol == 0) echo "</tr><tr>";
}
echo '</tr>';
echo '</table>';
}
}
?>
$numCol defines how many column must have every table's row.
Also, I removed these {} that were useless:
$extension = $file['extension'];
{
// show image
echo "<img src='$dir_path$files[$i]' style='width:60px;height:80px;'><br>
</br>";
}

How to random name FILES and keep old TYPE_FILE in loop

for example i want to upload file name moble.jpg and i want to store it like XXDSSDFS.jpg i try to use pathinfo but when i print_r it return nothing, I think i should return like jpg or png .
NOTE assume that i upload 2 img
$text = $_POST['spec_text'];
$file_spec = $_FILES['spec_file']['name'];
$typefile = $_FILES['spec_file']['type'];
$sizefile = $_FILES['spec_file']['size'];
$filename = md5($_FILES['spec_file']['tmp_name']);
$a = count($file_spec);
for ($i=0; $i < count($file_spec); $i++) {
if ($typefile[$i] == 'image/png' OR $typefile[$i] == 'image/jpeg')
{
echo "string".$filename;
}else{
echo "eror";
}
}

Is it possible to add action only at LOOP's final round?

I want to do redirect to other page after finish the loop
something like this
for($i = 0; $i < 5; $i++)
{
echo $i;
header('Location: home.php'); // do this if finish the loop
}
Note : My case the redirect has to be in loop because my real code is about upload multiple files in loop and check file type in loop so I want to not redirect if it has wrong filetype, and if upload correctly, redirect to home.php page too. but the problem is when I upload correctly in first round loop it will redirect to home page without doing upload residual files.
and If I put redirect outside of loop , the errormessage of filetype will not show because it will redirect to home only.
$path_upload = 'images/cover/';
$count = count($_FILES["images"]["name"]);
$allowed_types = array("image/gif", "image/jpeg", "image/png");
$nl = PHP_EOL.'<br>'; // Linux: \n<br> Window: \r\n<br>
$arr_newname = array();
for($i=0; $i < $count; $i++)
{
$file_type = $_FILES["images"]['type'][$i];
$file_name = $_FILES["images"]['name'][$i];
$file_size = $_FILES["images"]['size'][$i];
$file_error = $_FILES["images"]['error'][$i];
$file_tmp = $_FILES["images"]['tmp_name'][$i];
if($_FILES["images"]["name"][$i] != "")
{
if (in_array($file_type, $allowed_types) && $file_size < 2000000)
{
if ($file_error > 0) {
echo 'Upload file:'.$file_name.' error: '.$file_error.$nl;
} else {
$ext = explode('.', $file_name); // explode dots on filename
$ext = end($ext); // get last item of array
$newname = "album_id".$album_id."_".date('Y-m-d')."_".($i+1).".".$ext;
$arr_newname[$i] = $newname;
$path_new_upload = $path_upload.$newname;
if(move_uploaded_file($file_tmp, $path_new_upload))
{
$data = array(
'front_pic'.($i+1) => $arr_newname[$i]
);
$this->db->where('album_id', $album_id);
$this->db->update('oav_album', $data);
redirect('home.php'); ////////THIS will stop the residual round of loop
}
}
}
else
{
echo 'Invalid file type to: '.$file_name.$nl;
// continue the code
}
}
}
redirect('home.php'); ////////IF I put this outside loop it will not show error` message but redirect to home
You can write the statement after the loop so it works at the end of the loop for one time. If you want to use last known $i value you can define $i before the loop and use it after the loop.
$i = 0
for ($i = 0; $i < $count; $i++){
//loop
}
$i--;//get last value
echo $i;
header('Location: home.php'); // do this if finish the loop

Count number of uploaded file

I want to count number of uploaded file but I'm unable to get the error if no file had been uploaded. Here is my code for reference:
html
<input type="file" name="file[]" class="filestyle" data-buttonText="Quotation 1" multiple="multiple">
php
$total = count($_FILES['file']['name']);
if($total > '2'){
for($i=0; $i<$total; $i++){
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if($tmpFilePath != ""){
$shortname = $_FILES['file']['name'][$i];
$filePath = "uploads/" . date('d-m-Y-H-i-s').'-'.$_FILES['file']['name'][$i];
if(!$msgError && move_uploaded_file($tmpFilePath, $filePath)){
// insert to db and success msg
}
}
} elseif($total < '4') {
$msgError[] = "Need to upload 3 Quotations";
}
if(isset($msgError)){
$msgErrorString = implode(",",$msgError);
header("Location: pr_form.php?msgError=".$msgErrorString."");
}
If user upload less than 3 files, the error will not appear. I have other validations for user input. Everything is working except for the file validation. May I know why?
First: Remove the '
$total > '2' should be $total > 2
same with total < 4
Second:
It should be
count($_FILES) not count($_FILES['file']['name'])
So, in your problem ..
if no file had been uploaded.
$total = count($_FILES);
if($total > 2){
for($i=0; $i<$total; $i++){
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if($tmpFilePath != ""){
$shortname = $_FILES['file']['name'][$i];
$filePath = "uploads/" . date('d-m-Y-H-i-s').'-'.$_FILES['file']['name'][$i];
if(!$msgError && move_uploaded_file($tmpFilePath, $filePath)){
// insert to db and success msg
}
}
} elseif($total < 4 && $total > 0) {
$msgError = "Need to upload 3 Quotations";
}
elseif($total === 0){ //This condition
$msgError = "No chosen file.";
}
if(isset($msgError)){
header("Location: pr_form.php?msgError=".$msgError."");
}
And then in your pr_form.php, you should have something like this line..
<?php
echo $_GET['msgError'];
?>

php loop and skip over if file exists

I need some help with some PHP logic. I'm adding images to my directory where some images already exist. I'm trying to loop over the directory and skip over the names if they exist...hard to explain...here's what I have:
if(isset($_POST['imgName'])){
$artName = $_POST['imgName'];
if ($_FILES['file']['name'][0] != ""){
$num = 0;
for ($i=0; $i < count($_FILES['file']['name']); $i++){
$fileExt = str_replace("image/", ".", $_FILES['file']['type'][$i]);
$newFileName = "..//images/$num$artName$fileExt";
if (file_exists($newFileName)){
$num++;
$newFileName = "..//images/".$num.$artName.$fileExt;
move_uploaded_file($_FILES['file']['tmp_name'][$i], $newFileName);
}
}
}
}
I tried doing a while loop and a do while loop and I couldn't get it to work...maybe I was doing it wrong. Can I please get some advice? Thanks...
This is for a blog so the $artName is the article name...the $num [0] will be the main image and the rest will be the gallery images
WORKAROUND SOLUTION:
if(isset($_POST['imgName'])){
$artName = $_POST['imgName'];
if ($_FILES['file']['name'][0] != ""){
$pics = glob('..//images/*'.$artName.'*');
if($pics[0] != ""){
for($j=0; $j<count($pics); $j++){
$path = pathinfo($pics[$j]);
$ext = $path['extension'];
rename($pics[$j], "..//images/".$j.$artName.".".$ext);
}
}
$num = count($pics);
for ($i=0; $i < count($_FILES['file']['name']); $i++){
$fileExt = str_replace("image/", ".", $_FILES['file']['type'][$i]);
$newFileName = "..//images/$num$artName$fileExt";
move_uploaded_file($_FILES['file']['tmp_name'][$i], $newFileName);
$num++;
}
}
}
The workaround I came up with is checking the images related to the article which are already in the directory and renaming them. Then using the count(of images in the directory) and setting that to the $num and using the $num as part of the new image name...this way there are no duplicates. It there's a better solution, I'd love to hear it...

Categories