Forum Moderators: coopster

Message Too Old, No Replies

Problem using strpos() to define PHP SELF

         

Borgscan

3:34 am on Aug 17, 2007 (gmt 0)

10+ Year Member



Hi, I'm trying to make a script that can be placed at the top of an included file. For example if I place this script in config.php then only index.php or admin.php could include it without dying with the error. For some reason the if statement doesn't work as I had expected. Any file (eg: test.php) I include config.php into, still loads without dying.


$self = $_SERVER["PHP_SELF"];
$index = strpos($self, "index.php");
$admin = strpos($self, "admin.php");

if (($index === false) ¦¦ ($admin === false))
{
die ("You can't access this file directly...");
}

However this works...


if ($index === false) // or admin.php, either works, but only one.
{
die ("You can't access this file directly...");
}

I've also tried doing this with index.php and admin.php in an array, and it still doesn't work as expected. I'd prefer to have the script be something like the following. Naturaly it does notwork either when having two strpos() functions.


$self = $_SERVER["PHP_SELF"];

if ((!strpos($self, "index.php")) ¦¦ (!strpos($self, "admin.php")))
{
die ("You can't access this file directly...");
}

Any help would be greatly appreciated.

[edited by: Borgscan at 3:40 am (utc) on Aug. 17, 2007]

dreamcatcher

6:25 am on Aug 17, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could do it like this as an alternative:

if (!strstr [php.net]($_SERVER['PHP_SELF'],'index.php') &&!strstr [php.net]($_SERVER['PHP_SELF'],'admin.php'))
{
// not allowed
}

dc

Borgscan

6:35 am on Aug 17, 2007 (gmt 0)

10+ Year Member



Thanks for that Dreamcatcher, that does what I need. Cheers.

I think it might have been the ¦¦ in my statement that was stopping it from working.

Once again, thannks.

EDIT: Yeah, it was definetly my use of ¦¦ (OR) in the statement. is there any benefits to using strstr() instead of strpos()? Just I read somewheret that strpos was faster.

[edited by: Borgscan at 6:45 am (utc) on Aug. 17, 2007]

dreamcatcher

7:50 am on Aug 17, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



strpos is faster. This is directly from the PHP website:

Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

Up to you really.

dc