I have been looking for multiple ways to redirect users to a html page when a certain access code if submitted in a form. I have the form up and is working properly, but I can’t get it to redirect to the right page, I have seen 1 other post like this, but with specific user login.
<?php
$_GET["code"] = $accessCode;
if ($accessCode === "code123") {
header("Location: http://www.example.com/code_123.html");
} else if ($_GET["code"] === "test") {
header("Location: http://www.example.com/code_test.html");
} else {
header("Location: http://www.example.com/unknown_code.html");
}
?>
I even tried using the redirect option (cPanel)
Whenever I use the code code123 or test, they redirect me to unknown_code.html
I tried using both if ($accessCode === "code123")
and ($_GET["code"] === "test")
2
Answers
You need to assign the value of $_GET[‘code’] to $accessCode.
Also, when you are comparing a single variable to several values, use a switch statement.
It’s a good idea to follow a redirect header with exit – you’re done at that point.
You have it backwards.
When you are making an HTTP “GET” Request, PHP will store the “query string parameters” in the global $_GET array.
For example, http://www.yoururl.com?code=code123&mobile=1
In this context, the query string starts with “?” and is delimited by “&”, leaving you with key value pairs of:
PHP converts that and stores it in the global $_GET array as such:
The same thing would happen if you were to do an HTTP POST request, where instead of the query string, the HTTP POST Request “Body” contains the query string, or in some cases, JSON, or XML, etc.
PHP would parse that and you would get as so:
So for your context, you actually have it backwards.
You want to “assign” $accessCode with the value stored in the $_GET array at index “code”