However, I am not able to rescue this data by the value in the input (the data is always empty).
Usually, when you open the page directly from the browser bar, the header is not generated HTTP_REFERER
.
That’s because the referrer
refers to a source page. That is, if you came from one page to another.
I suggest that, to put a default value on HTTP_REFERER
If there’s nothing, you can put it like this:
<input type="hidden" value="<?php echo isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $_SERVER['PHP_SELF']; ?>" id="origem" name="origem">
if not, the traffic source will always be the form URL)
In the case of PHP_SELF
, you could put another value, which would be the default value if there was nothing on HTTP_REFERER
. You could register it manually, but I believe PHP_SELF
already takes good care of this work.
Have you thought about using session?
Assuming the user can manipulate this information, I suggest you use $_SESSION
to store the HTTP_REFERER
, if she exists.
For example:
// script_do_formulario.php
session_start();
// Se o header referer existir, ele vai ser adicionado na sessão,
// e não vai sair, ao menos que o usuário entre na página novamente.
if (isset($_SERVER['HTTP_REFERER']) {
$_SESSION['referrer'] = $_SERVER['HTTP_REFERER'];
}
When saving the form data, you will check whether the value of $_SESSION['referrer']
exists to save you in the bank.
Curiosities
Just out of curiosity, you might be confused about being "referer" or "referrer" (with two "r"). There’s a question about that here:
And why don’t you use
$_SERVER['HTTP_REFERER']
right on the server? Use this on ainput[type=hidden]
is totally unviable. The user can manipulate the data of his report at will if he opens the F12 of Google Chrome!– Wallace Maxters
The problem is that, as described, the URL is different. When using this code directly on the server, it rescues the form URL always.
– Eduardo Martins Casagrande
So save it in session. The solution isn’t to put it in the form, man. It’s not safe, the user could change it, you know?
– Wallace Maxters
Although in any way, whoever manipulates the form could manipulate the
header
also. You’re using the form on more than one page, that’s it?– Wallace Maxters
As so in session?
– Eduardo Martins Casagrande
This form, in particular, I’m only using on one page.
– Eduardo Martins Casagrande
I get it. The
HTTP_REFERER
then it would be to know by which page he entered the form (before submitting it)?– Wallace Maxters
Yes. That’s exactly it.
– Eduardo Martins Casagrande
@Eduardomartinscasagrande If you only want the origin within your site, you can save the contents of the variable
location.href
in a cookie/localStorage or you can force a different header, for example:X-HTTP-REFER
. Ps.: For security reasons, the browsers can change the header value.– Valdeir Psr