PHP不会在链接中放置变量

时间:2018-11-03 12:14:29

标签: php if-statement redirect submit isset

在我的网站的开头,我要求一个名字。然后,我将名称传递给具有相同$name变量的主页。他们可以在其主页上按“内容”按钮,将其重定向到URL中带有变量$name的内容网页。在主页上,它在$name中显示echo "<h1>$name's Profile</h1>";变量的值,但是由于某些原因,当我在链接上使用它时,它是不确定的。这是代码:

<!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>

2 个答案:

答案 0 :(得分:0)

以下应该有效

<!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>

答案 1 :(得分:-1)

代码假定您有一个名为$ name的变量,而不是$ name。

关闭“并使其:

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

或在字符串中使用{}:

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