简体   繁体   English

PHP 定义在 XMLHttpRequest() 之后不起作用

[英]PHP define not working after XMLHttpRequest()

I need to protect a file using PHP constant variable and access files only through index.php.我需要使用 PHP 常量变量保护文件,并且只能通过 index.php 访问文件。 I need to get this page through XMLHttpRequest request but when I send page.php's content inside index.php's page-container DIV using Javascript's XMLHttpRequest it does not work and always redirects to homepage.我需要通过 XMLHttpRequest 请求获取此页面,但是当我使用 Javascript 的 XMLHttpRequest 在 index.php 的页面容器 DIV 中发送 page.php 的内容时,它不起作用并且总是重定向到主页。

I have 4 files in the same folder我在同一个文件夹中有 4 个文件

1. index.php
2. page.php
3. get-page.js
4. protectedf.php

index.php code index.php 代码

<?php define("protectedf", TRUE); ?>

<div class="page-container"></div>

page.php code page.php代码

<?php require_once("protectedf.php"); ob_start(); ?>
// some html inside page.php

get-page.js code获取 page.js 代码

const pageContainer = document.querySelector('.page-container');
function mySettings(){ 
        const x   = new XMLHttpRequest();
        const url = 'page.php';
        x.open('GET',url);
        x.send();
        x.addEventListener('readystatechange',function(){
            if (this.readyState == 4 && this.status == 200) {
                const xResult = this.responseText;
                pageContainer.innerHTML = xResult;
                this.abort();
            }
        });
}

protectedf.php code protectedf.php 代码

<?php
    if (!defined("protectedf")) {
        header("Location:http://localhost/homepage/");
        exit();
    }
?>

just add define("protectedf", TRUE);只需添加define("protectedf", TRUE); on the page that include it: page.php在包含它的页面上:page.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM