Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use variables passed through header() in php [closed]

Tags:

php

header

I'm using header() to pass var user from one page to another as:

header( "Location: temp.php? user = $user" );

The variable is getting passed and is shown on the URL of the other page.

I don't know how to use the var user in that page. Please help.

like image 780
Abdul Hadi Shakir Avatar asked Nov 07 '12 09:11

Abdul Hadi Shakir


People also ask

Can we pass variable in header in PHP?

header( "Location: temp. php? user = $user" ); The variable is getting passed and is shown on the URL of the other page.

What PHP can do with header () function?

The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).

Why my header is not working in PHP?

The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error. Like following example, there should not be any output of even a space before the headers are sent.

What is the syntax for including a header in PHP?

Syntax: header(string,replace,http_response_code); string: It consists of a header string. Basically, there are two types of header calls. One is header which starts with string “HTTP/” used to figure out the HTTP status code to send.


1 Answers

page1.php

<?php
    $user = "batman";
    header("Location:temp.php?user=".$user);
    exit();
?>

temp.php?user=batman (you have just been redirected here)

<?php
    if($_GET){
        echo $_GET['user']; // print_r($_GET); //remember to add semicolon      
    }else{
      echo "Url has no user";
    }
?>

Or you could use a $_SESSION - but this could easily complicate things

page1.php

<?php
    session_start();
    $_SESSION['user'] = "batman";
    header("Location:temp.php);
    exit();
?>

temp.php

<?php
    session_start();
    echo $_SESSION['user'];
    unset($_SESSION['user']); // remove it now we have used it
?>
like image 72
Chris Avatar answered Nov 10 '22 21:11

Chris