Validating Form input via PHP and then redirecting with POST data?

I would like to use PHP to validate form data, and then redirect to another page while passing the form’s data as POST variables.

I thought that perhaps I could set the form action as “” so that it comes back to the current page, which would then check the data and redirect if everything was OK (although I’m open to alternative approaches if this approach is not the best idea). For example, the PHP code below would redirect to the current page, use some simplified validation checking for the social security number and email data, and if everything was OK it would redirect somehow:

<?php
$error = FALSE;
if(count($_POST)>0){
	$error_check = TRUE;
}
else{
	$error_check = FALSE;
}
?>
<form action="" method="POST">
<input maxlength='3' name='ssn1' size='3' value=''>)-<input maxlength='2' name='ssn2' size='2' value=''>-<input maxlength='4' name='ssn3' size='3' value=''>
<?php
if($error_check && (!is_numeric($_POST['ssn1']) || !is_numeric($_POST['ssn2']) || !is_numeric($_POST['ssn3']))){
	echo "<br />Error - invalid SSN<br />";
	$error = TRUE;
}
?>
<input name='email' size='30' maxlength='80' value=''>
<?php
if($error_check && strpos($_POST['email'], '@')===FALSE){
	echo "<br />Error - invalid email<br />";
	$error = TRUE;
}
?>
<input type="submit" name="Submit">
</form>
<?php
if($error_check && !$error){
	echo "Redirecting...";
	//redirect somehow?
}
?>

However I don’t know how to redirect while still passing the data as POST data. Is there some way to do this?

1 Like

You can use $_SESSION to store it, or if that’s not possible - you can store it in a database, then generate a token that gets passed to the redirected page. On the redirected page you would query and pull out the $_POST data back. This method does introduce some minor security issues, so the best thing to do would be to expire the data in 30s or so.

Thank you, but how would one redirect to another target page (e.g. http://example.com/target.php) while still passing the POST data?

form1.php


session_start();

if ($_POST['submitted']) {
    # process the $_POST data
    if ($no_error) {
        $_SESSION['form_data'] = $_POST;
        header ("Location: form2.php"); exit;
    }
}

form2.php


session_start();

if ($_SESSION['form_data']) {
    # do your thing here
}

Thanks, but would that pass data in POST form…? In any case that would not work for my as the page I need to redirect to is on a different domain. So a session can’t be passed.

In this situation, there’s two ways.

  1. If the user needs to be redirect as well, you have to create a form as HTML - then use javascript to submit it. There’s no other way.

  2. If the user doesn’t need to be redirected, you can use cURL to submit the data via POST.

Thanks for the help :slight_smile: