using $_GET with PHP if statement and MYSQL - php

So I'm having a problem with the logic behind this statement on my PHP login website. Here is the code:
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$results=mysql_query("SELECT temporary_password FROM $tbl_name");
$row = mysql_fetch_array($results);
if($_GET['temp_password'] != $row['temporary_password'] && $_GET['temp_username'] != $row['temporary_username']){
mysql_close();
header("Location: index.php");
}
basically I have a registration webpage that should only be accessed if the users URL contains both temp_username AND temp_password and that both of those variables exist inside the database. Currently I can get this to work using OR (||) instead of AND (&&) this statement only works if either password OR username exists, but I want the person to access this site only if both temp_username and temp_password are true, otherwise forward to the index page.
what's wrong with my logic?
P.S. I know mysql_* is not secure, I currently don't have time to transition to mysqli.

Your query should be this:
$results=mysql_query("SELECT temporary_password,temporary_username FROM $tbl_name");
Or you can make your like this:
$results=mysql_query("SELECT temporary_password,temporary_username FROM $tbl_name where temporary_username = '".$_GET['temp_username']."'");
As you are not selecting the temporary_username from the Database so it is not checking the last condition in if condition.
That's it is working for OR condition and not for AND.
So use the above query and it will work for And condition also.

Given:
if($_GET[...snip...] && $_GET['temp_username'] != $row['temporary_username']){
^^^^^^^^^^^^^^^^^^---this
Don't you think you might want to add it:
$results=mysql_query("SELECT temporary_password FROM $tbl_name");
^----- here?

You should add a WHERE statement into your query:
"SELECT count(*) from $tbl_name WHERE temporary_username = :username AND temporary_password = :password"

You need to check username and password from database
$results=mysql_query("SELECT temporary_password FROM $tbl_name where temp_username = $_GET['temp_username'] AND temporary_password = $_GET['temp_password'] ");
then if it both matched then grant it access else redirected to index.php
or it will be better to check rowcount >0
if($_GET['temp_password'] == $row['temporary_password'] && $_GET['temp_username'] == $row['temporary_username']){
// access granted
}
else {
//wrong credential
header("Location: index.php");
}
you should use pdo or mysqli since mysql_* is deprecated

Related

update database from confirmation link email

Anyone can help me pls!
This code supposed to compare between the passkey from the confirmation email and the confirm_code from the database and if the two value are identical it update "verified" row from null to 1.
Thank you and sorry for my english :/
//Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$passkey=$_GET['passkey'];
$confirm_code=$_GET['confirm_code'];
if($confirm_code == '$passkey';){
$sql1="UPDATE $tbl_name SET verified='1' WHERE $confirm_code ='$passkey'";
echo "Confirmation code verified!!!";
}
else {
echo "Wrong Confirmation code";
}
?>
Change if($confirm_code == '$passkey';){ to if($confirm_code == "$passkey"){
Also notice the double quotes around $passkey.
Check your syntax first, maybe this is the problem here :
if($confirm_code == "$passkey"){
Are you not supposed to retrieve first the passkey from database then compare it with the one GET from URL ? Here you use GET for both of them.
You have an incorrect SQL statement
$sql1="UPDATE $tbl_name SET verified='1' WHERE $confirm_code ='$passkey'";
That $confirm_code should be confirm_codeand should correspond to the column in your table having the stored key. So you will be simply updating the record where the passed key is equal to the stored key.

sql=update returns a successful message but no changes were made to db

I am trying to update a database with the following code:
// 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");
// update data in mysql database
$sql="UPDATE $tbl_name SET FirstName='$FirstName', LastName='$LastName', >>>>Email='$Email' WHERE id='$id'";
$result = mysql_query($sql) or die(mysql_error());
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='list_records.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
I get a successful message but the information was not changed. I realize this code is open to hacking and I will address that but I want to get it to work first.
If there's no error and you got zero modified rows, it must mean that you either write the same information that's already there or no rows match the condition. So either you don't have a row with the given ID, or you're writing the same value for every field that's already in the record.
Remove >>>> code in your update statement.
UPDATE $tbl_name SET FirstName='$FirstName', LastName='$LastName',
Email='$Email' WHERE id='$id'"
Also Check whether the $id is existing in the table.

Can i pull a URL from a mysql database attached to a log in?

I want to know if i can use a URL in a database attached to a login that when the user logs in the script will read the url redirect to that? Or any other ideas on a simple unique login redirection?
My database is made up of columns ID/username/password/url - obviously i have the connection things sorted just though you wouldnt need to see them ;)
and my code is
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$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);
$count=mysql_num_rows($result);
$count=mysql_num_rows($result);
if($count==1){
session_register("myusername");
session_register("mypassword");
header('Location: '.$row['url']);
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
Yes, you can. At login time, just read the URL from the database table and redirect using header('Location: ...');
You would not create such a thing in yor database.
You can house a url field in your DB to be used when they login though.
In your PHP script once you have verified the user actually exists and his/her password is correct by getting a result row from the DB (more complex logins would do more of course) you can use something like:
header('Location: '.$row['url']);
To redirect that user to another page depending upon their logged in status. Though as a tip make sure they are logged using some kind of $_SESSION variable that is set just before you redirect them and has its value checked on the other page.
Edit
Use of session_register is deprecated: http://php.net/manual/en/function.session-register.php
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql="SELECT * FROM $tbl_name WHERE username=".mysql_real_escape_string($myusername)." and password=".mysql_real_escape_string($mypassword);
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
while($row = mysql_fetch_assoc($result)){
header('Location: '.$row['url']);
exit(); // As a user above mentions this is actually quite important
}
}else{
echo "Wrong Username or Password";
}
Take out that end PHP tag, you really don't want it. I think that should work, you might get an SQL error in which case you can probably work out that it's the quotes causing pain and should encapsulate the field values with ' but I always forget how mysql_real_escape_string escapes so Ima just leave it like that for now.
With the login fields in your database add a field specifying the url. Now when the person logs in retrieve the URL and then use the following code to redirect to the retrieved url
header('Location: http://www.example.com/');

Why Am I Getting This SQL Error?

I am trying to see if there is a match from a form to my database. here is my php code:
<?php
$host="localhost"; // Host name
$username="****"; // Mysql username
$password="*****"; // Mysql password
$db_name="*****"; // Database name
$tbl_name="public"; // 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");
$door=$_POST['door'];
$postcode=$_POST['postcode'];
// To protect MySQL injection (more detail about MySQL injection)
$door = stripslashes($door);
$postcode = stripslashes($postcode);
$door = mysql_real_escape_string($door);
$postcode = mysql_real_escape_string($postcode);
$sql="SELECT * FROM $tbl_name WHERE door ='$door' AND postcode='$postcode' AND active = 'not_activated' AND ref = '". $_SESSION['ref']."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
header("location:securityquestion.php");
}
?>
the error message i am getting is as follows:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /home/jahedhus/public_html/system/checkdetails.php on line 36
line 36 is $count=mysql_num_rows($result);
what am i doing wrong here?
Because, just like many, many others here, the code blindly assumes that the query succeeded and everything is fine. Check for errors after each operation. Most of the functions return false when they fail.
Because your query failed.
php.net/mysql-query: "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
Try this:
$result=mysql_query($sql) or die(mysql_error());
You need to do two things:
Find out what the MySQL error is, as already suggested
$result=mysql_query($sql) or die(mysql_error());
You need to sanitize everything that goes into the query. Although you sanitize $door and $postcode, you don't sanitize $_SESSION['ref']. You should and run it through mysql_real_escape_string(). I don't know what you are storing in it, but perhaps that's where the code is breaking because of unescaped characters?
In theory I guess $_SESSION is stored server side, but personally I still wouldn't trust it, and I'd escape everything that goes into a MySQL query.
I think answer lies in the curly braces:
$sql="SELECT * FROM $tbl_name WHERE door ='{$door}' AND postcode='{$postcode}' AND active = 'not_activated' AND ref = '". $_SESSION['ref']."'";
$result=mysql_query($sql);

PHP Ban Visitor & Insert into mySQL DB

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).

Categories