FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Checking if user exists, whats wrong?





ThePolemistis
heyy,,,
im new to PHP, but I have experience in MySQL, Java and Perl.

I am trouble over this code of mine:

Code:

     //check if username and password exists
   $sql = mysql_query("SELECT * FROM user WHERE username=$_POST['username']");
   $result = mysql_num_rows($sql);
   if($result==0){
          echo "Username already exists!";
          exit;
   }


Assume the tables are correct.

Does anyone know where I am going wrong??
ALostSoul
Code:

     //check if username and password exists
   $sql = mysql_query("SELECT * FROM user WHERE username=$_POST['username']");
   $result = mysql_num_rows($sql);
   if($result==0){
          echo "Username already exists!";
          exit;
   }


shouldn't it be
Code:


     //check if username and password exists
   $sql = mysql_query("SELECT * FROM user WHERE username=username");
   $result = mysql_num_rows($sql);
   if($result==1){
          echo "Username already exists!";
          exit;
   }
ThePolemistis
ALostSoul wrote:
Code:

     //check if username and password exists
   $sql = mysql_query("SELECT * FROM user WHERE username=$_POST['username']");
   $result = mysql_num_rows($sql);
   if($result==0){
          echo "Username already exists!";
          exit;
   }


shouldn't it be
Code:


     //check if username and password exists
   $sql = mysql_query("SELECT * FROM user WHERE username=username");
   $result = mysql_num_rows($sql);
   if($result==1){
          echo "Username already exists!";
          exit;
   }


okay... yea.... it should be $result ==1 or equally same $result > 0...

however, the problem i think is in the comparing of the textfield...

I have a textfield called username. How do I compare that fields value in php?
so like
Code:
$sql = mysql_query("SELECT * FROM user WHERE username=txtUsername");

where txtUsername is the textbox on the form

Anyone know???
Star Wars Fanatic
Code:
     //check if username and password exists
   $sql = mysql_query("SELECT * FROM user WHERE username=\"".$_POST['username']."\"");
   $result = mysql_num_rows($sql);
   if($result){
          echo "Username already exists!";
          exit;
   }


That should do it... You had it so that it was sending the text "$_POST['username']" in the query, instead of the value of the variable. To send the value of the variable, you have to end the string with the ", and then use a period followed by the variable name, followed by another period...

Instead of this...

Code:
"SELECT * FROM user WHERE username=$_POST['username']"


this must be used...

Code:
"SELECT * FROM user WHERE username=\"".$_POST['username']."\""
ncwdavid
Well first of all trying to put the information that was submitted by the unknown user straight into a query is very bad and leaves a great chance for hackers. You should first do this:

Code:

$username = $_POST['username'];
$username = addslashes($username);

That will add slashes to the start and the end of the username so there will be no sql injection. Then just do the query as normal and use "$username" instead of "$_POST['username']".

Goodluck.
Star Wars Fanatic
ncwdavid wrote:
Well first of all trying to put the information that was submitted by the unknown user straight into a query is very bad and leaves a great chance for hackers. You should first do this:

Code:

$username = $_POST['username'];
$username = addslashes($username);

That will add slashes to the start and the end of the username so there will be no sql injection. Then just do the query as normal and use "$username" instead of "$_POST['username']".

Goodluck.


That is true...

You can also do this...

Put this at the beginning of the file...

Code:
extract($_POST);


Then the $username will be the value that $_POST['username'] is, so you can run your

Code:
$username = addslashes($username);


You could do this, if you don't want to extract the Post data...

Code:
$username = addslashes($_POST['username']);
ThePolemistis
Thanks for the replies from all 3 of u... it workss!!!
Stubru Freak
Star Wars Fanatic wrote:
Code:
extract($_POST);


Never do that, it makes your site so easy to hack.
ThePolemistis
Stubru Freak wrote:
Star Wars Fanatic wrote:
Code:
extract($_POST);


Never do that, it makes your site so easy to hack.


Okay, can someone present to me the most secure method of which you know, on how to check if a username in the username field matches the one in the database?

Also, what do u mean easy to hack? Hack the database? or hack the php file responsible for sending the information to the database, or even hack the php which makes the connection to the database?

Thanks
Stubru Freak
ThePolemistis wrote:
Stubru Freak wrote:
Star Wars Fanatic wrote:
Code:
extract($_POST);


Never do that, it makes your site so easy to hack.


Okay, can someone present to me the most secure method of which you know, on how to check if a username in the username field matches the one in the database?


Basically, make sure to use $_POST['username'] instead of extract($_POST);. Also make sure to use addslashes (or, even better, mysql_real_escape_string, although in most cases addslashes will do). This is perfectly safe AFAIK:

Code:
$username = mysql_real_escape_string($_POST['username']);


After that you can just use $username in your SQL statement without worrying.

Quote:
Also, what do u mean easy to hack? Hack the database? or hack the php file responsible for sending the information to the database, or even hack the php which makes the connection to the database?

Thanks


Extract($_POST) and register_globals can do a lot of bad things, although you can prevent anything from happening by making sure to initialize variables.

I'll give an example of a hack here. (I think it's appropriate as every PHP programmer should know about this risk, and every hacker knows about this anyway, so even if this post educates one bad guy, it will educate two good guys so the internet will be a little better a place.) Say, you have a page like this:
This is intentionally unsafe code, DON'T USE.
Code:
<?php

extract($_POST);
extract($_SESSION);
// Or remove the two lines above and turn on register_globals, which
// basically executes the previous two lines before any actual code is
// executed, and also extracts $_GET, $_COOKIE and $_SERVER the
// same way.

if($username) {
  if(/* Do a mysql query for $username */){
    $_SESSION['logged_in'] = true;
    $logged_in = true;
  }
} else {
  // Show login form
}

if($logged_in){
  // Secret area
}

?>


This code will not work and I intentionally left away some parts to clarify the important parts.
In the default situation, both $_SESSION and $_POST will be empty at first. No variables will be exported. It will go to the else part, and display the login form.

Next, the login form will be submitted, and $_POST will be the following array:
Code:
username => 'what you filled in'

Also probably a password, but that's not the point right now.
After the export, the variables will look like this:
Code:
$username = 'what you filled in';

It will go to the elseif part, and if everything goes right, will set $_SESSION['logged_in'] to true. It also sets the $logged_in variable in the current script to true, so you can already see the secret area without having to reload the page.
If you don't know what the $_SESSION variable does: it basically persists on every page the user visits. If you want to use it, it's actually slightly more complicated than shown here. See the session_start function.

So when the user loads the next page, the $_POST variable will be empty, but now the $_SESSION variable looks like this:
Code:
logged_in => true

After exporting $_SESSION and $_POST, the variables will look like this:
Code:
$logged_in = true;

And the user will be allowed to access the secret area again. This is what happens when everything goes right.

But users can get access to the secret area without the right username. I'll show you how. First, the bad guy makes a local html page that looks like this:
Code:
<form method="post" action="YOUR WEBSITE">
<input type="text" name="logged_in" value="true">
<input type="submit" value="Log in">
</form>

When he submits that form, look at what POST data is sent:
Code:
logged_in=true

It will end up in the $_POST variable like this:
Code:
logged_in => true

And then be exported as a variable like this:
Code:
$logged_in = true;

The variables now look exactly the same as in the case someone actually logs in, and the user gets access to the secret part. This is called variable injection.

Please note that the $_SESSION variable used is just an example, and the same hack would be perfectly possible when the username and password are sent to every page visited. (Which, again, is a security risk as sensitive information shouldn't have to constantly cross the internet.)

How to prevent:
There are two ways:

1. Make sure to always initialize variables to a default value. You would put
Code:
$logged_in = false;

between the two extract functions, and the hack I described wouldn't be possible.

2. Never ever extract arrays if you aren't completely sure what they will contain. Never ever ever extract the $_POST, $_GET and $_COOKIE arrays under any circumstances. Also be sure to turn off, and leave off register_globals, which does this for you. If you're on frih.net, and you didn't turn it on in a .htaccess file, you're safe. Otherwise, look for information on how to turn it off in a .htaccess file. After that, refer to POST values as $_POST['name'] instead of $name and to session variables as $_SESSION['name'] instead of $name.

Try to use both ways. If you use the first one, you're almost sure to forget it sometimes, so the second way is more secure. But the first way can also help you to prevent a lot of different bugs.

Also, why to use addslashes or mysql_real_escape_string:

This is an example of a MySQL query:
Code:
SELECT * FROM users WHERE username = '$username' AND password = '$password'


When $username contains aName and password is abc123, this will be sent to the server as:
Code:
SELECT * FROM users WHERE username = 'aName' AND password = 'abc123'

This will work correctly.

However, if the user instead inputs this as a password:
Code:
' OR 1=1 OR 1 = '


The result will be this query to the database:
Code:
SELECT * FROM users WHERE username = 'aName' AND password = '' OR 1 = 1 OR 1 = ''


So the server will check if the password equals '', which it doesn't, but then it will check if 1 equals 1, which it does, so the server will let you in.

So always be sure to escape slashes, or even better, use one of the advanced database modules that do it for you.
Bejeweledhorses
usually i just use a database, it is easeir
qebab
Bejeweledhorses wrote:
usually i just use a database, it is easeir


Since when, my dear, is MySQL not database-related? You would do well to heed the guy, he seems competent and experienced with php. It's always better to be overcautious with scripts you write for the internet. He talked about variable injection, which has a counterpart called SQL injection. If you use any common database, these are things you should read carefully.
Related topics
whats wrong with my database
911
Frihost whats wrong,i can'tsendprivate messages
Are they FAKE
If you don't believe God exists
Second FTP account [Resolved]
Login without server scripting
Help!!! My DirectAdmin isn't working!!!
Should I make a flash site?
[Community Project] Easy Simple Content Management System
Problem connecting to MySQL database with PHP [RESOLVED]
Don't know what's wrong
The Sun God, anyone?
whats wrong with this php script?
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.