Re: look at all files, then go elsewhere
| From: | brian | Date: | Tue, 11 Sep 2007 15:38:02 +0000 |
| Subject: | Re: look at all files, then go elsewhere | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-261945@lists.php.net to get a copy of this message | ||
Wolf wrote:
All,
I'm trying to figure out the logic piece, and I'm pretty sure I am
missing something simple.
I have a script that I want to check all files in a directory for
information, if it doesn't find it when all done, I want it to go
elsewhere, however if it does find it, I want it to break out of the
search and perform a function.
CODE:
if ($userinfo == "")
{
if ($handle = opendir('./bp_csv/')) {
while (false !== ($file = readdir($handle))) {
if($file != '..' && $file != '.') {
if(is_dir($file)) { //Diretory skipped
} else {
$command = 'cat ./bp_csv/' . $file . ' | grep '"';
$user = $_POST[userid];
$command .= $user . '"'';
$userinfo=exec($command);
You'd sanitise this in real life, i hope. escapeshellarg() and escapeshellcmd() are your good friends.
curl -d "user=foo%22%3Becho+%22pwned%21" http://yourdomain/yourscript.php
And i think you have an extra single quote there at the end of both those lines.
Why aren't you simply reading into an array the contents of the file and searching for $user in that? Use file()
http://www.php.net/manual/en/function.file.php
-- snip --
while (false !== ($file = readdir($handle)))
{
$lines = file($file);
$idx = array_search($user, $lines)
if ($idx !== FALSE)
{
$userinfo = $line;
break;
}
}
if ($userinfo != "")
{
userprofile($userinfo);
}
else
{
...
-- snip --
Or something like that.
// here's where it is multi-looping
if ($userinfo =="")
{ echo "$user not found in any BP_CSV files, now running LDAP check<BR>";
ldap_check($user);
}
else
{
// ok, found the person, run the function
userprofile($userinfo);
}
}
}
}
} }
else
{
//original data has contents, go after user data
userprofile($userinfo);
}
--------------- END CODE
The reason your script was looping is because your second "if ($userinfo =="")" is reached for each and every file found in the directory. That is, every time you grep for $user in a file, you're re-setting $userinfo, regardless of the result. Then you're running ldap_check().
Basically, you need a break in there, at the very minimum. And your second test on $userinfo should be outside of the while loop.
Regardless, use file() instead of that exec() call. That looks as if it could have sharp edges.
brian