简体   繁体   中英

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>

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>

The code assumes you have a variable called $name's not $name.

Close the " and make it:

echo "<h1>" . $name . "'s Profile</h1>";

or use {} in the string like:

echo "<h1>{$name}'s Profile</h1>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM