允许window.location但阻止直接访问PHP文件

允许window.location但阻止直接访问PHP文件

问题描述:

I have a script file named script.php which is accessed from another php file called main.php through the "Window.location" command. I want to prevent direct access to file, i.e, no one can type script.php in the URL bar and view the contents of the file. But I want my main.php to be able to redirect to script.php using window.location. Any way to do this?

I have tried using Debug Backtrace and preg_match() but these are also blocking the window.location from main.php. Any way to get around this?

我有一个名为 script.php strong>的脚本文件,可以从另一个调用的php文件中访问 main.php strong>通过“ Window.location strong>”命令。 我想阻止直接访问文件,即,没有人可以在URL栏中键入script.php并查看文件的内容。 但我希望我的main.php能够使用window.location重定向到script.php。 有没有办法呢? p>

我尝试过使用 Debug Backtrace strong>和 preg_match() strong>,但这些也阻止了window.location 来自main.php。 有办法解决这个问题吗? p> div>

I'm not really sure what and why you want to do. There is no way to only allow a script to open a URL, because the browser will handle it.

Normally you should check in the files itself, if the user is allowed to use them. So you have to find a logic for you, how to tell you script, if the user should see it. Otherwise you can do some other action, like displaying an error or redirect him back to you main.php.

Just some quick ideas ...

Idea 1.) If possible, you can include() the script.php in main.php and block the direct access via .htaccess. Then you don't need a redirect and no one can access it directly.

Idea 2.) Set a session variable in main.php like $_SESSION["allow"] = true; and check this again in script.php. Afterwards set the value to false, so the next call will be fail.

Idea 3.) Add a parameter to the file call, like script.php?allow=true. But in this case, all users who know the parameter could call it.

Idea 4.) Add a custom parameter to the redirect, wich is only valid for a given time. To be simple, something like php time(). Check if the parameter is within a short time limit. But in this case, the redirect url has to be generated when the main.php file starts the redirect. Otherwise the request could be already to old.

So that are my ideas. Hope something gives you a hint how to do it.