i'm new in coding and have a problem coding on Mac.
When i do var_dump($_POST), answer is: array(0){}
Here is the code:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name=strip_tags($_POST["name"]);
$age=$_POST["age"]*1;
$_SESSION["name"] = $name;
$_SESSION["age"] = $age;
}
else {
$name = $_SESSION["name"];
$age = $_SESSION["age"];
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Session demonstration</title>
</head>
<body>
<h1>Session demonstration</h1>
<a href="session-2.php">Demo session</a><br>
<a href="session_destroy.php">Close session</a><br><br>
<form action="<?=$_SERVER["PHP_SELF"]?>"
method="post">
Your name is:
<input type="text" name="name" value="<?php echo $name?>"><br>
You are:
<input type="text" name="age" value="<?php echo $age?>"><br>
<input type="submit" value="Submit">
</form>
<?php
if ($name and $age) {
if ($name and $age) {
echo "<h1>Hello, $name</h1>";
echo "<h3>You are $age</h3>";
}
else {
print "<h3>Bye!</h3>";
}
}
?>
</body>
</html>
Same time, when i press submit button it shows me:
Notice: Undefined index: name in /Applications/MAMP/htdocs/PHP_Course 2/demo/mod2/sessions/session-1.php on line 5
Notice: Undefined index: age in /Applications/MAMP/htdocs/PHP_Course 2/demo/mod2/sessions/session-1.php on line 6
Maybe someone knows what can i do.
Sincerelly
the problem with this is your session variables are not set at the beginning and you are trying to assign your $name and $age with those unassigned variables on your else block. Validate your assignments like this.
<?php
session_start();
$name = $age = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = strip_tags($_POST["name"]);
$age = $_POST["age"] * 1;
$_SESSION["name"] = $name;
$_SESSION["age"] = $age;
} elseif (isset($_SESSION['name']) || isset($_SESSION['age'])) {
if (isset($_SESSION['name'])) {
$name = $_SESSION['name'];
}
if (isset($_SESSION['age'])) {
$age = $_SESSION['age'];
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Session demonstration</title>
</head>
<body>
<h1>Session demonstration</h1>
<a href="session-2.php">Demo session</a><br>
<a href="session_destroy.php">Close session</a><br><br>
<form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
Your name is:
<input type="text" name="name" value="<?php echo $name ?>"><br>
You are:
<input type="text" name="age" value="<?php echo $age ?>"><br>
<input type="submit" value="Submit">
</form>
<?php
if ($name and $age) {
echo "<h1>Hello, $name</h1>";
echo "<h3>You are $age</h3>";
} else {
print "<h3>Bye!</h3>";
}
?>
</body>
</html>
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.