Best code example:
if ($_SERVER['SCRIPT_NAME'] === $thisPage) { }
However, it depends on the contents of $ thisPage. If $ thisPage contains $_SERVER['PHP_SELF'] too, you should change this to $_SERVER['SCRIPT_NAME']
If you really can't use alternatives like __FILE__ and $_SERVER['SCRIPT_NAME'] , and make sure you understand the checks associated with it, yes.
For example, this URL: http://example.com/sick.php/mwuahahahaha gives:
/sick.php/mwuahahahaha
Comparison is acceptable for non-critical things like CSS.
If you donβt need to get the requested path (without rewriting the URLs), use $_SERVER['SCRIPT_NAME'] . If you really need $_SERVER['PHP_SELF'] (rewritten URL), avoid them when outputting (using htmlentities($_SERVER['PHP_SELF']) .
Variable Overview:
__FILE__ : contains the full path of the file system from the active script. For example.:
<?php /*test.php*/ include 'file.php';?>
<?php /*file.php*/ echo __FILE__;?>
The test.php query gives something like: /var/www/file.php (rather than /var/www/test.php )$_SERVER['SCRIPT_FILENAME'] : contains the file system path of the requested script, for example. /var/www/test.php$_SERVER['SCRIPT_NAME'] : contains the path to the requested script (for example, to the file system, but with a truncated document root), for example. /test.php (even when using rewritten URLs)$_SERVER['PHP_SELF'] : contains the translated path ( // β / $_SERVER['PHP_SELF'] And .. allowed), but with additional information about the path.$_SERVER['REQUEST_URI'] : the worst of them, it contains the raw string in the request, as in. GET [REQUEST_URI] HTTP/1.0 . (escaped) nullbytes are still visible here. This is only the source data between GET (or any method you use) and HTTP/1.0 (or any version of HTTP you use)
Comparison of these variables:
I performed this test using nc , but telnet would be enough too. The server was from http://xampp.org/ . The requested test.php file, which contains:
<?php $properties = array('SCRIPT_FILENAME', 'SCRIPT_NAME', 'PHP_SELF', 'REQUEST_URI'); printf("% 15s: %s\n", '__FILE__', __FILE__); foreach($properties as $property){ printf('% 15s: %s', $property, $_SERVER[$property]."\n"); } ?>
Test:
$ nc localhost 80 GET ///somedir/./../////test.php/somedata%20here?q%00=%25 HTTP/1.0 HTTP/1.1 200 OK Server: Apache/2.2.14 (Unix) [stripped] __FILE__: /opt/lampp/htdocs/test.php SCRIPT_FILENAME: /opt/lampp/htdocs/test.php SCRIPT_NAME: /////test.php PHP_SELF: /////test.php/somedata here REQUEST_URI: ///somedir/./../////test.php/somedata%20here?q%00=%25
Using RewriteRule ^page/test test.php :
$ nc localhost 80 GET ///somedir/./../page//.////test/somedata%20here?q%00=%25 HTTP/1.0 HTTP/1.1 200 OK Server: Apache/2.2.14 (Unix) [stripped] __FILE__: /opt/lampp/htdocs/test.php SCRIPT_FILENAME: /opt/lampp/htdocs/test.php SCRIPT_NAME: /test.php PHP_SELF: /test.php REQUEST_URI: ///somedir/./../page//.////test/somedata%20here?q%00=%25
Conclusion: the most secure variable to use in most cases is $_SERVER['SCRIPT_NAME'] .