Avatar of alexgreen
alexgreen
 asked on

Search within protected directory

I have a protected area for members to log in (.htaccess) on a linux server with 1&1

I have a php script that shows the list of files in a certain directory and gives them a link to download dynamically displayed each time you open / refresh the page.
Unfortunately, there are lots of files and I think that as well as that I would like a search option

I want a simple search solution that will enable users to search for a particular document title to see if it is there and then download it with one click.

I figure PHP can do it as it could do the dynamic list. I like the way the google search box works but obviously it won't read behind the password protection.

I do not want to use mySQL because I have no desire to add a database to the back end and make my life difficult by having to learn another language.

Can anyone help out. I have scoured the web and I'm sure it is out there if I can find the right search terms myself but I keep hitting blanks.

thanks in advance
PHP

Avatar of undefined
Last Comment
alexgreen

8/22/2022 - Mon
GMGenius

Hi,

I think you want to look at

http://us2.php.net/manual/en/function.readdir.php

This will allow you to read the files and build an array. if you use reg expressions you could search!

I hope this helps
alexgreen

ASKER
Hmmmm, not sure.

I am happy for the user to have the complete list available, but then have a search box to narrow it down if they want to quickly dig for a file (I know that most browsers give the option to search on the page but not sure if all users would know / bother)

Here is my existing php code which I think I don't need to mess with.

I was thinking of adding a second mini form type thing as a search box which will display in the same way the google search will search a web site and display results, only in the secure area.
<?php
if ($handle = opendir("music/")) { 
 
  $thelist = array(); 
  while (false !== ($file = readdir($handle)))
    if (preg_match("/\.doc/i",$file))
  {
          if ($file != "." && $file != "..")
          {
                $thelist[] = '<a href="music/'.$file.'">'.$file.'</a><br />';
                }
       }
  closedir($handle);
  }
  sort($thelist);
  $thelist = implode("\n",$thelist);
?>
<?=$thelist?>

Open in new window

Ray Paseur

"search for a particular document title" could have a lot of meanings.  Almost any search solution that goes beyond the file names will work better if you learn to use the data base.  For that, I would recommend this book:

http://www.sitepoint.com/books/phpmysql4/

It is easy to follow and will advance your skillset very rapidly if you work through the examples.  It's been a part of my professional library since Version One.

Now having given the advice you NEED to hear, let me turn to the advice you probably WANT to hear ;-)

Look at the PHP function strpos().  If you aggregate the file names into an array, you can iterate over the array with foreach().  As you inspect each file name you can use strpos() to see if the search string is part of the file name.  If you want to post the code you are using now, perhaps we can offer more concrete assistance.  But at least this much advice should help point you in the right direction as you add this functionality to your app.

Best regards, ~Ray
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
alexgreen

ASKER
Thanks for your time, I'm not sure I completely follow you.

It seems that you are saying that there is no basic code that you can just plug into a little formmail type search which will just check to see if a word occurs in the title of a document and return a value to the page you are looking at.

If this is the case, I'm not interested in going any more complex. It is not a paid job, it's not a subscription-paid web site, I have other things to do with my time so don't want to get too intricate and code-heavy / fancy. Worst case, people will have to be prepared to scroll down the page to look with their eyes to see if we have the song lyrics they are after!

ATM the files are on the server and the current php (above) just lists the available files.
I was hoping a similar simple bit of code could be added separately to query a match for a particular word in the title of the documents on the server and return a value to the same page.

I didn't think that it would be so difficult to explain!

thanks for the help, if it isn't doable in really simple php terms, then thanks, but it isn't going to happen which is fine.
ASKER CERTIFIED SOLUTION
GMGenius

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
GMGenius

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ray Paseur

Hadn't seen your code posted above when I responded, but I think it should not be too hard to modify that or provide a working replacement.  The code from GMGenius looks partially right, however you will want to look closely at the man page for strpos() because the double-equal notation is not what you want.

Best regards, ~Ray
alexgreen

ASKER
@GMGenius

thanks

That looks interesting, it also looks like I would need to know how to ask the code something.
I assume this would basically replace the full list of songs and have a purely searchable list instead.

so the option would be not to browse and search but to only search!

What is the best way of sending a request to this code?

Do I put this on the page the search is pointing to or the page the search is coming from.

sorry about the noobness of the questions, I generally only deal in static content.

Would it be a form thing like this or am I missing something?


      <form action="/searchresults.php?search="" method="GET">
        <input class="search" type="text" name="search" id="search" maxlength="20" />
 <input name="Submit" type="submit" value="submit" />
      </form>
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
alexgreen

ASKER
Ah, you were already posting! I'll have a play.
Ray Paseur


<?php // RAY_search_directory.php - NOT CASE SENSITIVE
error_reporting(E_ALL);
echo "<pre>\n";
 
 
// IF THE SEARCH ARGUMENT HAS BEEN POSTED
if (!empty($_GET["q"]))
{
 
// NORMALIZE THE SEARCH STRING
    $q = trim(strtoupper($_GET["q"]));
// ACTIVATE THIS TO SEE THE SEARCH ARGUMENT
//  var_dump($q);
 
 
// GET THE LIST OF FILES IN THIS DIRECTORY
    $arr = scandir(getcwd());
// ACTIVATE THIS TO SEE ALL THE FILES
//  var_dump($arr);
 
 
// ITERATE OVER THE LIST OF FILENAMES FROM THIS DIRECTORY
    foreach ($arr as $p => $fn)
    {
 
// REMOVE FILENAMES WITH STRINGS THAT DO NOT MATCH THE SEARCH ARGS
// MAN PAGE: http://us2.php.net/manual/en/function.strpos.php
        $poz = strpos($fn, $q);
        if ($poz === FALSE) unset($arr[$p]);
    }
 
// SHOW WHAT WE HAVE LEFT IN THE ARRAY - MATCHING THE ARGS
    var_dump($arr);
 
} // END OF PHP, PUT UP THE FORM FOR INPUT VALUES
?>
<form>
ENTER SEARCH STRING
<input name="q" />
<input type="submit" />
</form>

Open in new window

alexgreen

ASKER
Awesome

That works like a dream, thank you thank you thank you.

I'd share the results but my Church might not like me giving out the login details!

thanks again, perfect.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
alexgreen

ASKER
Thanks Ray, it looks complicated.

@GMGenius  is there a line I can put in to get it to not be case sensitive?
GMGenius

Hi,

New updated code.

including case insensitive solution ( strtolower() )

Also I have shown how to allow a FULL list by providing no search value. Should work but did not test it.
<?php
 
$search = @$_GET["search"];
 
if ($handle = opendir("music/")) { 
 
  $thelist = array(); 
  while (false !== ($file = readdir($handle)))
    if (preg_match("/\.doc/i",$file))
  {
          if ($file != "." && $file != "..")
          {		
		  		if $(search =="") {
					// Show all results
					$thelist[] = '<a href="music/'.$file.'">'.$file.'</a><br />';
				} else {
					// Show selected results
					$pos = strpos(strtolower($file), strtolower($search));
					if ($pos === true) {
						$thelist[] = '<a href="music/'.$file.'">'.$file.'</a><br />';
					}
				}
                
                }
       }
  closedir($handle);
  }
  sort($thelist);
  $thelist = implode("\n",$thelist);
  echo $thelist; 
  
  ?>

Open in new window

GMGenius

Hi,

As soon as I posted i noticed a typo.

We really need to be able to edit posts :D

The line

if $(search =="") {

should be

if ($search =="") {

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
alexgreen

ASKER
That latest code seems to break it completely!

The other code doesn't seem quite perfect either, some words it doesn't find when searching!!!

Its workable in its current form and does pretty much what I want it to do so I'm not too fussed!
alexgreen

ASKER
I've worked out that if searching the first word of a document, it doesn't recognise it.

I'm not sure why, its almost as if it is looking for something before the word??
GMGenius

Hi,

My appologies.

I have corrected the problem, as I said i didnt test it but it should work... This time i DID test it. I mistakenly used strpos instead of strstr.

strpos  - Finds the position of the last occurrence of a string inside another string (case-sensitive)
strstr - Finds the first occurrence of a string inside another string (case-sensitive)
<?php
 
$search = @$_GET["search"];
 
if ($handle = opendir("music/")) { 
 
  $thelist = array(); 
  while (false !== ($file = readdir($handle))) 
  {
		if (preg_match("/\.doc/i",$file))
	  {		
			  if ($file != "." && $file != "..")			  
			  {		
					if ($search == "") {
						// Show all results
						$thelist[] = '<a href="music/'.$file.'">'.$file.'</a><br />';
					} else {
						// Show selected results
						$pos = strstr(strtolower($file), strtolower($search));
						if ($pos == true) {
							$thelist[] = '<a href="music/'.$file.'">'.$file.'</a><br />';
						}
					}
					
				}
	  }
  }
  closedir($handle);
  }
  sort($thelist);
  $thelist = implode("\n",$thelist);
  echo $thelist; 
  
  ?>

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
alexgreen

ASKER
Wow, that's brilliant, thanks

It does everything - returns any result in any case - not case sensitive!

Fantastic, Am I still allowed to do a points question to give you a little more reward for all your work on this?