Soroush Rabiei
Soroush Rabiei

Reputation: 10868

How to send variables from a PHP script to another script using POST without forms?

I'm trying to write my first PHP script (hopefully). I want to send user input from a form inside an HTML page to a PHP script and validate them inside script. then, if there is any problem with input data, return to first page and highlight wrong fields. else go to another page (something like successful).

How do i send feedback from second script to first page without using forms?

Upvotes: 1

Views: 1832

Answers (4)

Marc B
Marc B

Reputation: 360572

In short, you'd have something like this:

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   $errors = array();

   $name = $_POST['name'];
   if ($name !== 'Fred') {
      $errors[] = 'Please enter "Fred"';
   }

   ... validate more fields ...

   if (count($errors) == 0) {
     ... form is ok ...
     header('Location: everything_is_ok.php');
     exit();
   }
}

?>

<form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
Enter 'Fred': <input type="text" name="name" value="<?php echo htmlspecialchars($name) ?>" /><br />
<input type="submit" />
</form>

Basically: Have the form page submit back to itself. If everything's ok, redirect the user to another page. Otherwise redisplay the form.

Upvotes: 3

James P. Wright
James P. Wright

Reputation: 9131

Just make your Form POST to itself, then in your PHP check the values and if they are valid, don't display your form and do your submit code. If they are invalid, display the form with the values and errors displaying.

Upvotes: 2

Brds
Brds

Reputation: 1075

Use a session... here's a link to help you get started: http://www.tizag.com/phpT/phpsessions.php

Upvotes: 0

noinstance
noinstance

Reputation: 761

Reload the first page and send the feedback in the session, for example. If session['errors'] exist, echo them. Note you'll have to include some php tags in your html page anyway.

Upvotes: 2

Related Questions