简体   繁体   中英

Allow access to php file only if redirected

Is it possible to disallow direct access to a PHP file and allow the access only if it's redirected from other PHP file?

For example, access to loading.php should be only allowed if it's redirected from example.php page. How how can I do that?

I hope you understand what I mean. If not, please ask me, and I will try to explain better.

example.php

session_start();

$_SESSION['loading']='yes';

loading.php

session_start();
if($_SESSION['loading']=='yes'){
/all good
}else{
//bad, redirect back or whatever
}
$_SESSION['loading']=''; // clear session var

You can check referer, but it not secure:

loading.php

<?php
if($_SERVER['HTTP_REFERER']!=='http://yoursite/example.php')
  die('Denied');

--

or you can set visited flag in session

example.php

<?php
  $_SESSION['isVisitedExample'] = true;

loading.php

<?php
  if(!isset($_SESSION['isVisitedExample']))
    die('Denied');

--

or in cookie (not secure)

example.php

<?php
  setcookie('isVisitedExample', 1);

loading.php

<?php
  if(!isset($_COOKIE['isVisitedExample']))
    die('Denied');

--

or mix this methods

Test for the variable $_SERVER['HTTP_REFERER'] . (yes, the incorrect spelling is what must be used.) That variable contains the URL of the site that a user came from. The REFERER header is blank or '-' if the page is accessed directly.

The code for this would look something like the following:

if (empty($_SERVER['HTTP_REFERER']) or $_SERVER['HTTP_REFERER'] == '-') {
  exit; // do nothing if hit directly.
}
// The real page logic goes here.

If you want to only allow the loading page from a specific URL, then you may test for that URL instead of testing for empty() .

Please be aware that the REFERER header is sent by the browser and easily spoofed. That said, checking the referer header is useful for blocking other sites from directly loading images from your site.

Another option would be to use sessions and session variables to check that someone hit the appropriate page before the loader page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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