Keyword search of file names in PHP - 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>";
}
}
}
}

Related

PHP - Generate dropdown List of images -> Copy image to new Dir -> Delete original image

I have a drop down list that generates all files in a folder, which is working. But i would like to only see .jpg files and also i would like to exclude one file from the list as it is a place holder image lets call it "0001_Place_Holder.jpg".
The second part to this is that i want to pick a file from the dropdown list and copy it to a New folder then delete the original image.
this is "move_files_general.php" // which generates my dropdown list
<?php
$dirname = "general_2";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != ".."))
{
echo "<option value=".$file.">$file</option>";
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality" class="submit" />';
echo '</form>';
?>
This is "move_general.php" // which should copy the file then delete the original
<?php
$dirpath = "general_2";
$dirpath_2 = "quality_2";
$file_to_move = $_GET['file2'];
copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move") or die("Unable to copy");
if (copy("$dirpath.'/'.$file_to_move", "$dirpath_2.'/'.$file_to_move")) {
unlink("$dirpath.'/'.$file_to_move");
if ( unlink ($dirpath.'/'.$file_to_move) ) {
echo $file_to_move . " deleted.";
echo '<script>parent.window.location.reload(true);</script>';
} else {
echo "Error.";
}
}
?>
You would test the filename if its extension is jpg and if it is not equal to your placeholder name.
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
For the second issue: try to set the folder permissions to 777 for testing purpose. Also echo the strings that you pass to copy(string1,string2) in order to check if something is wrong in there.
First off, Thanks for your answers, and help. Alex Odenthal, that worked for the 1st part. i tried everything to get the 2nd part to work. I finally rewrote it a different way and it's working now, I must have had something wrong , somewhere.
Here is my fixed "move_files_general.php"
<?php
$dirname = "general";
$dir = opendir($dirname);
echo '<form action="move_general.php" method="get">';
echo '<select name="file2">';
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "0001_Place_Holder_DO_NOT_DELETE.jpg"))
{
if(pathinfo($file, PATHINFO_EXTENSION) ==='jpg'){
echo "<option value=".$file.">$file</option>";
}
}
}
echo '</select>';
echo '<input type="submit" value="Move To Quality1" class="submit" />';
echo '</form>';
?>
Here is my fixed "move_general.php"
<?php
$file_to_move = $_GET['file2'];
$source = "general/$file_to_move";
$dest = "quality/$file_to_move";
copy($source, $dest);
if (copy($source, $dest)) {
unlink($source);
if(file_exists($source)) {
unlink($source); }
else {
echo "Deleted.";
}
}
?>

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);

display image from a directory and text from a text file

a current project of mine is giving me some trouble. The web page in question is supposed to display text from a text file followed by an accompanying image from a directory.
Currently, the output is text 1, image 1, text 2, image 1, text 1, image 2, text 2, image 2
My code so far:
foreach ($DirEntries as $Entry)
{
if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
{
$inputFile = fopen("imagelist.txt", "r");
if ($inputFile)
{
while (($line = fgets($inputFile)) !== false)
{
echo "Name, description, and file name:<br />" . $line."<br>";
echo "<img src=\"files/" . $Entry . "\" ><br /><br />\n";
}
}
else
{
echo "There was an error in the opening file";
}
fclose($inputFile);
}
}
closedir($DirOpen);
?>
Any help would be greatly appreciated.
Your problem appears to be the nested while loop since you're dealing with a one to one relationship.
This should solve the problem for you:
$inputFile = fopen("imagelist.txt", "r");
// probably better to check for file readability before looping the directory items.
if (!$inputFile) {
echo "There was an error in the opening file";
}
else {
foreach ($DirEntries as $entry)
{
if($entry === '.' || $entry === '..')
{
continue; // using a continue helps keeps the code indentation levels down.
}
// assuming that each line corresponds to an image in the same order
if (($line = fgets($inputFile)))
{
echo "Name, description, and file name:<br />" . $line."<br>";
echo "<img src=\"files/" . $entry . "\" ><br /><br />\n";
}
else
{
echo "Image '$entry' has no metadata";
}
}
fclose($inputFile);
}
closedir($DirOpen);
Good luck!

Array of folders in directory and show files in each folder, rename/delete option

This is a follow up question to a thread I came across here.
Users can upload pictures to my site, and they are saved in an 'uploads' folder. Another page on the site has a photo gallery that pulls pictures from an 'approved' folder. How do I go about including a link (or checkbox) to rename or delete each file, after the file name? i.e.:
<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li class="title">';
if(is_dir($dir.'/'.$ff)){
echo $ff;
listFolderFiles($dir.'/'.$ff);
}else{
echo ''.$ff.''.
'...Keep -
Delete';
}
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles('uploaded_files');
?>
<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li class="title">';
if(is_dir($dir.'/'.$ff)){
echo $ff;
listFolderFiles($dir.'/'.$ff);
}else{
echo ''.$ff.'';
echo ''.$ff.'';
}
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles('uploaded_files');
?>
In delete.php, take the File Argument $_GET['file'];
<?php
$file = "root/".$_GET['file'];
unlink($file);
location('back to the page');
?>
In rename.php get the new name and
<?php
$file = "root/".$_GET['file'];
rename($file,"New file name");
location('back to the page');
?>
Now there are two ways to going about, Use ajax in main page or in rename.php take the new file name as input and do renaming.

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>";
?>

Categories