note 111722 deleted from function.exit by aharvey

From: Date: Wed, 20 Mar 2013 20:40:56 +0000
Subject: note 111722 deleted from function.exit by aharvey
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-194152@lists.php.net to get a copy of this message
Note Submitter: rlerne at gmail dot com ---- As seen below, a useful way to prevent direct enumeration of includes is as follows: <?PHP if (strtolower($_SERVER['SCRIPT_FILENAME'])==strtolower(__FILE__)) { if (!headers_sent()) { header('HTTP/1.1 301 Moved Permanently',true,301); header("Location: http://{$_SERVER['HTTP_HOST']}/"); } die; } echo "The script was accessed via an include/require"; ?> This code contains a few enhancements, notably: - strtolower. In Windows environments, SCRIPT_FILENAME returned "i:/web/file.php", but __FILE__ returned "I:/web/file.php" making it not work. Additionally, added a 301 header to redirect gracefully (and preserve any SEO that you might get on an include ;)) The "L" in "Location" should be capitalized and the path should be absolute per RFC 2616 (check http vs. https for your use case). Finally, as suggested later, die; was added in the case that headers were already sent. It is up to the client to respect the redirection, so the client could disable redirection leading to unintended code execution. Though this is on the "exit()" page, I used die; as a form of habit. Alter as needed.

« previous php.notes (#194152) next »