Zestyy99
Zestyy99

Reputation: 307

passing associative array via URL using http_build_query()

I have two pages:page1.php which consists of an associative array containing potential error messages from a form.

$errors array:

Array ( [password] => password is required. [email] => email is required. )

This array could contain more errors or it could contain less.


Im trying to pass it via url to another page to be displayed next to the corrosponding form fields.

page1.php:

$a = http_build_query($errors);
header("Location: /test/page2.php?errors=".$a); 
exit();

URL:

http://localhost/test/page2.php?errors=password=password+is+required.&email=email+is+required.

However the url doesnt seem to be displaying correctly and when I get redirected to page2.php when I retrieve the $errors array, its no longer an array.


page2.php:

if(isset($_GET['errors'])){
$errors = $_GET['errors'];
print_r($errors);

$errors:
password=password is required.

Im trying to get the $errors array to display exactly like it does on page1.php before it is sent via url.

EDIT: NEW URL:

http://localhost/test/page2.php?a=errors%5Bpassword%5D=password+is+required.&errors%5Bemail%5D=email+is+required.

Upvotes: 1

Views: 2035

Answers (1)

Kep
Kep

Reputation: 5857

You're building your URL wrong, here's an example that should get you going:

// Just as an example:
$errors = array(
    "password" => "password is required",
    "email" => "email is required"
);

$queries = array(
    "errors" => $errors
);

$queryString = http_build_query($queries);

// This results in the string
// "errors%5Bpassword%5D=password+is+required&errors%5Bemail%5D=email+is+required"
// We simply append this to our header for the full redirect URL:

header("Location: /test/page2.php?".$queryString);

// The full url is then (for example):
// http://localhost/test/page2.php?errors%5Bpassword%5D=password+is+required&errors%5Bemail%5D=email+is+required

You can get those vars in page2.php like usual GET parameters:

$errors = $_GET["errors"];

Upvotes: 5

Related Questions