dongweiben5229 2013-10-11 02:39
浏览 59
已采纳

使用ajax时无法识别php常量

I want to restrict access to a php file such that only other php files can access it. In restricted.php I have added the following check:

if (!defined('myvar')) { exit(); }

and in index.php I define myvar as such: define('myvar', true);

This works when I use include 'restricted.php'; but I am denied access when I try to access the page using ajax. Is this expected?

$.ajax({
   url: "restricted.php",
   dataType: "text",
   success: function(data) {
   //use data
   }
});
  • 写回答

3条回答 默认 最新

  • douxie1894 2013-10-11 03:51
    关注

    Yes, this is expected from what you have posted. Like Paul Denisevich says, javascript is client side, PHP is server side, so as far as restricted.php is concerned, your ajax request could be coming from anywhere. Although you say that you want "other php files" to be able to access it, I get the impression that you want your ajax to be able to access it, but you don't want other client side scripting to be able to access it. You don't want someone to be able to load the file directly, like http://example.com/restricted.php.

    You need a piece of information that index.php and restricted.php both know about, but an outsider will not, then hash it. I don't know what information you might have available to these scripts. If there is a user logged into this, maybe you want to hash the users name and date of birth or something. It would be good to use something from a database that is never output to the UI and include that in the hash.

    For example purposes, maybe I'll just have a file:

    <?php
    $key = "some string" . date('DNi'); 
    // weird date format that changes every minute. This is no good for production as 
    // the minute may tick by during the request from the ajax to restricted.php. You 
    // are better off using some values from a database that are not shown anywhere.
    ?>
    

    in both index.php and restricted.php:

    require_once('hash.php');
    

    in your ajax:

    $.ajax({
       url: "restricted.php",
       dataType: "text",
       data {hash:"<?php echo md5($key) ?>"},
       success: function(data) {
       //use data
       }
    });
    

    then in restricted, something like:

    if($_GET['hash'] == md5($key)) {
        // do your thing and send some output for ajax to use
    } else {
        // bail
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?