Klapsius Klapsius - 5 months ago 11
HTML Question

PHP accept GET method only from specific page

I have two PHP files:

1.php

<?php

... header("location: 2.php?id=1");
?>


2.php

<?php

... echo $_GET['id'];

?>


URL from 1.php to 2.php is:
http://localhost/2.php?id=1


My question. Is it possible to validate where get method coming from and accept only if from coming 1.php. But if someone in address bar changing id values then ignore? Something with
$_SERVER['HTTP_REFERER']
but i'm not sure

Answer

Simple answer is no. $_SERVER['HTTP_REFERER'] is often disabled by browsers and is easily spoofed.

You can do someting close to your requirement:

<?php
 //1.php
 $id = 1;
 $key = generateKeyBasedOnId($id);
 header("location: 2.php?id=$id&key=$key");
?>

You can write generateKeyBasedOnId() function as you wanted to, but you are the only one who should known the algorithm. (For example return md5('my very secret'.$id.' string');

<?php
//2.php
if($_GET['key'] !== generatekeyBasedOnId($_GET['id'])) {
   //error
}
?>

Of course, if someone copy paste the url 2.php?id=..&key=..., it will still work. You can hide key into cookies, but it is still easilly spoofable.

You can also generate random key, save it into database, read it in 2.php and if it exists, immediately delete it. So the key can be used only once. But if someone catch your header redirect, he still could (theoreticaly) take it and use it in different browser in different country ...