Forum Moderators: coopster

Message Too Old, No Replies

Finding file using query string

using variable to find a file in directory

         

ln_tora

5:11 am on May 24, 2003 (gmt 0)

10+ Year Member



Hello. Forgive a newbie for the question. I'm using PHP 4.2, and I'm having some problems with trying to find a file in a directory based on a query(?) string. I've checked around google and such but nothing really seems to cover this in detail (not even php.net).

What I have is a url similar to this:
http://myplace.com/dir/file.php?action=this&object=var

The action variable calls a function I've written that's going to act on the file if the file exists. The object variable is what I'm trying to use to find the file. Basically, once I GET the object into $var, I want to use that to find any files that has $var at the beginning of their filenames, then open and read. I thought ereg() would do this, but I must be implementing it wrong or something. My code looks something like (the directory handle is declared earlier):


$var = $_GET['object'];
if ($thisdir = opendir($DIR))
{
if ($file = readdir($thisdir)!== false)
{
if (ereg("^$var" ,$file))
{
/* code here */
}
else
{
echo "<p>Error opening $file.</p>";
}
closedir($thisdir);
}
}

All I keep getting is the error message, and it's not echoing the $file variable, so I must not be getting it. I tried echoing $var to see if that was working and there's no problem there.

Sorry to bother, I've tried searching on my own but I can't find anything that covers file handling in depth, especially with finding the file. All help greatly appreciated.

[edited by: jatar_k at 6:06 pm (utc) on May 24, 2003]
[edit reason] delinked example [/edit]

dmorison

6:02 am on May 24, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi,

The logic looks incorrect on this line:

if ($file = readdir($thisdir)!== false)

$file will be 1, not the return value of readdir()!

I think it should be:

if (($file = readdir($thisdir))!== false)

Does that help - the rest of the code looks ok...!

ln_tora

4:32 pm on May 24, 2003 (gmt 0)

10+ Year Member



Thank you, dmorison. I did fix that (the risks of trying to code at 2am, you don't see all the brackets). But still nothing happened. The line currently looks like this

if (false!== ($file = readdir($thisdir)))

Yet again I get the error message. In the error message where I use the $file var, all I get is a period. Is there something else I'm doing wrong?

dmorison

4:37 pm on May 24, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A period "." is always the first "file" read using readdir(). It is the filing systems way of referring to the current directory.

The next file you read will always be ".." - referring to the parent directory.

The read after that will return an actual real file!

You need to loop ignoring "." and ".."!

Hope this helps!

ln_tora

5:37 pm on May 24, 2003 (gmt 0)

10+ Year Member



Well I'm not getting the error message, unfortunately I'm getting a blank page. I'm posting the entire function in the hopes that seeing the code will help (there's no site references, so I hope this is okay).


function tmplEdit()
{
global $TMPL_DIR;
$tmplname = $_GET['tmplFile'];
if ($thisdir = opendir($TMPL_DIR))
{
if (false!== ($file = readdir($thisdir)))
{
while ($file!= "." && $file!= "..")
{
if (ereg("^$tmplname" ,$file))
{
$file_content = fread(fopen($file, "r"), filesize($file), 1);
fclose($file);
// work on form later, worried about grabbing file content for now
echo <<<END
<form action="$_SERVER['REQUEST_URI'] method="POST">
<textarea name="thistmpl" cols="55" rows="15">$file_content</textarea>
</form>
END;
}
else
{
echo "<p>Error opening $file: No such template available.</p>";
}
}
}
}
else
{
echo "<p>Unable to open $thisdir.</p>";
}
}

I'm still looking through tutorials and references, but so far I'm coming up empty.

jatar_k

6:11 pm on May 24, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld ln_tora,

try switching

false!== (

to

false!= (

ln_tora

6:30 pm on May 24, 2003 (gmt 0)

10+ Year Member



Hello, jatar_k. I just tried your suggestion, but still only a blank page. (I checked the file permissions on the test file I'm trying to open just to be sure. It's reading 666, since I want to be able to edit the file later if I can get this part to work.)

I'm going to see if maybe I should add the extension somewhere in the ereg function so it knows exactly what to look for. I'll edit here and let you know how it works.

edit: no go. Is there another way besides ereg to try and match the string in $tmplname to a file in the directory containing said string in the name?

jatar_k

6:55 pm on May 24, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I use this to to check if a file already exists.


$mydir = $_SERVER['DOCUMENT_ROOT'];
$d = dir($mydir);
while($entry = $d->read()) {
if ($entry == $pagename . ".php") {
$formerror = "That page Name already exists";
do stuff
die;
}
}
$d->close();

ln_tora

7:37 pm on May 24, 2003 (gmt 0)

10+ Year Member



Okay, now I'm getting error messages again, which is a good thing, since I can get something of an idea of what's going on.

I changed the code following jatar_k's snippet, so the function looks like this


function tmplEdit()
{
global $TMPL_DIR;
$tmplname = $_GET['tmplFile'];
$thisdir = @opendir($TMPL_DIR) or die("Unable to open $TMPL_DIR");
while($file = readdir($thisdir) && $file!= "." && $file!= "..")
{
if ($file == $tmplname . ".tmpl")
{
$file_content = fread(fopen($file, "r"), filesize($file), 1);
fclose($file);
// work on form later, worried with grabbing file content for now
echo <<<END
<form action="$_SERVER['REQUEST_URI']" method="POST">
<textarea name="thistmpl" cols="55" rows="15">$file_content</textarea>
</form>
END;
die;
}
else
{
echo "<p>Error opening $file: No such template available.</p>";
}
}
closedir($thisdir);
}

I'm getting the following errors on the page itself, along with an empty textbox. (site references removed)

Warning: filesize() [function.filesize]: Stat failed for 1 (errno=2 - No such file or directory) in /mypath/www/tmpl_config/functions_tmpl.php on line 599

Warning: Wrong parameter count for fread() in /mypath/www/tmpl_config/functions_tmpl.php on line 599

Warning: fclose(): supplied argument is not a valid stream resource in /mypath/www/tmpl_config/functions_tmpl.php on line 600

So I'm guessing it's saying the file doesn't exist, which it does, so it's either not matching the $tmplname variable, or just not reading the file. So opening the directory isn't the problem, it's just not finding the file based on the GET variable I'm trying to match up.

I'm wondering if there's an easier way to do all of this. I just don't know what, and I can't find a tutorial that's been helpful.

Again, I'd like to thank you for all the help given so far. At the very least, I'm learning more.

jatar_k

8:00 pm on May 24, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well, 1 at a time

string fread ( resource handle, int length)

so this is wrong, drop the 1
fread(fopen($file, "r"), filesize($file), 1)

I think you are doing too many things at once and getting confused. Try splitting things into individual actions and you will get better error messages and therefore a better handle on what isnt happening.

your while could be split
while($file = readdir($thisdir)){
if ($file!= "." && $file!= ".."){

and this
$fp = fopen($file, "r");
$fsize = filesize($file);
$file_content = fread($fp,$fsize);

get my drift? You need to isolate the errors and deal with them one at a time, if everything is banged into one line it becomes difficult. Assign the value of a function to a var and then pass that var to the other function.

If you want to test a specific spot "if" it and then echo and die(if needed).

ln_tora

8:46 pm on May 24, 2003 (gmt 0)

10+ Year Member



Testing the ifs was the best advice, thanks! Seems the problem is coming in here
if ($file == $tmplname . ".tmpl")

I tried using that with an include($file), and for some reason the warning came back: Failed opening '1' for inclusion

It seems everything falls apart there, so to speak. In a nutshell, how do I go about using the string passed through the url to find a file with the same beginning name, then open and read it?

ln_tora

11:13 pm on May 24, 2003 (gmt 0)

10+ Year Member



Okay, I figured out a solution (after lunch). The check against $file works, but then it can't seem to find $file after that. I decided that since it couldn't find $file, I'd simply point $file to the correct, absolute path of the file I'm trying to get if there is a match. Bingo. So now the function looks like this:

function tmplEdit()
{
global $TMPL_DIR;
$tmplname = $_GET['tmplFile'];
$thisdir = @opendir($TMPL_DIR) or die("Unable to open $TMPL_DIR");
while ($file = readdir($thisdir))
{
if ($file!= "." && $file!= "..")
{
if ($file == $tmplname . ".tmpl")
{
$file = $TMPL_DIR . $tmplname . ".tmpl";
$fp = fopen($file, "r");
$fsize = filesize($file);
$file_content = fread($fp, $fsize);
fclose($fp);
// work on form later, worried with grabbing file content for now
echo <<<END
<form action="$_SERVER['REQUEST_URI']" method="POST">
<textarea name="thistmpl" cols="55" rows="15">$file_content</textarea>
</form>
END;
}
else
{
echo "<p>Error opening file: $tmplname.tmpl. ";
echo "No such file found in directory.</p>";
}
}
}
closedir($thisdir);
}

Tried with the actual file, the contents come up in the textbox just fine. I entered a bogus file variable and the error message printed out. So everything seems to work now. Thanks again for all the help, I wouldn't have been able to figure this out otherwise. Now I can move on and start learning how to edit and save the file.

[edited by: ln_tora at 11:15 pm (utc) on May 24, 2003]

jatar_k

11:14 pm on May 24, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



take a look at what is being compared in the vars

echo "<p>file: ",$file;
$tmplname .= ".tmpl";
echo "<p>tmplname: ",$tmplname;
if ($file == $tmplname) echo "it worked";

That should pop the filename and the tmplname. Take a look at the exact data being compared and that should help.

jatar_k

11:15 pm on May 24, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I was posting at the same time as you were. :)

Glad you got it sorted.

ln_tora

11:18 pm on May 24, 2003 (gmt 0)

10+ Year Member



I'll try your suggestion as well. It never hurts to have more than one way to do something if they both work. Thanks again!

ln_tora

3:40 pm on May 25, 2003 (gmt 0)

10+ Year Member



Update: I was doing things all wrong. The whole point to that was I wanted to first see if the file existed (in case someone tried inputting garbage in the url), and if it did, then proceed, or give an error. I knew where the file would be located, just not the name, which comes through the url. All I had to do was take the variable, construct a path, then use a file_exists() check.

$tmplname = $_GET['tmplFile'];
$template = $TMPL_DIR . tmplname . ".tmpl";
if (file_exists($template)) {
echo "Found match. Proceed.";
}
else {
echo "no match found";
}

Now that I feel like an idiot, I just wanted to thank you for your patience with me, and maybe this will help someone else out in the future.

jatar_k

3:56 pm on May 25, 2003 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Don't worry about it ln_tora,

Look at all that you learned. You have to love that with the gaining of knowledge, most often, the first thing we learn is how little we know. ;)