0

I have a php file that needs to redirect to another, but I need to pass an array to the second file. How can I do this.

I know this is wrong, but I need something logically similar to this.

<?php 
       $arr = array('this'=>'is', 'some'=>'stuff');
       header("someurl.php", vals=>$arr);
 ?>
1
  • What do you mean "pass between files" Commented Apr 21, 2012 at 16:12

4 Answers 4

7

Use http_build_query:

header("Location: someurl.php?" . http_build_query($arr));
Sign up to request clarification or add additional context in comments.

Comments

6

That's not how you do headers. it'd have to be

header("Location: someurl.php?vals=$arr");

however, this would just generat the URL

someurl.php?vals=Array

Note that a redirect by its nature cannot do a POST. it will result in a new GET request, meaning you have to pass data in the URL. If you have a very large url, you're almost guaranteed to lose most of it, as URLs have length limits.

However, if it's a short one, you can try something like:

$url = 'someurl.php?vals=' . url_encode(serialize($arr));
header("Location: $url");

and hope it works.

2 Comments

PRECISELY!! this is the best answer! a common misconception most devs have.
Wouldn't base64_encode be a better option here? I think urlencode has worse length ratio properties than base64. (base64 is 33% I believe - I can easily see urlencode going over that). Also, if you have simple data the serialize is a bit overkill.
5

If you don't want to expose your $array, you MUST use PHP inbuild session support.

session_start(); // DO CALL ON TOP OF BOTH PAGES
$_SESSION['array'] = $array;
echo $_SESSION['array']; // GIVES SAME $array FOR BOTH PAGES

Comments

3

You may store the array on the session or the request and then retrieve it.

If it is a different request you'll have to do it in the session.

$_SESSION['myarray'] = $array_you_want_to_store;

And then.

$array_you_want_to_retrieve = $_SESSION['myaarray'];

1 Comment

This gives considerable issues if the user uses tabbed browsing (=everyone) and clicks multiple links at once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.