Shinyshell Community Forums > Coding >
Peter's Adventures in MySQL


[1]


July 04 02009, 22:22 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

I've been wanting to implement a new system on my site with MySQL lately. I've tried and failed at this twice. I started messing with MySQL + phpMyAdmin today. I found it to be far easier. I simply got bored coding it by hand.

My point is this. If I'm putting info into my table via a form, does mysql_real_escape_string() really do the trick? Honestly? It seems too easy.

July 05 02009, 04:06 GMT
Nick^
merciful justice

Nick's avatar
Location: Brisbane, Australia
Post count: 78
au
Yeah. You should also be htmlspecialchars()-ing data that you want to retrieve from tables to display on your site.
______________________________
Lazurane

July 05 02009, 04:21 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

What is the purpose of that? (Not trying to sound rude, I just want to know ;D)

July 05 02009, 04:43 GMT
Pikachu
Kelp is good!

Pikachu's avatar
Location: California
Post count: 50
us
It translates something like this:

<a href="linky">link</a>


to this:

&lt;a href=&quot;linky&quot;&gt;link&lt;/a&gt;


The first entry, without htmlspecialchars(), will enter into the table and when it is called, a link is displayed. The second entry, with htmlspecialchars(), will submitted as the first entry but is translated into the second entry. When called for, you get the second entry. It's a toned-down version of htmlentities().
______________________________

Linux | Chrome | Python | Chuck

July 05 02009, 05:22 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

So basically it won't screw with the PHP... but will it still appear, upon inclusion or echoing, as a link?

EDIT: Basically, I'm trying to code a login system. It's confusing me, though, because it doesn't run right. My coding is sloppy. XD

I'll copy the code.

 $user = $_REQUEST['user'];
 $password = $_REQUEST['password'];
 $user = mysql_real_escape_string($user);
 $password = mysql_real_escape_string($password);
 
 checkDatabase();
 
 $result = mysql_query("SELECT * FROM users
 WHERE name='Peter' and type='admin'") or die(mysql_error());
 
 if(!$result)
 {
 echo "crap.";
 }
 
$user = $_REQUEST['user'];
$password = $_REQUEST['password'];
$user = mysql_real_escape_string($user);
$password = mysql_real_escape_string($password);

checkDatabase();

$result = mysql_query("SELECT * FROM users
WHERE name='Peter' and type='admin'") or die(mysql_error());

if(!$result)
{
echo "crap.";
}
]]>


In this database, Peter is not a real user. I'm just not sure how to know when the query returns false! Grr.

July 05 02009, 06:23 GMT
Pikachu
Kelp is good!

Pikachu's avatar
Location: California
Post count: 50
us
Nope, it will appear like this: &lt;a href=&quot;linky&quot;&gt;link&lt;/a&gt;.

There shouldn't be a need to escape the username and password since you are checking them with the table, not inserting them.

This is what I use:
 <?php
 $username = $_POST['username']; //from an different page
 $password = $_POST['password']; //from an different page
 
 $sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
 $result = mysql_query($sql);
 $count = mysql_num_rows($result);
 
 if($count==1){
 echo "Success";
 }
 else
 {
 echo "Wrong!";
 }
 ?>
<?php
$username = $_POST['username']; //from an different page
$password = $_POST['password']; //from an different page

$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);

if($count==1){
echo "Success";
}
else
{
echo "Wrong!";
}
?>]]>

______________________________

Linux | Chrome | Python | Chuck

July 05 02009, 12:11 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173

Basically, you need to put any user-submitted data that you are printing through htmlspecialchars(), or they can include HTML in their posts which could break your site (or worse, if they know what they're doing).

As for mysql_real_escape_string(), it puts little backslashes before any quote symbols the user submits, therefore it stops people from potentially damaging your database. It's very important to perform mysql_real_escape_string() on any user-submitted data that's being used in SQL statements, even usernames.

The code appearing in previous posts is vulnerable to SQL injection, which is a security problem that lets users run any SQL statement they want on your database.

<?php 
$username = $_POST['username']; //from an different page
$password = $_POST['password']; //from an different page

# Oh-oh!!
$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);

if($count==1) { echo "Success"; }
else { echo "Wrong!"; }
?>
<?php
$username = $_POST['username']; //from an different page
$password = $_POST['password']; //from an different page

# Oh-oh!!
$sql = "SELECT * FROM users WHERE username='$username' and password='$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);

if($count==1) { echo "Success"; }
else { echo "Wrong!"; }
?>
]]>


For example, if someone entered their username as

Michael'--


That would allow them to be logged in without checking for a password. Worse yet,

Michael'; DROP TABLE users; --


Which would delete your users table! The correct code is this:

<?php 
$username = $_POST['username']; //from an different page
$password = $_POST['password']; //from an different page

# Oh-oh!!
$sql = "SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "' and password='" . mysql_real_escape_string($password) . "'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);

if($count==1) { echo "Success"; }
else { echo "Wrong!"; }
?>
<?php
$username = $_POST['username']; //from an different page
$password = $_POST['password']; //from an different page

# Oh-oh!!
$sql = "SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "' and password='" . mysql_real_escape_string($password) . "'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);

if($count==1) { echo "Success"; }
else { echo "Wrong!"; }
?>
]]>

July 05 02009, 22:33 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

But doesn't this:


<?php
$user = $_REQUEST;
$password = $_REQUEST;
$user = mysql_real_escape_string($user);
$password = mysql_real_escape_string($password);
?>


do the trick?


So basically, to make my login thing...


<?php
$user = $_REQUEST;
$password = $_REQUEST;
$user = mysql_real_escape_string($user);
$password = mysql_real_escape_string($password);


$query = "SELECT * FROM users WHERE username='" . $username . "' and password='" . $password . "';
$result = mysql_query($query);
$count = mysql_num_rows($result);

if($count == 1)
{
echo "Correct!";
}

else
{
echo "Darn. WRONG.";
}
?>

July 05 02009, 23:12 GMT
Nick^
merciful justice

Nick's avatar
Location: Brisbane, Australia
Post count: 78
au
Yeah. It does the trick. You can even do it easier/quicker/whatever, lawl.
______________________________
Lazurane

July 06 02009, 02:31 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173

Actually, the reason why I put it into the statement is because mysql_real_escape_string() takes a second parameter: the connection string (only it's optional).

Optimally, if you connected to the database like this:

<?php  
$conn = mysql_connect("localhost", "user", "pass");
?>
$conn = mysql_connect("localhost", "user", "pass");
?>]]>


you'd call the function like this:

<?php 
mysql_real_escape_string($username, $conn);
?>
mysql_real_escape_string($username, $conn);
?>]]>

And then you need it in a place where you can pass the connection identifier to the function.

Of course you don't have to do that. Since you haven't assigned a connection variable (and you're only going to be connecting to one database) what you're doing is fine.

July 06 02009, 02:39 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Now, if I want to create a session and check it, would this stuff work?

 <?php
 $user = $_REQUEST['user'];
 $password = $_REQUEST['password'];
 mysql_real_escape_string($user);
 mysql_real_escape_string($password);
 
 
 checkDatabase();
 
 $query = "SELECT * FROM users WHERE name='" . $user . "' and password='" . $password . "'";
 $result = mysql_query($query) or die(mysql_error());
 $count = mysql_num_rows($result);
 
 if($count == 1)
 {
 session_start();
 $_SESSION['bowchika'] = 1;
 echo "Success! You've been logged in!";
 }
 
 else
 {
 echo "Darn, the user and password combination you defined do not match or do not exist. Please try again or register.";
 }
 ?>
 
<?php
$user = $_REQUEST['user'];
$password = $_REQUEST['password'];
mysql_real_escape_string($user);
mysql_real_escape_string($password);


checkDatabase();

$query = "SELECT * FROM users WHERE name='" . $user . "' and password='" . $password . "'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);

if($count == 1)
{
session_start();
$_SESSION['bowchika'] = 1;
echo "Success! You've been logged in!";
}

else
{
echo "Darn, the user and password combination you defined do not match or do not exist. Please try again or register.";
}
?>
]]>


 function userCheck()
 {
 if($_SESSION['bowchika'] == 1)
 {
 echo "You're logged in!";
 }
 
 else
 {
 echo "You could log in!";
 }
 
 }
 
function userCheck()
{
if($_SESSION['bowchika'] == 1)
{
echo "You're logged in!";
}

else
{
echo "You could log in!";
}

}
]]>


Oh wait, never mind. ;D

Should I submit the form to a separate page? Because it seems that when I submit it to this one, it doesn't recognize (from userCheck()) that it is logged in until I go to another page. =/

July 06 02009, 22:29 GMT
Pikachu
Kelp is good!

Pikachu's avatar
Location: California
Post count: 50
us
Well, I think using cookies is much better than sessions, just because sessions don't seem to work for me.

It shouldn't really matter whether you submit the form on a different page or not.
______________________________

Linux | Chrome | Python | Chuck

July 07 02009, 00:04 GMT
Nick^
merciful justice

Nick's avatar
Location: Brisbane, Australia
Post count: 78
au
+1, cookies are much better than sessions.

Sorry, I didn't see those posts about the necessity of mysql_escaping strings.

However, you can probably your code a little more light-weight and easier to read, like in the code below (also, as I explained to Pika, use the (code=php) bbcode tag to get syntax highlighting - just replace the brackets with square ones ('['). Another thing you might like to note is that you should be using the POST method for some of your forms, especially forms where sensitive data is supposed to be entered, hence why I've changed the $_REQUEST to $_POST. Also, $_REQUEST checks (I think) $_GET data AND $_COOKIE, meaning that it could stuff up, so unless you want to check both, stick with $_POST, $_GET or $_COOKIE. FINALLY, you should ALWAYS ENCRYPT PASSWORDS. You can do this by using the md5() function on you password string, as I have done in the code below.

<?php 
//Escape Username $_POST string
$user = mysql_real_escape_string($_POST['user']);
//Escape and md5 encrypt Password $_POST string
$password = md5(mysql_real_escape_string($_POST['password']));

checkDatabase();

//Write Query
$query_string = "SELECT *
FROM users
WHERE name = ". $user ."
AND password = ". $password

//Count Results
$count = mysql_num_rows(mysql_query($query_string) or die(mysql_error()));

if($count == 1)
{
session_start();
$_SESSION['bowchika'] = 1;
echo "Success! You've been logged in!";
}

else
{
echo "Darn, the user and password combination you defined do not match or do not exist. Please try again or register.";
}
?>
<?php
//Escape Username $_POST string
$user = mysql_real_escape_string($_POST['user']);
//Escape and md5 encrypt Password $_POST string
$password = md5(mysql_real_escape_string($_POST['password']));

checkDatabase();

//Write Query
$query_string = "SELECT *
FROM users
WHERE name = ". $user ."
AND password = ". $password

//Count Results
$count = mysql_num_rows(mysql_query($query_string) or die(mysql_error()));

if($count == 1)
{
session_start();
$_SESSION['bowchika'] = 1;
echo "Success! You've been logged in!";
}

else
{
echo "Darn, the user and password combination you defined do not match or do not exist. Please try again or register.";
}
?>
]]>


Hopefully this helps.
______________________________
Lazurane

July 10 02009, 05:42 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Now I need to know that/if my user login page is secure. I don't want it to get hacked XD

My functions page:
<?php 
session_start();
// Page Include
function pageInclude()
{

$page = $_GET['id'];
if(!isset($page))
{
$file = "main.php";
}

elseif(!file_exists($page . ".php"))
{
$file = "404.php";
}

else
{
$file = $page . ".php";
}

include($file);
}


//Database Connect
function checkDatabase(){
mysql_connect("myhost", "myusername", "mypassword") or die(mysql_error());

mysql_select_db("mydatabasename") or die(mysql_error());

}


//Check User
function userCheck()
{
if($_SESSION['bowchika'] == 1)
{
echo "<strong>You're logged in,</strong> " . $_SESSION['bowchow'] . "! [<a href=\"?id=usercp\">User CP</a> . ";
if($_SESSION['dfusergroup'] == "admin")
{
echo "<a href=\"?id=admincp\">Admin CP</a> . ";
}
echo "<a href=\"?id=logout\">Log Out</a>]";
}

else
{
echo "<strong>Hello,</strong> Visitor! [<a href=\"?id=login\">Login</a> . <a href=\"?id=register\">Register</a>]";
}

}

//Login User
function login()
{
$user = $_POST['user'];
$password = $_POST['password'];
mysql_real_escape_string($user);
mysql_real_escape_string($password);

$query = "SELECT * FROM users WHERE user='" . $user . "' and password='" . $password . "'";
$query2 = "SELECT usergroup FROM users WHERE user='" . $user . "' and password='" . $password . "'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);

if($count == 1)
{
$result2 = mysql_query($query2) or die(mysql_error());
$hereWeGo = mysql_fetch_array($result2);
$_SESSION['dfusergroup'] = $hereWeGo['usergroup'];
$_SESSION['bowchow'] = $user;
$_SESSION['bowchika'] = 1;
echo "Success! You've been logged in! Click <a href=\"?id=main\">here</a> to go home.";
}

elseif($count != 1)
{
echo "Darn, the user and password combination you defined do not match or do not exist. Please try again or register.";
}
}

function logout()
{
session_destroy();
}
?>
<?php
session_start();
// Page Include
function pageInclude()
{

$page = $_GET['id'];
if(!isset($page))
{
$file = "main.php";
}

elseif(!file_exists($page . ".php"))
{
$file = "404.php";
}

else
{
$file = $page . ".php";
}

include($file);
}


//Database Connect
function checkDatabase(){
mysql_connect("myhost", "myusername", "mypassword") or die(mysql_error());

mysql_select_db("mydatabasename") or die(mysql_error());

}


//Check User
function userCheck()
{
if($_SESSION['bowchika'] == 1)
{
echo "<strong>You're logged in,</strong> " . $_SESSION['bowchow'] . "! [<a href=\"?id=usercp\">User CP</a> . ";
if($_SESSION['dfusergroup'] == "admin")
{
echo "<a href=\"?id=admincp\">Admin CP</a> . ";
}
echo "<a href=\"?id=logout\">Log Out</a>]";
}

else
{
echo "<strong>Hello,</strong> Visitor! [<a href=\"?id=login\">Login</a> . <a href=\"?id=register\">Register</a>]";
}

}

//Login User
function login()
{
$user = $_POST['user'];
$password = $_POST['password'];
mysql_real_escape_string($user);
mysql_real_escape_string($password);

$query = "SELECT * FROM users WHERE user='" . $user . "' and password='" . $password . "'";
$query2 = "SELECT usergroup FROM users WHERE user='" . $user . "' and password='" . $password . "'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);

if($count == 1)
{
$result2 = mysql_query($query2) or die(mysql_error());
$hereWeGo = mysql_fetch_array($result2);
$_SESSION['dfusergroup'] = $hereWeGo['usergroup'];
$_SESSION['bowchow'] = $user;
$_SESSION['bowchika'] = 1;
echo "Success! You've been logged in! Click <a href=\"?id=main\">here</a> to go home.";
}

elseif($count != 1)
{
echo "Darn, the user and password combination you defined do not match or do not exist. Please try again or register.";
}
}

function logout()
{
session_destroy();
}
?>
]]>


Login page/form
<form action="?id=usercheck" method="post"> 
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="user" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>

<form action="?id=usercheck" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="user" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
]]>


EDIT: And will this work for registration? I'm not sure about this query...

function register() 
{
$query = "INSERT INTO users (user, password, usergroup, email, regdate)
values('".$_POST['user']."', '".$_POST['password']."', 'user', '".$_POST['email']."', CURDATE()";
}
function register()
{
$query = "INSERT INTO users (user, password, usergroup, email, regdate)
values('".$_POST['user']."', '".$_POST['password']."', 'user', '".$_POST['email']."', CURDATE()";
}
]]>


[1]



Forum Information
  Currently Active Members [detailed] (0 members and ? guests)
-
Forum Statistics
Topics: 0, Posts: 0, Members: 108.
Welcome to our newest member, adamthephantump
Most members online was 5, on August 28 2009, at 21:49:28.
Legend
    Forums with unread topics in them are indicated by a strong yellow colouring around the forum icon.
    Forums with no unread topics have the standard pale yellow colouring around the forum icon.
    Forums with a blue arrow icon will redirect you to a non-forum page.
    Locked forums have a little padlock by their icon. You won't be able to post in these forums.
Shinyshell Home | Contact | Staff List | Archive | Top 

Conventional Login

Don't have an account? You may want to create one.

OpenID Login
OpenID login and registration is usable, but not finished.
What is OpenID?
Search

(advanced search)
Site Stats
  Total members: 108
  Latest member: adamthephantump
  Members currently online: 0
  Most online: 5 - Aug 28, 2009 (21:49)
  Front page hits: 88112
Developer info
  Site version: 3.5 Alpha
  16 queries - 9 templates
Under the Spotlight
Collide Site
Collide make fabulously dreamy electronic-industrial music, they're one of my favourite bands! Give them a chance to take control of your life - myspace | youtube - "Euphoria".

Collide Site - Hits: 4924

5/5 (2) | Rate this site?