While working on my website today, I came across this -
Site url is -
http://url.com/?age={age}
I use the GET function to pass the variable -
<?php
$age = $_GET['age'];
?>
I have a url on this page but I want to change it based on the visitor age, for example -
0-20 years old ---> http://url.com/teenagers/
21-40 years old ----> http://url.com/adults/
40+ years old ----> http://url.com/matures/
I have the following code in mind -
<?php
if ($age <= '20')
{
echo '<a href="http://url.com/teenagers/">URL</a>';
}
else if($age >= '40')
{
echo '<a href="http://url.com/matures/">URL</a>';
}
else{
echo '<a href="http://url.com/adults/">URL</a>';
}
?>
I'm not even sure if the code is correct, when I append some random letters (not numbers), it points to http://url.com/matures/ instead of http://url.com/adults/. And if I don't append anything after the age variable, I get pointed to http://url.com/teenagers/.
Am I missing something here?
First of all, if $age
will be a string and you will check like:
if($age && $age <= 20)
In this case $age will be equal 1, because, look here
Second. You need to check 20 or 40 not like string('20', '40' ). Dot this:
if (is_numeric($age)) {
$var = "";
if ($age <= 20) {
$var = 'teenagers';
} else if ($age >= 40) {
$var = 'matures';
} else {
$var = 'adults';
}
echo '<a href="http://url.com/'.$var.'/">URL</a>';
}
If $age is not intger you can redirect to some another page
Before this checking you can check if $age even integer(because someone can set in url not int) using is_numeric
<?php
$age = 40;
if ($age <= 20) {
echo '<a href="http://url.com/teenagers/">URL</a>';
} else if ($age >= 40) {
echo '<a href="http://url.com/matures/">URL</a>';
} else {
echo '<a href="http://url.com/adults/">URL</a>';
}
?>
You just need to remove the quotes around the string. Assuming your string is just numerical
In the current version of your code you are comparing strings not numbers. Strings are always compared in alphabetical order so 'b' > 'a'
and 'a' > '1'
. That is why you get the result matures
for non-numeric strings.
As other suggest you should just drop the quotes in the if
statements to issue a numeric comparison. PHP will then try to translate your string to a number and compare the two as numbers.
If you let your users put anything in the age
parameter you should take this into consideration in your code:
<?php if (
null !== $age // make sure the `age` parameter is not left empty
&& is_numeric($age) // make sure it's a number
&& $age < 20
) {
...
} elseif ($age > 40) {
// if the age is empty or is not a number it will never be bigger than
// a numeric 40
...
} else {
// this will cover all other cases so:
// - empty `age`
// - non-numeric `age`
// - `age` between 20 and 40 (inclusive)
...
}
?>