3

Is there an easy way to find out the source of a post variable in PHP?

Form on example.com/formone.php

<form method="post" action="test.php">
<input name="myusername"type="text">
<input name="mypassword" type="password">
<input type="submit">
</form>

Form on example.com/formtwo.php

<form method="post" action="test.php">
<input name="myusername"type="text">
<input name="mypassword" type="password">
<input type="submit">
</form>

I understand that I could use a hidden input, but I was wondering if PHP had a method to test the source of the POST.

Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
Will
  • 733
  • 8
  • 23
  • Maybe addressing *why* you need to know the referring page would be useful. You may not need to at all. – Wesley Murch Jul 09 '12 at 19:34
  • I'm working on a very rudimentary controller type file. It was mostly curiosity. ie, not security related in the slightest. – Will Jul 09 '12 at 19:38

1 Answers1

8

While you could potentially use the HTTP_REFERER server variable, it is not very reliable. Your best bet would be to use a hidden field.

Another alternative would be to switch out your submit input for a submit button. This way you can pass a value with it, retain the button's label, and test for that inside your test.php page:

<button name="submit" type="submit" value="form1">Submit</button>

In your PHP file you would then test:

if( $_POST['submit'] == "form1" )
    // do something
Community
  • 1
  • 1
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
  • Exactly what I wanted to know. I really like the button value approach and will probably continue down that path. – Will Jul 09 '12 at 19:40
  • 1
    @MobyD: Note that button `value`s are only sent if it is actually clicked (or focused when the form is submitted), submitting by pressing "enter" while focused in a text field will not send the value, you might want to use hidden inputs. – Wesley Murch Jul 09 '12 at 20:08
  • @WesleyMurch Thank you for the wise comment. – jeffjenx Jul 09 '12 at 20:10
  • @WesleyMurch You are absolutely right. I probably would have never figured that out and been quite distraught for about a week. Hidden values it is. – Will Jul 09 '12 at 20:13