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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了