tags:

views:

146

answers:

5

Hi,

I want to make my php page just can be accessed by another page redirect, and want to prevent my user directly access to it.

i mean, lets say i have a page called "main.php" and other php file that i want to prevent direct access called "noaccess.php".

I want to make noaccess.php file accessible if i only redirect from main.php

any suggestion?

Thnx

UPDATE: Session is good idea thx but problem is i have to use javascript to redirect page, so the question is, can i use ajax to set a php session ?

UPDATE 2 : OK I found solution, i dont need preventing direct access now as i can check from mysql whether page needs to be accesible or not. but thanx everyone tho

A: 

You can use $_SERVER["HTTP_REFERER"]. Put the following code in the beginning of your php file and set $url to be equal of your desired url for example http://a.com/main.php

if ($_SERVER['HTTP_REFERER'] != $url) {
    header('Location: noaccess.php');
    exit();
}
Ivo Sabev
Which is definable by the user, so can't be trusted at all.
Chad Birch
On the other hand, many paranoid firewalls cut this header off
Col. Shrapnel
i think so, it seems not trusted at all
Ahmet vardar
but will try it tho, thx
Ahmet vardar
A: 

Why not to just include instead of redirect?

Col. Shrapnel
include is not suitable for the situation :(
Ahmet vardar
@Ahmet Care to explain why?
Col. Shrapnel
A: 

The other folks are right there are issues with $_SERVER["HTTP_REFERER"] so I guess the best way will be to have a variable set into a $_SESSION or $_POST and you will need to check if that variable exists, if not it means it is a direct access.

Ivo Sabev
+3  A: 

I think you're probably coming at the problem from the wrong direction, but if you really want to implement this I'd most likely do it with a session variable. Just have main.php set a flag indicating that they're now able to access noaccess.php and then redirect there. noaccess.php checks for the flag, and only functions if it's been set.

Chad Birch
this seems like a good idea !
Ahmet vardar
+1  A: 

What if everytime you were going to redirect you saved a value in the $_SESSION variable. So you have

//code
$_SESSION['fromMain'] = "true";
header("Location: noaccess.php");

Then in noaccess.php put

if($_SESSION['fromMain'] == "false"){
   //send them back
   header("Location: foo.php");
}
else{
   //reset the variable
   $_SESSION['fromMain'] = "false";
}

I really don't know if this would work or not, but this is what I would try off the top of my head.

yes exactly this is ;)
Ahmet vardar
oh man i forgot to mention, i have to use javascript to redirect page, so how will i start session :( ? can i use ajax to start session ?
Ahmet vardar
Not sure. I always have a config file that has session_start() in it and then I include_once("config.php") in every page so then I don't have to bother with it. I suppose you could make an ajax call to a php file with session_start() in it and see if it works.