How to check if an IP is already stored in mysql? - php

I have this feedback form I made, but I need a bit of help. I want to stop people from posting feedbacks if they already did with the same ip, which is stored in a database. Here is the code:
<?php
if(isset($_POST['add'])){
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
$ip = $_SERVER['REMOTE_ADDR'];
$datetime = date('Y-m-d H:i');
$checkIp = mysql_query("SELECT ip from comments WHERE ip = '$ip'");
if (mysql_num_rows($checkIp) > 0) {
echo "Only 1 feedback per IP allowed!";
$IP = mysql_fetch_array($checkIp);
print_r($IP);
}
if($name){
if($email){
if($comment){
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
mysql_query("INSERT INTO comments (id, name, email, comment, ip, datetime) VALUES ('','$name','$email','$comment','$ip','$datetime')");
}
else
echo "The email address is invalid!<br><br>";
}
else
echo "You haven't entered any comment!<br><br>";
}
else
echo "You haven't entered an email address!<br><br>";
}
else
echo "You haven't entered your name!<br><br>";
}
I tried to have a go myself, but failed (you can see at the top I tried some functions), can someone please tell me how to do it?

You should be using PDO or mysqli_ with prepared statements rather than mysql_ since its deprecated and due to be removed. Also, if you really want IP address to be unique in this table, you should set a unique constraint on the field.
But probably you could get this code working as far as this point (for about 90-98% of cases) simply by adding an exit; in the if-statement where you are checking the number of rows:
if (mysql_num_rows($checkIp) > 0) {
echo "Only 1 feedback per IP allowed!";
$IP = mysql_fetch_array($checkIp);
print_r($IP);
exit; //stop execution here so nothing else happens
}
The code will be open to SQL injection, however, if you continue with mysql_, and it won't be as straightforward and will leave open a technical possibility of somehow ending up with more than one of the same IP in the database.
For example, if two requests came in at once and both read the database as not having the IP yet, then both inserted. With a contraint in the table, that wouldn't happen because the database server would be managing the constraint itself.

Related

Can't get php to post to mysql

Hello I cannot get my php to post to mysql. I get no errors when submitting, but entries are not showing up in my database. I appreciate anyone that can give me advice on how I can fix this. I tried to search around here but couldnt find a dirrect reason on why my php code is not working.
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['element_1']) || empty($_POST['element_2'])) {
die("You have forgotten to fill in one of the required fields! Please make sure you submit your name, and paypal e-mail address");
}
$entry = htmlspecialchars(strip_tags($_POST['entry']));
$timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
$name = htmlspecialchars(strip_tags($_POST['element_2']));
$email = htmlspecialchars(strip_tags($_POST['element_1']));
$comment = htmlspecialchars(strip_tags($_POST['element_3']));
$comment = nl2br($comment);
if (!get_magic_quotes_gpc()) {
$name = addslashes($name);
$url = addslashes($url);
$comment = addslashes($comment);
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
}
mysql_connect('host', 'username', 'password') ;
mysql_select_db('database name');
$result = mysql_query("INSERT INTO payments (entry, timestamp, name, email, comment) VALUES ('$entry','$timestamp','$name','$email','$comment')");
header("Location: post.php?id=" . $entry);
}
else {
die("Error: you cannot access this page directly.");
}
?>
Thanks in advanced for your time, understanding, and knowledge. I greatly appreciate it.
advice on how I can fix this
use var_dump($_POST); after if(isset($_POST['submit']))
do $sql="" and var_dump($sql) and mysql_query($sql);
after query var_dump(mysql_insert_id());
and var_dump(mysql_error());
and dont forget: error_reporting(E_ALL); at the top of the file
Then look what happens
[optional] after first query use SHOW COUNT(*) WARNINGS
Things you should check:
I cant see your database design, so you'll have to make sure that your database columns and table match correctly with what is specified in your database.
echo your variables to make sure none are empty.
Ensure that you are not inserting a string in column of type int or vice versa.
Make sure your form method is POST and that your name attributes match what you have specified in your variables ie $_POST['name_attr'].
The order of your insert columns should be the same order as in your table.
Lastly, i hope host,username,password and database name are just placeholders for your real database info? if not, that's the problem.

Compare IP to SQL table values

I am capturing the visitors ip address during a form submit using the following.
$users_ip=$_SERVER['REMOTE_ADDR'];
What I would now like to do is see if this ip variable has been used before when submitting a comment, can anyone point me in the right direction?
Maybe a like SQL command?
Assuming you stored client ips in the table named: "ips" then use this:
$connection = mysql_connect($your_db_host, $your_user_account, $your_password);
$mysql_select_db($your_db_name);
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "select 1 from `ips` where `ip`='$ip'";
$sql_resource = mysql_query($sql);
$mysql_close($connection);
if($sql_resource && mysql_num_rows($sql_resource) > 0){
// your logic code if the ip existed in the db
echo 'The ip has been used before';
} else {
// code if the ip not existed in the db
echo 'The ip has not been used before yet';
}
There is a good tutorial explaining how to store IP addresses in MySQL. In short, convert them to long like suggested in this comment, then use simple SELECT statement to find it:
"SELECT COUNT(*) FROM comment WHERE ip = " . ip2long($_SERVER['REMOTE_ADDR'])

finding out if two people hold the same ip address php and sql

Right, I have done a small amount of coding, but have yet to find out how to do the following.
If two users have the same IP address, to mark it through echo.
I wish to make it so that if($user222['current_ip'] (has the same as another user)); { //do action
but I can not find the code any where... does it exsist?
I'd be forever grateful for any help (if you can)
my codes are the following:
`$usersearch = mysql_query ("SELECT * FROM users WHERE online = 'Online'");
$user222 = mysql_fetch_array($usersearch);`
<? if ($user222['reg_ip'] == $user222['current_ip']) {
echo "<font color='green'><b>".$user222['current_ip']."</b></font>";
} else if ($user222['reg_ip'] != $user222['current_ip']) {
echo "<font color='orange'><b>".$user222['current_ip']."</b></font>"; } else //add new code here ?>
EDIT::: I am wanting to find out if two users are registered with the same IP address through SQL. If there is then to echo the reason.
The question is very vague, however the client IP address can be obtained in PHP like this:
$client_ip = $_SERVER["REMOTE_ADDR"];
http://php.net/manual/en/reserved.variables.server.php
You could use cookies if you want to figure out if users are different based upon their browsers. One user could use multiple browsers, though.
As anttix said, you can use "$_SERVER['REMOTE_ADDR']" to obtain the user IP address. You have to register in the MySQL database all the IP addresses, of course.
$result = mysql_query("
SELECT *
FROM users
WHERE
ip = '$_SERVER[REMOTE_ADDR]';
");
while ($row = mysql_fetch_array($result)) {
if ($_SERVER['REMOTE_ADDR'] == $row[ip]) {
// do something
}
}

FILTER_VALIDATE_EMAIL

I understand this has been discussed before but since this post in late 2010 and other discussions around that time when issues were raised - Does FILTER_VALIDATE_EMAIL make a string safe for insertion in database? - I have tried some of the situations described, such as using single quotes and the ` characters in an email form where I am using FILTER_VALIDATE_EMAIL and it has blocked them from being entered into the database.
Have recent releases of PHP fixed earlier issues and is it safe?
I'm tempted to also use mysql_real_escape_string(), presumably the two functions can be used in parallel without any conflict?
Here is the mailing list code that I am using to put addresses into the database
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "unsub")) {
// trying to ubsubscribe; validate email addresses
if ($_POST["email"] == "") {
header("Location: mailing_list_remove.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// print failure message
$display_block = "We couldn't find ".$_POST["email"].". No action has therefore been taken.";
} else {
// get value of ID from result
while ($row = mysqli_fetch_array($check_res)) {
$id = $row["id"];
}
// unsubscribe the address
$del_sql = "DELETE FROM subscribers
WHERE id = '".$id."'";
$del_res = mysqli_query($mysqli, $del_sql)
or die(mysql_error($mysqli));
$display_block = " Your email address, ".$_POST["email"].", is unsubscribed!";
}
mysqli_close($mysqli);
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
The filter_var flag FILTER_VALIDATE_EMAIL will do what it says = Validate value as e-mail, meaning if its not an email it will return false.
You might be looking for FILTER_SANITIZE_EMAIL which will (Remove all characters, except letters, digits and !#$%&'*+-/=?^_`{|}~#.[] )
or
FILTER_SANITIZE_STRING will Strip tags, optionally strip or encode special characters.
Tho I don't recommend w3schools it has a list of filter_var flags http://www.w3schools.com/php/php_ref_filter.asp
Also as others have said, use PDO's prepared query's tobe safe, you can find a great pdo example here: http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#10 which will explain a few things and there is also a simple pdo CRUD (Create Retrieve Update Delete) class here: http://www.phpro.org/classes/PDO-CRUD.html
good luck...

mysqil_real_escape_string() error I can't fix

Although the item is successfully added to the database, I'm not sure that I'm executing the mysql_real_escape_string() function correctly and, thus, getting the error. Any help is appreciated.
Success!
Warning: array_map() [function.array-map]: Argument #2 should be an array in /home/site4/public_html/lab/mailing_list_dev_1-0/mailing_list_add.php on line 32
Thanks for signing up!
Here's the code in question...
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo 'Success!';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = array_map("mysqli_real_escape_string", ($_POST["email"]));
// add record
$add_sql = "INSERT INTO subscribers (email)
VALUES('".$_POST["email"]."')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address, ".$_POST["email"].", is already subscribed.";
}
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
You're treating $_POST['email'] as an array, which it probably ins't.
If you only intended to escape email, do
$email = mysqli_real_escape_string($dbConn, $_POST['email']);
Then in your INSERT statement, use the escaped $email instead of $_POST['email']
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
array_map() is meant for arrays. If all you have is a single value then just call the function directly.
There is at least one bug, here:
// Does not work because $_POST["email"] is a string, not an array
$email = array_map("mysqli_real_escape_string", ($_POST["email"]));
This looks like something you adapted from code that was working, but right now it's broken. You probably wanted something like this:
$post = array_map("mysqli_real_escape_string", $_POST["email"]);
after which you can use $post["email"] safely, as it has been escaped.
Of course escaping everything inside $_POST is possibly not the best way to go about this. There's still the mundane but spot-on way to consider:
$email = mysqli_real_escape_string($_POST['email']);
This is apparently not mysqli_real_escape_string problem but array_map() problem. Or rather misuse of the latter one.
However, you will face mysqli_real_escape_string() problem as soon as you solves this one.
To solve this latter your doDB() function have to return connection id, which you have to use with every mysqli_* function.
$conn = doDB();
$email = mysqli_real_escape_string($conn,$_POST["email"]);
thus you will have all your [listed] problems solved but I believe that emailChecker will may cause the same kind of problem of inexistent $check_res variable. Instea d of which such a function apparently have to return just a boolean and used like
if (!emailChecker($_POST["email"])) {

Categories