php - I can't get my redirect to work if the user's ip is in the database
I am creating a welcome page for my site that will be displayed to the user if they haven't already been on the website.
I have created a landing page called welcome that will add the users ip to a table in a database when they visit my website.
On my homepage I am trying to make it so that if the users ip is in the database then it won't redirect them to the welcome page and if the ip is not in the database then it will redirect them to the welcome page and on that page their ip will be added to the database so that they do not get redirected next time they visit the site.
Here is my code so far, when I go onto the site it doesn't redirect me to the landing page and I am not sure what the issue is:
<?
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
$query = "SELECT * FROM landing WHERE ip = $ip";
$result = mysql_query($query);
$num = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
if($num == '0') {
header("Location: https://tantami.com/welcome/index.php");
} else {
}
}
?>
Answer
Solution:
If enough to check in the database if there's a record of that ip:
Answer
Solution:
There are several issues going on here, in a rough order of importance with regards to your problem they are:
Encase your value in quotes. so
SELECT * FROM landing WHERE ip = '$ip'
notice the$ip
is encased, as is required for strings in a Query.Please start to use MySQLi rather than the deprecated MySQL. This is more secure, and still supported by both MySQL and PHP. research on StackOverflow how to make the pretty easy transfer.
Your mysql_num_rows is a integer count so should not be in quotes. So set
if (mysqli_num_rows($result) == 0 )
.Immediately after your
header()
you should add a die or end command such asexit;
PHP should ideally always open with a full
<?php
declaration.I'll say it again, use MySQLi.
The
$ip
should be escaped in this script, specifically, usemysqli_real_escape_string()
or even use a REGEX pattern to remove any non valid characters from the$ip
, before testing in the SQL query.Code:
$ip = preg_replace("/[^0-9:.]/","",$ip);
Answer
Solution:
your problem was in your query.
you should add (Apostrophe) before and after of all string in query.
(i also change your select * query yo select count(*))