PHP: prevent direct access to page

2020-02-14 07:12发布

I have some pages that I don't want users to be able to access directly.

I have this function I came up with which works:

function prevent_direct_access()
{
    if($_SERVER['REQUEST_URI'] == $_SERVER['PHP_SELF'])
    {
        //include_once('404.php');
        header("Location: 404.php");
    }
}

This does exactly what I want, the URL does not change but the content does. However I am wondering if there is something I need to add to tell search engines that this is a 404 and not to index it. keep in mind I do not want the URL to change though.

Thanks!

4条回答
萌系小妹纸
2楼-- · 2020-02-14 07:35

Just to clarify:

  • You have some PHP that you want available to other PHP programs on the system
  • You do not want anybody accessing it except by running one of the other PHP programs

(i.e. "direct" doesn't mean "except by following a link from another page on this site")

Just keep the PHP file outside the webroot. That way it won't have a URL in the first place.

查看更多
爷的心禁止访问
3楼-- · 2020-02-14 07:42

Don’t redirect but send the 404 status code:

header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
exit;
查看更多
乱世女痞
4楼-- · 2020-02-14 07:54

To ensure Search Engines don't index it, use a header() command to send a 404 lke this;

header("HTTP/1.0 404 Not Found");

Or put all such files in one folder, "includes" say, and add a "Deny /includes/" into your robots.txt file. This way, you can also add a ".htaccess" file in the same directory with one line - "Deny From All" - this will tell Apache to block access (if apache is configured properly), for another layer of security.

查看更多
forever°为你锁心
5楼-- · 2020-02-14 07:57

for the search engines, if you return HTTP status 404 they should not index I believe. But you could always redirect to somewhere covered by a robots.txt

查看更多
登录 后发表回答