Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable in header function

I am attempting to pass variables through the URL using the header function as a way to redirect the page. But when the page is redirected it passes the actual variable names rather than the values associated with the variables. I am new to PHP and do not fully understand the syntax so any further explanation as to the proper way to do this would be much appreciated.

header('location: index.php?id=".$_POST[ac_id]."&err=".$login."');
like image 283
Joe Avatar asked Apr 26 '11 02:04

Joe


2 Answers

You want:

header("Location: index.php?id=".$_POST['ac_id']."&err=".$login);

You were combining ' and " in this string, which is why it couldn't interpolate the variables properly. In my example above, you are strictly opening the string with " and concatenating the variables with the string.

like image 83
Mike Lewis Avatar answered Oct 03 '22 00:10

Mike Lewis


You have quotes within quotes. Try this instead:

header('location: index.php?id=' . urlencode($_POST['ac_id']) . '&err=' . urlencode($login));

The urlencode() function takes care of any reserved characters in the url.

What I would do instead is use http_build_query(), if you think you will have more than one or two variables in the URL.

header('Location: index.php?' . http_build_query(array(
    'id' => $_POST['ac_id'],
    'err' => $login
)));

Also, you technically can't use relative paths in the location header. While it does work with most browsers, it is not valid according to the RFCs. You should include the full URL.

like image 39
Brad Avatar answered Oct 03 '22 00:10

Brad