Simple Question: Trying to set a cookie for capturing user city in a PHP form - not able to get cookies set despite referring to all related SO threads and tutorials.
cityform.php
<p>Enter Your City?</p>
Enter City:
<?php
echo "<table align='center'><tr><td><form action='https://example.com/getcityform.php' method='get' target='_top'><input type='text' name='cityname' value='' /><input type='submit' name='submit' value='Submit'></form></table><br>";
?>
getcityform.php
<!DOCTYPE html>
<?php
if (!empty($_GET))
{
$cookie_name = "city";
$cookie_value = $_GET["cityname"];
echo "Value Captured: ".$cookie_value."<br>";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
header("Location:getcityform.php"); //Included this based on SO thread, but not working
}
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
However, the output is always (even after multiple refresh of the page):
Value Captured: New York
Cookie named 'city' is not set!
PS: Referred to W3Schools (https://www.w3schools.com/php/func_network_setcookie.asp) , and also to getting cookie value from php form SO thread.
Based on the later, I included the header("Location:getcityform.php");
, but still it shows cookie not set error message.
Including !empty($_GET)
check has also not helped.
Other threads, like set cookie in php directly from form input, are also not relevant as they have minor errors like variable names mismatch.
I also tried to set the cookie without taking inputs from the form - i.e. - directly set the cookie name/value in the single php file, but it is still not working.
What may be going wrong here please?