Reputation: 5
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.
Upvotes: 0
Views: 1365
Reputation:
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
Upvotes: 2
Reputation: 503
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.
Upvotes: 0
Reputation: 51
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
Upvotes: 0