Search code examples
phpif-statementhttp-redirectsubmitisset

PHP won't put variable in link


At the beginning of my website, I ask for a name. I then pass the name over to the homepage that has the same $name variable. In their homepage, they can press the button "something" to redirect them to the something webpage WITH the variable $name in the URL. On the homepage, it displays the value of the $name variable in the echo "<h1>$name's Profile</h1>";, but for some reason is undefined when I use it on the link. Here is the code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Profile</title>
</head>
<body>
<center>
<?php
$name = $_GET['name'];
echo "<h1>$name's Profile</h1>";
echo "<hr>";
echo "<br>";
echo "<h3>Choose an option</h3>";
if(isset($_GET['btn'])) {
    $name = $_GET['name'];
    $loc = 'something.php?name=' . $name;
    header("Location: " . $loc);
    exit();
}

?>
<input type="Submit" value="Something" name="btn">
</center>
</body>
</html>

Solution

  • Following should work

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Profile</title>
    </head>
    <body>
    <center>
    <?php
    //First check if $_GET['name'] is set
    if(isset($_GET['name'])){
    
      $name = $_GET['name'];
      //So here concatinate the strings and variables properly as following
      echo "<h1>".$name."'s Profile</h1>".
           "<hr>".
           "<br>".
           "<h3>Choose an option</h3>";
    
      if(isset($_GET['btn'])) {
          $name = $_GET['name'];
          $loc = "something.php?name=" . $name;
          header("Location: " . $loc);
          die();
      }else{
        //There was no btn parameter in the url means $_GET['btn'] isn't set notify the user
        echo "Can't Redirect The Page\nReason: Details Missing...";
      }
    }else{
      //There was no name parameter in the url means $_GET['name'] isn't set notify the user
        echo "Can't Process The Request\nReason: Details Missing...";
    }
    ?>
    <input type="Submit" value="Something" name="btn">
    </center>
    </body>
    </html>