PHP If Statements With mySQL Results - php

The code below is supposed to check if there is a person in the database with a row in the database with the username it gets from the cookie login.And if there is it is supposed to include a page and if there isn't a person in the database with this user_id it is supposed to echo.Here is my code so far please tell me how I would do this.I also already know before someone tells me that mySQL statements like I have it are becoming depreciated.Here is My code:
<?php
include("dbconnect.php");
mysql_select_db("maxgee_close2");
$username = $_COOKIE['maxgee_me_user'];
$result = mysql_query("select user_id from users where username = '$username'");
$row = mysql_fetch_array($result);
mysql_free_result($result);
$check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row['user_id']'") or die(mysql_error());
if(1==1){
if (mysql_num_rows($check)>0)
{
include("example.php");
}
else
{
echo "example";
}
}
?>

In the double-quoted string, your array variable $row['user_id'] is being incorrectly parsed due to the fact that you have quoted the array key without surrounding the whole thing in {}. It is permissible to omit the {} in a double-quoted string if you don't quote the array key, but the {} adds readability.
check = mysql_query("SELECT * FROM events_main WHERE user_id ='{$row['user_id']}'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
// Also acceptable, but not as tidy, and troublesome with multidimensional
// or variable keys - unquoted array key
check = mysql_query("SELECT * FROM events_main WHERE user_id ='$row[user_id]'") or die(mysql_error());
//-------------------------------------------------------------^^^^^^^^^^^^^^^^^^
As mentioned above, $_COOKIE is never considered a safe value. You must escape its values against SQL injection if you continue to use the old mysql_*() API:
$username = mysql_real_escape_string($_COOKIE['maxgee_me_user']);

2 Things right off the bat, like Waleed said you're open to SQL injection, not very nice thing to have happen to you. I would look into reading tutorials about MySQLi and PDOs, from there try and dive into a better way or running queries.
Also you are choosing to use cookies instead of sessions to store the username? Cookies can be modified client-side to say anything a smart user with firebug would want them to be. Sessions are stored server-side and the client (end-user) is only given an id of the session. They cannot modify the username if you send it as a session. (They could try and change the session id to another random bunch of numbers but thats like pissing into the wind, pardon my french.
Heres some pseduo code that will get you on your way I think
<?php
include("dbconnect.php");
$database = "maxgee_close2"; //Set the database you want to connect to
mysql_select_db($database); //Select database
$username = $_SESSION['maxgee_me_user']; //Grab the username from a server-side stored session, not a cookie!
$query = "SELECT user_id FROM `users` WHERE `username` = '" . mysql_real_escape_string($username) . "' LIMIT 1"; //Note the user of mysql_real_escape_string on the $username, we want to clean the variable of anything that could harm the database.
$result = mysql_query($query);
if ($row = mysql_fetch_array($result)) {
//Query was ran and returned a result, grab the ID
$userId = $row["user_id"];
mysql_free_result($result); //We can free the result now after we have grabbed everything we need
$query_check = "SELECT * FROM `events_main` WHERE `user_id` = '" . mysql_real_escape_string($userId) . "'";
$check = mysql_query($query_check);
if (mysql_num_rows($check)>0) {
include("example.php");
}
else {
echo "example";
}
}
?>
That code may/may not work but the real key change is that fact that you were running
mysql_free_result($result);
before your script had a chance to grab the user id from the database.
All in all, I would really go back and read some more tutorials.

Related

How do I get the user ID of a user from their username via sessions in php?

I have to get the user ID from the database, but the only session information I can get from the login page is the username and the password. I am able to get the username, but when I try to run a query to get the id using that info, it returns nothing. Here is the code:
$_SESSION['username'] = $username;
$connect = mysqli_connect("xxxx","xxxx","xxxx", "xxxx");
$IDquery = "SELECT UserID FROM User WHERE Username = ".$username.";";
$result = $connect->query("SELECT UserID FROM User WHERE Username = '$username';");
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$user_id = $row["UserID"];
$_SESSION["UserID"] = $user_id;
}
How can I get the user ID if I only have the username?
I do suspect that this:
$_SESSION['username'] = $username;
Should actually be:
$username = $_SESSION['username'];
That is: you want to retrieve the username from the session rather than setting the session variable.
Side note: you should really use parameterized queries rather than mungling variables into the query string. This is more efficient, and safer, as it prevents you from SQL injection. You can have a look at this famous SO post for the whys and hows.
It looks like the issue is how you are trying to use the $username variable into the query (you should also, as mentioned before, use parameterized queries).
First of all, make sure that before sending the $username you know what's is inside it.
try for example:
var_dump($_SESSION['username']);
Put it before you execute the query.
Sometimes it helps to remove variables from the middle if not sure how it is being assigned:
$IDquery = "SELECT UserID FROM User WHERE Username = ".$_SESSION['username'].";";
Also, you want to be sure that the session is filled with the information you are going to use at the same time the user is authenticated. that should remove queries in the middle of the session.

PHP select logged in user, not working

I can't get the logged in user in the code, can you please help me to figure it out:
the code which is not working:
$result = mysql_query("SELECT * FROM clients WHERE user = '$_SESSION['user']['username']'")
or die(mysql_error());
but it is working for showing it thought, in here:
echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
thanks in advance for any help.
There are two solutions to this. The first is to define a new variable to contain the $_SESSION['user']['username'] value and the second is to enclose $_SESSION['user']['username'] in curly braces (see: Strings - variable parsing for more information).
Solution 1
$username = $_SESSION['user']['username'];
mysql_query("SELECT * FROM clients WHERE user = '$username'")
or die(mysql_error());
Solution 2
mysql_query("SELECT * FROM clients WHERE user = '{$_SESSION['user']['username']}'")
or die(mysql_error());
In addition to this, if one is only accessing the top-level of the array (e.g. $_SESSION['username'] rather than $_SESSION['user']['username']) one can simply remove the quotes around the key name:
mysql_query("SELECT * FROM clients WHERE user = '$_SESSION[username]'")
or die(mysql_error());
However, it should be worth pointing out that mysql functions are deprecated and that your code is vulnerable to SQL injection. You should look into using PDO or mysqli prepared statements.
You can try this, please avoid using mysql functions anymore, and this not a hackproof code. Pleae make it
$user = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
mysql_query("SELECT * FROM clients WHERE user = '".$user."'")
or die(mysql_error());

Query producing unexpected results (sha1)

I have a form for updating user data. It posts to this page:
<?php
//Update user table
session_start();
include 'sql_connect_R.inc.php';
$id = mysql_real_escape_string($_POST['userID']);
$password = mysql_real_escape_string($_POST['user_passwrd']);
$salt = time();
$hash = sha1($password . $salt);
mysql_query("UPDATE users SET user_passwrd = '$hash', stamp = '$salt', pending = 'yes'
WHERE userID = '$id'");
mysql_close($con);
?>
(I have edited out the things not pertinent to this question)
I believe what is happening is when the 'stamp' field is being populated with the $salt it is getting a different value than when the $hash is being calculated. Therefore, when a user signs in and is checked here:
$qry="SELECT * FROM users WHERE userlogin = '$login' AND user_passwrd = sha1(CONCAT('$password', stamp))";
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$num = mysql_num_rows($result);
When I echo $num it returns a value of 0.
I'm wondering if there is a way to ensure that the value of $salt remains the same when it is being used in $hash and then when it is updating the field 'stamp'.
Can anyone help me with this or point me in the right direction? Thanks in advance.
Cheers
More ideas so I've changed my comment into an answer...
It's worth noting that you're using PHP's SHA1 function when storing but mysql's when retrieving. They should be the same but that's the first place I'd look to debug this. try using mysql's sha function to store the hash or retrieve the record based on login, read the salt and hash it in PHP to compare
How are you storing the timestamp? Is it possible that it's being transformed/rounded/clipped/treated as a date string in some way? Just for a sanity check, take the string you're feeding into the sha1 function in both steps and check they're identical.
Further to your comment, can you post the schema for the relevant fields in the table?
Thank you for all comments. I want to report that I've 'solved' the problem. I had made a change in the name of the password input field late one night and neglected to change the $_POST value. What this did, of course, was not supply the $password value to the $hash. Though I'm embarrassed about this, I think it is important for me to share my oversight to exemplify how important it is to check ALL places where errors can occur. I failed to double-check everything and made incorrect assumptions about the nature of the problem. The code worked fine, it was the loose screw in front of the keyboard that caused the problems. Cheers
You're doing your queries incorrectly. You need to concatenate the variables in the string and NOT use single quotes. Use the quote to the left of your 1 key ``. This is the way that most MySQL read queries. example:
<?php
//Update user table
session_start();
include 'sql_connect_R.inc.php';
$id = mysql_real_escape_string($_POST['userID']);
$password = mysql_real_escape_string($_POST['user_passwrd']);
$salt = time();
$hash = sha1($password . $salt);
mysql_query("UPDATE `users` SET `user_passwrd` = '".$hash."', `stamp` = '".$salt."', `pending` = 'yes' WHERE `userID` = '".$id."'");
mysql_close($con);
?>
$qry="SELECT * FROM `users` WHERE `userlogin` = '".$login."' AND `user_passwrd` = '".sha1(CONCAT($password, stamp))".'";
$result=mysql_query($qry);
$row = mysql_fetch_assoc($result);
$num = mysql_num_rows($result);
This little change should help. Sometimes the db can be a little touchy. I hope this helps.

Display usernames at random

I’m trying to create a script for a user to enter in their username, and then have other logged in usernames randomly show, in a chatroulette fashion.
So, you will enter in your name and hit submit, then your name will be stored in a database and someone else’s name will be pulled out at random and shown. Then the user can hit a next button to see another random user name. When the user closes the page, their name will be unloaded from the system.
What I have tried is creating a simple post submission form which will return you to the same page logged in with your name, and it inserts your name into a mysql database. That worked.
Then I added some PHP code to detect that the name variable has been set and to find a random username in the database by finding the amount of users in the database and using a random integer to pick one out. I’m pretty sure it worked, however I was unable to get the user name to show with echo "$name";.
Then I tried adding an automatic logout by using:
<body onUnload=<?php session_destroy();?>>
That didn’t work. I didn’t get around to creating a next button because I was having a few problems, because I figured out that the logout wouldn’t work because I would be dropping rows from the database that wouldn’t be filled in again as new rows were added to the SQL database with an auto increment function causing blank pages to be shown.
Here is my code:
<html>
<head>
<title>random name</title>
</head>
<body>
<center>
<h1>random name</h1>
<h5>By DingleNutZ</h5>
</center>
<?php
if (!isset($_POST['name'])){
echo "<form action=\"index.php\" method=\"POST\" name=\"form\"><center><h4>name:</h4><input name=\"name\" id=\"name\" type=\"text\"/><br/>
<input type=\"submit\" name=\"submit\" value=\"Play!\"/></center></form>";
}else{
$name = $_POST['name'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="ftr"; // Database name
$tbl_name="players"; // 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");
// To protect MySQL injection (more detail about MySQL injection)
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
session_register("name");
session_start();
if(session_is_registered(name)){
$players=mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand=rand(1,$players);
$callee=mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
echo "Logout";
if (isset($playing)){
if ($playing == 1){
$drop_name=mysql_query("DELETE FROM $tbl_name WHERE name=$name");
}}
}
}
echo "show random name here";
}
?>
</body>
</html>
There is a variable in there called $playing which was an attempt at a logout system.
I would be very grateful for any answers. Many thanks in advance.
as i didnt make it obvious (sorry guys) i need to fix my main problem which is being able to show a random user without ever showing a blank page due to the rows being dropped from the database. it is essential that usernames are removed from the system for privacy
You have a few issues in your code, not all are errors as such, some code is unneeded, other code is potentially dangerous.
$name = stripslashes($name); <<-- delete this line.
$name = mysql_real_escape_string($name); <<-- this is all you need.
mysql_real_escape_string() is all you need. No other escaping is need to protect against SQL-injection.
A few caveats apply, which I will discuss below.
$sql="SELECT * FROM $tbl_name WHERE name='$name'";
$result=mysql_query($sql);
Select * is an anti-pattern, never use it in production code. Explicitly select the fields you need.
You are using dynamic tablenames, I fail to see the need for this and it's also a dangerous SQL-injection hole.
Never use it but if you must, see this question how to secure your code: How to prevent SQL injection with dynamic tablenames?
You do the query, but you don't test if it succeeds, put a test in there:
$sql = "SELECT id FROM users WHERE name='$name' ";
$result = mysql_query($sql);
if ($result)
{
$row = mysql_fetch_array($result);
$user_id = $row['id'];
}
else { do stuff to handle failure }
You are trying to get data out of the database, but this is not the way to do it:
$players = mysql_query("SELECT MAX (id) FROM $tbl_name");
$chooserand = rand(1,$players);
$callee = mysql_query("SELECT name FROM $tbl_name WHERE id=$chooserand");
echo "$callee";
But I see a few issues:
Please stop using dyname tablenames, it is a really bad idea.
The return value of mysql_query is a query_handle, not the actual data you're quering.
I would suggest escaping all values, whether from outside or inside your code; I know this is paranoid, but that way, if you code design changes, you cannot forget to put the escaping in.
Never ever ever echo unsanitized data in an echo statement.
If you echo a $var, always sanitize it using htmlentities. If you don't XSS security holes will be your fate.
See: What are the best practices for avoiding xss attacks in a PHP site
rewrite the code to:
$result = mysql_query("SELECT MAX (id) as player_id FROM users");
$row = mysql_fetch_array($result);
$max_player = $row['player_id'];
$chooserand = mysql_real_escape_string(rand(1,$max_player));
//not needed here, but if you change the code, the escaping will already be there.
//this also makes code review trivial for people who are not hep to SQL-injection.
$result = mysql_query("SELECT name FROM users WHERE id = '$chooserand' ");
$row = mysql_fetch_array($result);
$callee = $row['name'];
echo "callee is ".htmlentities($callee);
Finally you are deleting rows from a table, this looks like a very strange thing to do, but it is possible, however your code does not work:
$drop_name = mysql_query("DELETE FROM $tbl_name WHERE name=$name");
As discussed mysql_query does not return values.
On top of that only a SELECT query returns a resultset, a DELETE just returns success or failure.
All $vars must be quoted, this is a syntax error at best and an SQL-injection hole at worst.
Technically integers don't have to be, but I insist on quoting and escaping them anyway, because it makes your code consistent and thus much easier to check for correctness and it elimiates the chance of making errors when changing code
Rewrite the code to:
$drop_name = $name;
$result = mysql_query("DELETE FROM users WHERE id = '$user_id' ");
//user_id (see above) is unique, username might not be.
//better to use unique id's when deleting.
$deleted_row_count = mysql_affected_rows($result);
if ($deleted_row_count == 0)
{
echo "no user deleted";
} else {
echo "user: ".htmlentities($drop_name)." has been deleted";
}

Use PHP to link to user profile

I want my php query to display the user name with a link to the user profile.
<?php
$get_items = "SELECT * FROM items WHERE category='test'";
$result = mysql_query($get_items);
while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
$creator = $item['created_by'];
echo "<b>Seller: </b>"."<a href='userprof.php?id=$creator'>$creator</a>";
}
?>
Clicking on this link takes it to a user profile page that I created. But I want "userprof.php?id=$creator" to know which user to display the account information. Is this the best way to do this? How can I read the url and display the correct information?
<?php
$userId = $_GET['id'];
$sql = "SELECT * FROM user WHERE id = " . intval($userId);
$result = mysql_query($sql);
...
You are sending a GET variable.
$id = $_GET['id']; // Contains whatever was in $creator;
use $_GET for getting the variable from the URL.
like in your code you want to access the user profile then get the user id from url
like
http://localhost/test/user_profile.php?uid=2
here in the url uid is 2 thet is your userid.
you can get this id by using the code
$user_id = $_GET['uid'];
use this variable in your query.
OMG!! HORRIBLE PHP ABOUNDS! IT HURTS MY EYES!!
These people, none of them did both of the correct things:
ALWAYS FILTER USER INPUT!!
NEVER TRUST PHP ESCAPE FUNCTIONS, ESP NOT intval() and addslashes()!!
EVEN mysql_real_escape_string() HAS VULNERABILITIES AND SHOULD NEVER BE USED.
You should used prepared statements for everything in 2010.
Here it is the proper way:
<?php
if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
trigger_error('Invalid User ID. It must be an integer (number).', PHP_USER_ERROR);
exit;
}
$userId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT * FROM user WHERE id = ?";
$pdo = new PDO('mysql:host=localhost;db=mydb', $dbUsername, $dbPassWord);
$statement = $pdo->prepare($sql);
$statement->execute(array($userId));
$result = $statement->fetch(PDO::FETCH_ASSOC);
That is 100% secure. I hope people neither vote me down nor tone down my answer. Bad code is so systemic, we just have to shout from the rooftops until the new guys start learning it correctly, otherwise PHP as a professional language is seriously harmed.

Categories