Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to post data in a PHP redirect?

Tags:

php

Well right now I have a page (page2.php) and at the top it does some validation checking and if something fails it bounces back to page1.php. The problem is that page1.php is loaded by a post meaning it is the end result of a form. This means that all the post data I originally have on page1.php is lost.

So here is my code:

if ($validation_fails)
{
    header('Location:page1.php');
}
like image 319
Andrew G. Johnson Avatar asked Jan 20 '09 22:01

Andrew G. Johnson


People also ask

Can we send data in redirect?

Yes. If not passing the object, then passing the id so that the other function can retrieve it from the database.

Can we redirect with POST?

in response to a POST request. Rather, the RFC simply states that the browser should alert the user and present an option to proceed or to cancel without reposting data to the new location. Unless you write complex server code, you can't force POST redirection and preserve posted data.

How redirect data from one page to another in PHP?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.


4 Answers

You can post data back with cURL or re-structure to do the validation at the top of page1.php and if it doesn't fail, take to page2.php. If you are doing some sort of multi-step form, you could save all the data in a session and populate fields if there's matching data in the session. Not sure if that applies, though.

like image 87
Paolo Bergantino Avatar answered Oct 13 '22 01:10

Paolo Bergantino


You could restructure the logic. The validation should happen on page1.php and if it fails, the redirection does not happen. If it succeeds, you are redirected.

If you are concerned about safety (people just going to page2), you could set a session variable that is checked on page2 and set on page1.

like image 36
Ólafur Waage Avatar answered Oct 12 '22 23:10

Ólafur Waage


Can’t you just include the validation script via include or require instead of redirecting to it?

like image 40
Gumbo Avatar answered Oct 13 '22 01:10

Gumbo


On page2.php You could store the contents of the post into a $_SESSION variable if validation fails.

On page1.php you simply include a properly escaped/encoded version of the data that you stored in the session as part of the form. You would also be able to use this to update the form so it is clear the user what part failed the validation.

like image 44
Zoredache Avatar answered Oct 13 '22 00:10

Zoredache