1

This might have already been answered before, but I haven't found any answer to my problem.

If i have a form like the following one in more than 1 page and when I click on the submit button, I want to know what page it was sent from without having to manually write an <input type=hidden> to store the page's name as a value and then retrieve it with a $_POST.

<form action="newsletterInsert" method="post" accept-charset="utf-8">
 <input type="text"><input type="submit" name="newsletterEmail" value="Subscribe">
</form>

1 Answers1

-2

You could use $_SERVER['HTTP_REFERER'] in php. It will give you the referrer page's URL if there exists any. Some browsers however are configured to remove/hide the referrer.

Another option would be to add some javascript to your page that will find all forms on the page and create the hidden-input with the referrer-information dynamically.

(function() {
  let referrer = encodeURIComponent(window.location.href);
  let forms = document.getElementsByTagName('form');
  for (let form of forms) {
    let input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'referrer';
    input.value = referrer;
    form.appendChild(input);
  }
})();
<form>
  <input type="text" value="some input">
  <input type="submit" value="submit">
</form>
Jan
  • 2,853
  • 2
  • 21
  • 26
  • 1
    Also worth a read - https://stackoverflow.com/questions/36240145/how-to-use-serverhttp-referer-correctly-in-php – Nigel Ren Jun 03 '19 at 15:43
  • 1
    Since it isn't trustworthy or even guaranteed to be set, why add it as an answer? You've basically already argued against using it. – M. Eriksson Jun 03 '19 at 15:46
  • @MagnusEriksson becuase for some situations/environments it can be useful and also really quick implemented. – Jan Jun 03 '19 at 15:51
  • Since it's the client that sends that header, and you can't control what the client sends, I can't really see any situation where it would be useful? At least not as a solution to this question. Not as long as the developer has 100% control over what clients are using their site and know their configurations. But since the OP haven't mentioned that, it doesn't seem to be the case. – M. Eriksson Jun 03 '19 at 15:53