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'];
?>
Related
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!
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>";
}
Hello I do the PHP Upload multiple files, but my form does not require to upload all field (require just at least one field upload) so user may not upload the second input field.
The problem is if user upload only 1 file, user will get the error "Invalid file" (final else statement).
But if user upload all 2 fields, it does not have error, I guess the error come from null upload field. So I use if not empty first, but it's not work. How should I do?
<form action="upload.php" method="post" enctype="multipart/form-data">
Image 1 :
<input type="file" name="images[]" />
<br>
image 2 :
<input type="file" name="images[]" /> <br>
<input type="submit" value="Upload" />
</form>
in upload.php page
if(!empty($_FILES))
{
$count = count($_FILES["images"]["name"]);
for($i=1; $i <= $count; $i++)
{
if ((($_FILES["images"]["type"][$i-1] == "image/gif")
|| ($_FILES["images"]["type"][$i-1] == "image/jpeg")
|| ($_FILES["images"]["type"][$i-1] == "image/png"))
&& ($_FILES["images"]["size"][$i-1] < 2000000)) //2 MB
{
if ($_FILES["images"]["error"][$i-1] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
if (file_exists("path/to/".$_FILES["images"]["name"][$i-1] ))
{
echo "<b>".$_FILES["images"]["name"][$i-1] . " already exists. </b>";
}
else
{
$newname = date('Y-m-d')."_".$i.".jpg";
move_uploaded_file($_FILES["images"]["tmp_name"][$i-1] , "path/to/".$newname);
}
}
}
else
{
echo "Invalid file" ;
exit();
}
}
}
You can change your first line to:
if(isset($_FILES["images"]["name"][0])) {
With one or multiple files this can work
on line with:
echo "Invalid file" ;
exit();
this can be a problem, because if the first file have a problem you exit aplication and not process the second or others.
i suggest to you this code, too:
<?php
if (isset($_FILES["images"]["name"][0])) {
$path_upload = 'path/upload/';
$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>
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 (in_array($file_type, $allowed_types) && $file_size < 2000000) {
if ($file_error > 0) {
echo 'Upload file:'.$file_name.' error: '.$file_error.$nl;
} else {
$path_new_upload = $path_upload.$file_name;
// verify while filename exists
while (file_exists($path_new_upload)) {
$ext = explode('.', $file_name); // explode dots on filename
$ext = end($ext); // get last item of array
$newname = date('Y-m-d_').$i.'.'.$ext;
$path_new_upload = $path_upload.$newname;
}
move_uploaded_file($file_tmp, $path_new_upload);
}
} else {
echo 'Invalid file type to: '.$file_name.$nl;
// continue the code
}
}
}
Can be better, this verify filename to new creation.
Please help me
My html code is as follows:
here image_name is getting through echo from another upload query
My upload script code
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)){
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')");
echo "<img src='uploads/".$actual_image_name."' class='previewOfimgss'> ";
$allimages_name = "$actual_image_name";
echo "$allimages_name";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
It is working quite good and giving result like
and i want images names in on textbox like
$items=$_POST["post_items"];
$final = "";
foreach($items as $item){
$final .= $item."<br>";
}
echo $final
And you can then pass the $final variable to the column.
There is another way to do it.
$items= $_POST["post_items"];
$final = implode("<br>",$items);
It will work only if $items is array.
Ok I've done a working solution for you. This is a kind of prototype of your system. Hope it helps you in what you are building.
fileForm.php (Where you select file to upload.)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="uploadFile.php" method="post" enctype="multipart/form-data">
<input type="file" name="photoimg[]" multiple="yes">
<input type="submit" name="fileUploader">
</form>
</body>
</html>
uploadFile.php (Where you upload your files as in your question)
<?php
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$path = "uploads/"; // Upload directory
// Return's files extension
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP"); // Valid formats to upload
$fileCount=count($_FILES["photoimg"]["name"]); // Number of files uploaded
$files=array(); // Initilize an empty array to save names
// Loop through all files and upload them
for ($i=0; $i < $fileCount; $i++) {
$name=$_FILES["photoimg"]["name"][$i];
$tmp=$_FILES["photoimg"]["tmp_name"][$i];
$size=$_FILES["photoimg"]["size"][$i];
// If name is not empty
if(!empty($name)){
$ext = getExtension($name); // Get file extension
// If file is valid to upload
if(in_array($ext,$valid_formats)){
If file is less than 1 MB.
if($size<(1024*1024)){
$actual_image_name = time().substr(str_replace(" ", "_", $name), 5); // Final name of image
// If file uploads successfully
if(move_uploaded_file($tmp, $path.$actual_image_name)){
$time=time();
$ip=$_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')"); // Insert into your table
echo "<img src='uploads/$actual_image_name' class='previewOfimgss'> "; // Show the image
$files[$i] = $actual_image_name; // Save file names
}else{
echo "Fail upload folder with read access.";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}
}
?>
<form action="toSaveFileName.php" method="post">
<?php
for ($i=0; $i < $fileCount; $i++) {
// Generate input fields
echo "<input type='text' name='post_items[]' value='{$files[$i]}'>";
}
?>
<input type="submit">
</form>
toSaveFileName.php (This is what you originally asked for.)
$items=$_POST["post_items"]; // from input fields
$todb=""; // to send to database
if(is_array($items)){
$todb=implode("<br>",$items);
}else{
$todb=$items;
}
echo $todb; // for output
//save to database
Now implementing it to your system is your job. And I hope you should be able to do it on your own.
Don't forget to mark this as answer and vote up.
What I am trying to put images where my folder is generate from "$tablename", but fail to bring the image there. How do I store the uploaded files ?
I like to upload images from my form.
<input type="file" id="file" name="files" multiple />
No matter which of those upload techniques I use is not good to use, to save the file to a specific location on the server.
If you have an idea how to do this problem please.
here is the mkdir code. The code is works fine.
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die("" . mysql_error() . "" . $qShowStatus);
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string) ("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If (!file_exists($year)) {
$createsyear = mkdir("$year", 0777);
} else {
If (!file_exists("$year/$month")) {
$createsmonth = mkdir("$year/$month", 0777);
} else {
If (!file_exists("$year/$month/$day")) {
$createsday = mkdir("$year/$month/$day", 0777);
} else {
If (!file_exists($year / $month / $day / $tablename)) {
$createsday = mkdir("$year/$month/$day/$tablename", 0777);
} else {
//dada
}
}
}
}
?>
Thank You.
Here I give basic example for file upload.
in HTML
<form action="phpfilename.php" method="post" enctype="multipart/form-data" >
<input type="file" name="files" />
<input type="submit" name="submit" />
</form>
In PHP
<?php
if(isset($_POST['submit']))
{
$path = $_FILES["files"]["name"];
$target = "$year/$month/$day/$tablename/$path"; //this is your path where image need to be saved
move_uploaded_file($_FILES["files"]["tmp_name"], $target);
}
?>
I fix the problem
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "" . mysql_error() . "" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string)("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If(!file_exists($year)){
$createsyear = mkdir("$year", 0777);
}
else
{
If(!file_exists("$year/$month")){
$createsmonth = mkdir("$year/$month", 0777);
}
else
{
If(!file_exists("$year/$month/$day")){
$createsday = mkdir("$year/$month/$day", 0777);
}
else
{
If(!file_exists($year/$month/$day/$tablename)){
$createsday = mkdir("$year/$month/$day/$tablename/", 0777);
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$target = "$year/$month/$day/$tablename/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $target.$name)) {
$count++; // Number of successfully uploaded files
}
}
}
}
}
}
else
{
}
}
}
}
?>