I have the below code that i am wanting to into certain files so that when someone visits this "certain" file they get banned if they are not allready. but for some reason it is not adding new visitors into the database, if i add a user manually it works fine and echo's Banned! but otherwise it just echo's the $sql query but does not actually do it.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="banlist"; // Database name
$tbl_name="list"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$sql="SELECT * FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count==0){
$sql="INSERT INTO $tbl_name (`id` ,`ip`) VALUES (NULL , $ip)";
mysql_query($sql);
echo $sql;
//header("location:index.html");
} else {
// Register $myusername, $mypassword and redirect to file "login_success.php"
//header("location:index.html");
echo "banned!";
exit();
}
?>
Have you double-checked that your MySQL account has the INSERT privilege?
You'll also find that things go more smoothly if you always check the return value of mysql_query(). While you're developing, you could change these lines (from the end of your snippet):
mysql_query($sql);
echo $sql;
... to this:
$result = mysql_query($sql);
if($result === FALSE) {
echo 'INSERT failed with this error: '.mysql_error();
} else {
echo 'INSERT succeeded';
}
Also if you're not yet familiar with SQL injection, you'll want to become familiar with it. Your code is currently vulnerable to this kind of attack, because it doesn't filter input (the HTTP headers where you're looking for an IP address) and it doesn't escape output (the variable portion of your dynamically-constructed SQL queries).
just few remarks
$sql="SELECT * FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
wouldn't be better to do a
$sql="SELECT count(*) FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
since you don't use that data.
$sql="INSERT INTO $tbl_name (`id` ,`ip`) VALUES (NULL , '$ip')";
mysql_query($sql);
if your id is an auto increment you don't have to include it
$sql="INSERT INTO $tbl_name (`ip`) VALUES ('$ip')";
mysql_query($sql);
You should quote $ip since it's probably a varchar in your table.
Since an ip address should be a sort of unique identifier you have better to use the IP as primary key.
last point checking for results of mysql_query would be a good pratice, like there
$sql="INSERT INTO $tbl_name (`ip`) VALUES ($ip)";
$ret = mysql_query($sql);
if (!$ret) {
die('Invalid query: ' . mysql_error());
}
I think it would give you valuable information about what is happening. in that case it would probably say you have an error near the IP address (because of the missing quotes).
Related
I've read quite a few different posts, but none seem to be helping me nail this script I'm writing for a login page.
Basically I want it to do the 'normal' login check username and password against a MYSQL DB/table then based on the users assigned role forward to a specific web page. The DB has four columns id, username, password, and a ROLE column. In the ROLE column in the DB I have Superuser, Manager, Site1 or Site2 against the user names.
The script runs and at the moment dumps out on a syntax error, but I think thats my fault with not using {}'s correctly around the switch($row["ROLE"]) line. Previously I got the script running, but it wasn't matching the ROLE's and I was getting the echo "Wrong Login or password" message, so I know I'm close.
Here is my checklogin PHP script so far:
<?php
ob_start();
$host="XXXXXX"; // Host name
$username="XXXXXX"; // Mysql username
$password="XXXXXX"; // Mysql password
$db_name="XXXXXX"; // Database name
$tbl_name="XXXXXX"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$row = mysqli_fetch_array($rslt, MYSQLI_ASSOC);
switch($row["ROLE"])
$sql="SELECT ROLE FROM $tbl_name WHERE username={$myusername} and password={$mypassword}";
{
case 'Superuser':
header("location:http://www.XXXXXX.com/1/index.html");
break;
case 'Manager':
header("location:http://www.XXXXXX.com/2/index.html");
break;
case 'Site1':
header("location:http://www.XXXXXX.com/3/index.html");
break;
case 'Site2':
header("location:http://www.XXXXXX.com/4/index.html");
break;
default:
echo "Wrong Login or password";
}
}
else {
header("location:login_fail.php");
}
ob_end_flush();
?>
Any help or advice gladly welcomed.
Simon
Update1: Ok when I modified the code and remove the $sql=SELECT... line the script runs fine no syntax issue but doesn't match the ROLE of the logged in username and displays Wrong Login or password.
If I add back in and modify the $sql="Select.. line:
switch($row['ROLE'])
$sql="SELECT ROLE FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
I get the following syntax error:
Parse error: syntax error, unexpected '$sql' (T_VARIABLE), expecting ':' or ‘{‘ XXXXX on line 37
Hmmm...
Update2:
Ok I think I've tidied this up a bit as per comments below:
$sql="SELECT * FROM $tbl_name WHERE myusername='$myusername' and mypassword='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$row = mysql_fetch_array($rslt, MYSQL_ASSOC);
switch($row['ROLE'])
$sql="SELECT ROLE FROM $tbl_name WHERE myusername='$myusername' and mypassword='$mypassword'";
{
case 'Superuser':
header("location:
Now this chucks the syntax error:
Parse error: syntax error, unexpected '$sql' (T_VARIABLE), expecting ':' or '{' in /XXXXX on line 37
Which relates to:
$sql="SELECT ROLE FROM $tbl_name WHERE myusername='$myusername' and mypassword='$mypassword'";
Update3:
Ok having re read the comments below I've now changed the code dumping some of the offending lines (see below).
$sql="SELECT * FROM $tbl_name WHERE myusername='$myusername' and mypassword='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// ??
$row = mysql_fetch_array($rslt, MYSQL_ASSOC);
switch( $row['ROLE']){
case 'Superuser':
header("location:http://
Problem I have now is I don't seem to be matching against the values in the ROLE column of the DB table and I'm not sure why. I'm pulling all the values back with the *.
As ever thoughts and observations welcomed.
Update 4:
Chaps still fighting with this tried this method below using 'elseif' but not working. The script runs but doesn't go beyond option 1 (Superuser) even if the ROLE is set as Manager. Any ideas?
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){
// Register $myusername, $mypassword and redirect to file"login_success.php"
$_SESSION['username'] = $myusername;
$_SESSION['password'] = $mypassword;
$result = mysql_fetch_array($result); // get the result set from the query
$redirect = trim($result['ROLE']); // get the redirect column's value
if ($redirect == '')
{echo "No redirect value set";}
elseif ($redirect="Superuser"){header("Location: http://www.xxxx.com/1/index.html");}
elseif ($redirect="Manager"){header("Location: http://www.xxxx.com/2/index.html");}
elseif ($redirect="User1"){header("Location: http://www.xxxx.com/3/index.html");}
elseif ($redirect="User2"){header("Location: http://www.xxxx.com/4/index.html");}
exit;
}
else
{ echo "Wrong Username or Password"; }
ob_end_flush();
?>
Is my issue that I'm not matching the column of ROLE's value in the DB??
PS I have no syntax errors now ;)
Update 5: Fixed it!!
My issue was using elseif instead of if and not using == in my code lines, so it should look like this...
if ($redirect=="Superuser"){header("Location: http://www.xxxxx.com/1/index.html");}
Now I can sleep. Thanks all for input.
You have syntax errors in PHP and SQL:
switch($row['ROLE']) {
$sql = ".."; // illegal. a switch can contain only `case` and `default` clauses.
And then your SQL in that illegal line is wrong as well:
$sql="SELECT ROLE FROM $tbl_name WHERE username={$myusername} and password={$mypassword}";
^-----------^ ^-----------^
You are missing quotes around the two insert variables, which means your query will be
SELECT ... WHERE username=fred and password=hunter42
Unless you have fred and hunter42 fields in your table, that query will fail with "unknown fields"
You are also mixing mysql and mysqli functions. They are NOT interchangeable, and connections/results from one are utterly useless/meaningless in the other. Plus you have variable name mismatches:
$result=mysql_query($sql);
^^^^^^^--- note this variable
^---note the lack of an "i"
$row = mysqli_fetch_array($rslt, MYSQLI_ASSOC);
^----note the "i"
^^^^--note the different variable
I'm trying to insert into several related database tables some data after clicking a submit button, my tables are:
USERS: ID (primary key), User, Name, Password
LEVELS: ID, User_ID (foreign key), Level1, Level2, Level3, Level4
where User_ID on the table levels is the same ID as the primary key for users.
I want to make this insert with php, my code is as follows:
$host="xxxxxx"; // Host name
$username="xxxxxx"; // Mysql username
$password="xxxxxx"; // Mysql password
$db_name="xxxxxx"; // Database name
$tbl_name="USERS"; // Table name
// Connect to server and select databse.
$dbh= mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// sent from form
$name=$_POST["name"];
$user=$_POST["user"];
$password=$_POST["password"];
$L4=$_POST["L4"];
$L3=$_POST["L3"];
$L2=$_POST["L2"];
$L1=$_POST["L1"];
$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$userid = mysql_insert_id();
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");
$sql2 = "INSERT INTO LEVELS (User_ID, Level1, Level2, Level3, Level4) VALUES('$userid','$L1','$L2','$L3','$L4');";
$tab2= mysql_query($sql2, $dbh) or die ("problem query 2");
either, I don't get how to relate the tables, or something here is wrong, cause only the first sql statement is being executed, and the second one prints the die 'problem query 2'.
Can anybody please help me?
Thanks!
$userid = mysql_insert_id();
should be called after the insert query is executed and in your case you are calling it before the first query being executed.
So it should be as
$sql="INSERT INTO $tbl_name (Name, User, Password) VALUES('$name','$user','$password');";
$tab1= mysql_query($sql, $dbh) or die ("problem query 1");
$userid = mysql_insert_id();
i'm going to update a row into mysql database. the senarius is: taking the values from a form and redirect to another file and set the form values to database using update statement. the problem is that mysql_query return value 1 and does not return any error but when i check the database through phpmyadmin my database doesn't affected.
here is the code
<?php
$host="localhost";
$username="root";
$password="";
$db_name="login_takrim";
$tbl_name="takrim_users";
// Connect to server and select databse.
mysql_connect("c$host","$username","$password") or die("can not connect");
mysql_select_db($db_name) or die(mysql_error());
// username and password sent from form
$myusername=$_POST["txtusername"];
$mypassword=$_POST["txtpassword"];
$myemail=$_POST["txtemail"];
// To protect MySQL injection
$myusername=stripslashes($myusername);
$myemail=stripslashes($myemail);
$mypassword=stripslashes($mypassword);
$myemail=mysql_real_escape_string($myemail);
$myusername=mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);
echo "$myusername $mypassword $myemail";// test to see i get the form value on the php server.
$sql="UPDATE $tbl_name SET username = '$myusername' and password = '$mypassword' and email= '$myemail' where showname='hussein'";
$result=mysql_query($sql) or die(mysql_error());//does not return error
echo $result;
if($result==false)
{
echo "no";
}
else
{
//header("location:setEmail.php");
echo "yes";
}
?>
query may excuted correctly may be there was no matching records just do like this
<?php
$host="localhost";
$username="root";
$password="";
$db_name="login_takrim";
$tbl_name="takrim_users";
// Connect to server and select databse.
mysql_connect("c$host","$username","$password") or die("can not connect");
mysql_select_db($db_name) or die(mysql_error());
// username and password sent from form
$myusername=$_POST["txtusername"];
$mypassword=$_POST["txtpassword"];
$myemail=$_POST["txtemail"];
// To protect MySQL injection
$myusername=stripslashes($myusername);
$myemail=stripslashes($myemail);
$mypassword=stripslashes($mypassword);
$myemail=mysql_real_escape_string($myemail);
$myusername=mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);
echo "$myusername $mypassword $myemail";// test to see i get the form value on the php server.
$sql="UPDATE $tbl_name SET username = '$myusername', password = '$mypassword',email= '$myemail' where showname='hussein'";
$result=mysql_query($sql) or die(mysql_error());//does not return error
if(mysql_num_rows($result) > 0)
{
//header("location:setEmail.php");
echo "yes";
}
else
{
echo "no";
}
?>
Chage your UPDATE statement like this
$sql="UPDATE $tbl_name SET `username` = '$myusername',`password` = '$mypassword',`email`= '$myemail' where `showname`='hussein'";
Disclaimer: Stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.
You have an extra c here (before $host):
mysql_connect("c$host","$username","$password") or die("can not connect");
I have made a small website, non-members can register with the website, when they register their details should be stired in the database table. I had this working but now it is not, it does everything apart from store the details in the database. Can anyone help please?
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$repeatpassword=$_POST['repeatpassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = strip_tags($myusername);
$mypassword = strip_tags($mypassword);
$repeatpassword = strip_tags($repeatpassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$repeatpassword = mysql_real_escape_string($repeatpassword);
if($myusername&&$mypassword&&$repeatpassword)
{
if ($mypassword==$repeatpassword)
{
if (strlen($myusername)>10)
{
header("location:erroruname.php");
}
else
{
if (strlen($mypassword)>10||strlen($mypassword)<5)
header("location:errorpword.php");
else
{
$queryreg = mysql_query("
INSERT INTO $tbl_name VALUES('','$myusername','$mypassword')
");
session_register("myusername");
session_register("mypassword");
header("location:insertdetail.php?myusername=" . $username);
}
}
}
else
header("location:errornomatch.php");
}
else
header("location:errorfields.php");
This was never working because you aren't specifying any column names in your INSERT
INSERT INTO $tbl_name VALUES('','$myusername','$mypassword')
Needs to look like
INSERT INTO $tbl_name(`column_a`, `username`, `password`)
VALUES('','$myusername','$mypassword')
Do you have an auto-increment column in that table? If so, don't use the ' ', instead, don't enter anything at all. In that case, you should specify only the two columns (username and password).
echo the query and run manually the sql query in phpmyadmin
echo "INSERT INTO $tbl_name VALUES('','$myusername','$mypassword') "; die();
I am trying to setup a website that will know if a user has logged into the website before. The MYSQL table has a username, password and firstLogin field. The firstLogin field is an integer field containing 1 if the user has not logged and 2 if they have logged in in the past.
The login sysetm logs in and starts a session as it should do therefore i am certain the count is returning the value of 1. The problem that i am having is the website is going straight to homepage.php even if the firstLogin integer is set to 1. The website should be going to welcome.php whilst performing an update operation to change the integer to 2. Ive been staring at this for about a week now. Hope you can help.
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST ['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT username, password,firstLogin FROM $tbl_name WHERE username='".$myusername."' and password= sha1('".$mypassword."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$row = mysql_fetch_array($result);
print_r($row);
exit;
if ($row ['firstLogin']=="1")
{
$sql2 ="UPDATE $tbl_name SET firstLogin = '2' WHERE username ='".$myusername."'";
session_start();
session_register("myusername");
session_register("mypassword");
header("welcome.php");
}
else
{
session_start();
session_register("myusername");
session_register("mypassword");
header("location:home.php");
}
}else
{
echo "Wrong Username or Password";
}
?>
In addition to Jeff Parker's fixes, I might suggest extracting your session starting code into a function so that you're not repeating your code. I already see your code introducing a copy and paste error.
Also, I think $row['firstLogin'] == 1 would be acceptable, considering that the row will be returning an integer as opposed to a string.
if ($row ['firstLogin']=="1")
{
$sql2 ="UPDATE $tbl_name SET firstLogin = '2' WHERE username ='".$myusername."'";
session_start();
session_register("myusername"); //!! This is possibly an error, you're saving myusername as opposed to $myusername
session_register("mypassword"); // Same as above
header("welcome.php"); // This is possibly an error since the header is missing the "location:" part
}
else
{
session_start();
session_register("myusername");
session_register("mypassword");
header("location:home.php");
}
Can be turned into
if ($row ['firstLogin']=="1")
{
$sql2 ="UPDATE $tbl_name SET firstLogin = '2' WHERE username ='".$myusername."'";
start_session_and_redirect('welcome.php');
}
else
{
start_session_and_redirect('home.php');
}
then place a function ...
function start_session_and_redirect($location){
session_start();
session_register("myusername"); // I'm also wondering if that's supposed to be $myusername instead of "myusername...
session_register("mypassword");
header("location:$location");
}
You have an error in your above code possibly if php doesn't automatically fix it, where welcome.php doesn't have "location:" in front of it, which can be entirely prevented by having a function for the repeat functionality, something you should always be looking to eliminate from your code.
if ($row ['firstLogin']="1") // wrong
You're doing an assignment. It should be a comparison.
if ($row ['firstLogin'] == "1") // right
There's also an error in the query used to retrieve the user data.
// -- This is wrong, missing the ending parenthesis, and will not run.
$sql="SELECT username, password,firstLogin FROM $tbl_name WHERE
username='".$myusername."' and password= sha1('".$mypassword."'";
// -- This includes the ending parenthesis, and should run.
$sql="SELECT username, password,firstLogin FROM $tbl_name WHERE
username='".$myusername."' and password= sha1('".$mypassword."')";