php - 访问 AJAX 页面时如何显示未找到页面 (404)

标签 php

我能够阻止从浏览器地址栏直接访问 AJAX 页面(如果他们从浏览器访问,我存在 PHP 代码)。例如,这是一个 AJAX 页面:www.example.com/ajax/ajax.php我需要向用户表明该页面不存在——类似于当他们访问实际上不存在的页面时发生的情况。我从如下可用的站点执行此操作:

ErrorDocument 404 /page_not_found.php

所以,当用户访问页面时:www.example.com/ajax/ajax.php ,我需要他们看到页面的内容:page_not_found.php

注意 1:AJAX 页面是包含从 Javascript 访问的 PHP 代码的页面,用户不得访问这些页面,因为它们没有要显示为 HTML 的可见代码。

注意2:在AJAX页面的顶部,我检查访问的来源,如果是从浏览器地址栏,然后我退出代码,我使用$_SERVER['HTTP_REFERER']。

我如何保护我的 ajax 页面不被浏览器直接访问:

为了简化代码,我在页​​面顶部添加:

// To prevent from accessing the ajax page from the browser address bar direct
if( strtolower($_SERVER['HTTP_REFERER']) != 'http://example.com/index.php'){
    exit; // I need to show the content of the 404 error page before this exit 
}

我不想做任何重定向!寻找一种假的方式来显示找不到该页面。

最佳答案

我已经通过在退出代码之前使用file_get_contents 读取not_found.php 页面解决了这个问题。因此,通过这种方式,它将显示为服务器上不存在任何真实页面,并且不会发生重定向。

// To prevent from accessing the ajax page from the browser address bar directly
if( strtolower($_SERVER['HTTP_REFERER']) != 'http://example.com/index.php'){

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

    file_get_contents("http://example.com/not_found.php"); // will bring the 404 page 

    exit; // no more execution
}

关于php - 访问 AJAX 页面时如何显示未找到页面 (404),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279674/

相关文章:

javascript - 将数据从模态插入数据库

php - 拉拉维尔 : How do I parse this json data in view blade?

php - 具有某些值的数组中的意外行为

php - 在 SugarCRM 中显示通知

PHP exec 没有按预期运行我的脚本

php - MySQL & PHP - 选择 6 行,每行有不同的 'WHERE' 子句

php - 在 PHP 中将 stdClass 对象转换为数组

php - 如何在点击时设置 Cookie?

php - ubuntu 16.04 上的 vtiger php 错误

php - Yii 2 dropDownList - 未选择默认值