PHP multiple upload runs the loop once even no files submitted - php

I am trying to upload multiples files using PHP and HTML but even I set the validation in my code isset, the foreach loop runs once with empty submission.
<?php
if (isset($_FILES['fileToUpload']))
{
foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key . $_FILES['fileToUpload']['name'][$key];
$file_size = $_FILES['fileToUpload']['size'][$key];
$file_tmp = $_FILES['fileToUpload']['tmp_name'][$key];
$file_type = $_FILES['fileToUpload']['type'][$key];
move_uploaded_file($file_tmp, getcwd() . "/" . time() . $file_name);
}
echo "Success";
}
else
{
echo "<form enctype='multipart/form-data' action='' method='POST'>";
echo "File:<input name='fileToUpload[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
echo "</form>";
}
?>

You have to check the file name whether it is empty or not before run the foreach loop using PHP
<?php
if (isset($_FILES['fileToUpload']))
{
if($_FILES['fileToUpload']['tmp_name'][0] == "") {
die("No files to upload");
}
else {
// Now there are some files you can run upload method here
foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name) {}
}
}
?>

You can check errors for UPLOAD_ERR_NO_FILE or just check for general errors (as below).
<?php
if($_FILES['userfile']['error'] == 0) {
// do something
} else {
// handle
}

Related

How to add subfolders delete functionality

This is the script it deletes all the files from a directory but it is not deleting the empty subfolders and subfolders with files in it.
<?Php
$dir='directory name here'; // directory name
$ar=scandir($dir);
$box=$_POST['box']; // Receive the file list from form
// Looping through the list of selected files ///
while (list ($key,$val) = #each ($box)) {
$path=$dir ."/".$val;
if(unlink($path)) echo "Deleted file ";
echo "$val,";
}
echo "<hr>";
/// displaying the file names with checkbox and form ////
echo "<form method=post name='f1' action=''>";
while (list ($key, $val) = each ($ar)) {
if(strlen($val)>3){
echo "<input class=roundedOne id=roundedOne type=checkbox name=box[] value='$val'>$val<br>";
}
}
echo "<input class=button1 type=submit value='Delete'></form>";
?>
This function will delete subfolders and its files:
function removeDir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object !== '.' && $object !== '..') {
if (filetype($dir.'/'.$object) === "dir") {
removeDir($dir . '/' . $object);
}
else {
unlink($dir.'/'.$object);
}
}
}
reset($objects);
unlink($dir);
}
}
You can use it by executing removeDir($dir);

php delete file from directory doesn't work

I have code like this however it doesn't delete. I check console if there is an error, no; there is no error appearing either. Can you help that can delete properly files in the pointing directory.
<?php
$dir = 'C:\xampp\htdocs\phpex\uploads';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST['filenames'] ) ) {
foreach( $_POST['filenames'] as $key => $file ) {
unlink( $dir . '\\' . $file );
}
echo 'Files deleted';
}
else {
echo 'No files selected';
}
}
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input name='filenames[]' value='".($files1[$n])."' type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo "<input type='submit' value='Delete'>";
echo "</form>";
echo "</div>";
?>
Your code of deleting is alright. It must work.
Obviously, the problem is in input: something wrong in $_POST['filenames'].
Insert log right before unlink and examine it.

Keyword search of file names in PHP

With another coder's help, I have PHP code that creates a photo gallery with auto-created thumbnail images of any image files in the directory. (It's open source, so anyone else is free to use and modify as they desire.)
I use it as a stock photo library and the file names include the keywords for that image. For example, one might be businessman-tie-suit-briefcase-office-meeting.jpg.
I've been trying to add a keyword search input that looks at the file names, but cannot figure out how to proceed. I've built keyword searches for a database, but this directory file name search is new to me.
Here's the relevant code of the page:
<?
$gallery = $_GET["gallery"];
$dir = $dir.$gallery."/";
//Put files into an array
// create a handler to the directory
$dirhandler = opendir($dir);
// read all the files from directory
$nofiles=0;
while ($file = readdir($dirhandler)) {
// if $file isn't this directory or its parent
//add to the $files array
if ($file != '.' && $file != '..')
{
$nofiles++;
$files[$nofiles]=$file;
}
}
//close the handler
closedir($dirhandler);
//Back button to appear at the top of each page to go to the previous directory if not on the main page
if ($gallery !="" or $keyword !="")
{
echo "<div><a href='javascript:history.go(-1)'><img src='images/up.png' border='0'></a></div>";
}
// BEGINNING ADD FOR KEYWORD SEARCH
// KEYWORD SEARCH BOX- create text box to search entire directory for that keyword and display page in grid pattern with results
?>
<div style='position:relative; left:10px;'>
<form action='index_search.php?keyword=$keyword' method='get' name='search'>
<input type='text' name='keyword' size='25'>
<input type='submit' value='Search Keyword'>
</form>
</div>
<?
//*************************************************************************//
// PERFORM KEYWORD SEARCH
if ($keyword !="")
{
echo "<div class='keytext'>Keyword search: <b>" . $keyword . "</b><br/></div>";
/*********************************************************************************************************/
/* ***** THIS IS WHERE THE SEARCH OF DIRECTORY FILES NEEDS TO OCCUR AND OUTPUT RESULTS AS $files */
/* get results where $file LIKE %$keyword%; */
/*********************************************************************************************************/
//Show images
foreach ($files as $file)
{
if ($file!="."&&$file!="..")
{
$extention = explode('.', $file);
if ($extention[1] != "")
{
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group'' href='$dir$file' return false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'/>";
echo"</a><br/>";
$file_name = current(explode('.', $file));
echo substr($file_name,0,21);
echo "</div>";
}
}
}
}
else { // starts the split from keyword or no keyword
//***********************************************************************//
// sort folder names alphabetically, ignore case
natcasesort($files);
//Show the folders
foreach ($files as $file){
if ($file!="."&&$file!="..")
{
sort($files); //Sorts the array (file names) alphabetically -- not the directory/folder names
$extention = explode('.', $file);
if ($extention[1] == "")
{
echo "<div class='imgwrapper'>";
echo "<a href='?gallery=$gallery/$file'>";
echo "<img src='images/folder.jpg' border='0'>";
echo "<div class='folder'>";
echo current(explode('.', $file));
echo "</a>";
echo "</div>";
echo "</div>";
}
}
}
?>
<div style="clear:both"></div>
<?
//Show images
foreach ($files as $file){
if ($file!="."&&$file!="..")
{
$extention = explode('.', $file);
if ($extention[1] != "")
{
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group'' href='$dir$file' return false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'/>";
echo"</a><br/>";
echo "<div class='title'>";
$file_name = current(explode('.', $file));
echo substr($file_name,0,125);
echo "</div>";
echo "</div>";
}
}
}
}
?>
I have the area commented out where I believe the search string would be executed, as the display code is already there. I've tried a few things that didn't work, so didn't bother listing any of it.
Any ideas if I'm going about this the wrong way?
Thanks in advance.
if ($extention[1] != "")
{
if(stripos($file, $keyword) !== false)
{...
}
}
See (stripos() manual)
I was able to get this resolved from some outside help.
if ($file!="."&&$file!="..")
{
sort($files); //Sorts the array (file names) alphabetically -- not the directory/folder names
$extention = explode('.', $file);
if ($extention[1] == "")
{
$dir = "pics/";
$dir = $dir.$file."/";
$dirhandler = opendir($dir);
// read all the files from directory
$nofiles=0;
$files2=array();
while ($file2 = readdir($dirhandler)) {
if ($file2 != '.' && $file2 != '..')
{
$nofiles++;
$files2[$nofiles]=$file2;
}
}
closedir($dirhandler);
sort($files2); //Sorts the array (file names) alphabetically -- not the directory/folder names
//Show images
foreach ($files2 as $file2){
if ($file2!="."&&$file2!="..")
{
$extention = explode('.', $file2);
if ($extention[1] != "" && stripos($file2,$keyword)!==false)
{
echo "<div class='imgwrapper'>";
echo"<a class='fancybox' rel='group'' href='$dir$file2' return false' title='$filename'>";
echo "<img src='timthumb.php?src=$dir$file2&h=$height&w=$width' alt='$extention[0]' width='$width' height='$height'/>";
echo"</a><br/>";
echo "<div class='title'>";
$file2_name = current(explode('.', $file2));
echo substr($file2_name,0,125);
echo "</div>";
echo "</div>";
}
}
}
}

droplist only with specific file with php

I'm currently making a droplist but in the droplist let's say I only want to include only .txt extension files so any other extensions like .php .jpg or any other extensions will not be in in the droplist. How can I do that as simple as possible?
Another question is I want to make a warning IF the folder does not have any .txt extension files an error message will show. So even if there are other .jpg .php or any other files inside as long as there's no .txt file in the folder a warning will show.
Anyone able to give me a hand?
This is what I have done but it only shows a drop-list with no .txt at the end but it will still show other random files in the drop-list though.
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if(($list == ".") || ($list == ".."))
{
continue;
}
echo "<option value=\"";
echo basename($list,".txt");
echo "\">";
echo basename($list,".txt");
echo "</option>";
}
echo "</select>";
echo "</form>";
editted added the substr with $hasTxt
<?php
if(!(is_dir("./aaa")))
{
die("Must create a <strong>aaa</strong> folder first, sorry");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select name=\"aaa\">";
$aaa_files = scandir("./aaa");
$hastxt = false;
foreach($aaa_files as $file_list)
{
if(($file_list == ".") || ($file_list == ".."))
{
continue;
}
if(strlen($file_list)>4 && strtolower(substr($file_list, -4))!='.txt')
{
continue;
}
else
{
$hastxt = true;
echo "<option value=\"";
echo basename($file_list,".txt");
echo "\">";
echo basename($file_list,".txt");
echo "</option>";
}
}
echo "</select>";
echo "<br/><input type=\"submit\">";
echo "</form>";
if($hastxt == false)
{
echo "Must create text files first, sorry";
die();
}
?>
This is what happens for the script that I have now if the folder does not have any txt files.
This is what I actually want if there's no txt file but of course without the arrow
For the first part, just like you continue on directories . and .., you can continue on non-text files:
if(strlen($list)>4 && strtolower(substr($list, -4))!='.txt') continue;
For the warning part, put a flag before the foreach
$hasTxt = false;
And set it to true whenever you get input you don't ignore (ie. after the if(unwanted) continue;)
$hasTxt = true;
Finally, after the foreach check the value of $hasTxt and use it as you prefer.
You could use PHP's substr() function to test the filenames:
if(substr($filename, -3) == 'txt') {
// show file
}
See here: http://php.net/manual/en/function.substr.php
Try this , Hope it will work you
<?php
if(!(is_dir("./aaa")))
{
die("Must create a folder first, sorry");
}
$lists = scandir("./aaa");
$i =0;
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
$i++;
}
}
if($i == 0){
die("the folder does not have any .txt extension files");
}
echo "<form action=\"./page2.php\" method=\"get\">";
echo "<select>";
foreach($lists as $list)
{
if (strstr($list, '.txt')) {
echo "<option value=\"".substr($list,0, -4)."\">".substr($list, 0,-4)." </option>";
}
}
echo "</select>";
echo "</form>";
?>

Something wrong with my code? Multiple Upload PHP file

Here is the code i made, im expecting it to work but somewhere there must be an error. I can't figure out myself, Please help.
<?php
if(isset($_POST['submit'])){
$max_size = 500000;
$image_upload_path = "images/products/";
$allowed_image_extension = array('jpg','jpeg','png','gif');
for($i=0;$i<2;$i++)
{
//check if there is file
if((!empty($_FILES['image[]'][$i])) && ($_FILES['image[]']['error'][$i]==0))
{
//check extension
$extension = strrchr($_FILES['image']['name'][$i], '.');
if(in_array($extension,$allowed_image_extension))
{
//check file size.
if($_FILES['image']['size'][$i] > $max_size)
{
echo "file too big";
}
else if($_FILES['image']['size'][$i] < 1)
{
echo "file empty";
}
else
{
//we have pass file empty check,file extension check,file size check.
$the_uploaded_image = $_FILES['image']['tmp_name'][$i];
$the_uploaded_image_name = $_FILES['image']['name'][$i];
//replace empty space in filename with an underscore '_'
$the_uploaded_image_name = preg_replace('/\s/','_',$the_uploaded_image_name);
//get the file extension
$the_uploaded_image_extension = explode(',',$the_uploaded_image_name);
$the_new_image_name = $the_uploaded_image_name."".md5(uniqid(rand(),true))."".$the_uploaded_image_extension;
$save_image_as = $the_new_image_name;
//check file exist
if(file_exists($image_upload_path."".$the_new_image_name))
{
echo "file".$image_upload_path."".$the_new_image_name." already exist";
}
else
{
if(move_uploaded_file($the_uploaded_image,$save_image_as))
{
echo "image".$the_uploaded_image_name." uploaded sucessfully";
//set the image path to save in database column
}
else
{
echo "there was an error uploading your image.";
}
}
}
}
else
{
echo "extension not allowed";
}
}
else
{
echo "please choose file to upload";
}
}
}
?>
<html>
<head><title>image upload</title></head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image[]"/>
<input type="file" name="image[]"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
This is my new PHP code . Im getting both the result as found found not found not found. Will someone tell me what am i doing wrong here. The if else condition is seems to be not working as both the conditions are giving ouput. Why?
<?php
if(isset($_POST["submit"])) {
echo $_POST["submit"];
echo "<br/>";
for($i=0;$i<count($_FILES['image'])-1;$i++)
{
if(!empty($_FILES['image']['tmp_name'][$i]))
{
echo "found";
echo "<br/>";
}
else
{
echo "not found";
echo "<br/>";
}
}
}
else
{
echo "form is not posted";
}
?>
I guess the obvious WTF would be $_FILES['image[]'][$i], which should just be $_FILES['image'][$i] (the [] in the name makes it an array, it's not part of the name).
I'm unwilling to troubleshoot anything beyond this for you without more information. Try this at various points in the code:
echo '<pre>';
var_dump($_POST); // or other variables
echo '</pre>';
This should help you to debug your own code, something you must learn to do.

Categories