Click to See Complete Forum and Search --> : PHP Encryption


tinernet
10-21-2003, 03:15 PM
im usin a MySQL db to store usernames and passwords. i need the passwords to be encryted in the database so i cant see peoples personal details. however, i then need the passwords to be decoded again so that the versoin that is typed in when logging in is the same as the version in the database. the password encode function in the PHPMyAdmin thing im usin is only one way; it encodes them but then dusnt decode them. ne ideas/scripts/miracles?!

eomer
10-21-2003, 03:39 PM
Most likely it is using the md5() function which is as you have said is a one way hash.
There are multiple ways to do this, but probably the easiest to use the password() function under mysql. In other words it would be in your sql function. It would look something like insert into users_tbl (fname, lname, email, passwd) values ('Eomer', 'of Rohan', 'eomer@rohan.net', password('letmein'));

The function will then encode the password. Now it's not a lot, however it does discourage most hackers. There are a multiple array of functions that can work under PHP in the manual as well. I have never tried these I usually use md5 by md5ing whatever they enter into the password field, and then comparing the md5 strings. The link is: http://www.php.net/manual/en/ref.mcrypt.php
. Like I said never used these functions, but if the first doesn't help these might.

P.S. no that's not my email address :D

tinernet
10-21-2003, 04:29 PM
so would that encrypted password be decrypted again when the script that checks the username and password against the mysql db cos thats whats stoppin the password function in PHPMyAdmin workin.
thanks a lot:D

eomer
10-21-2003, 04:35 PM
If you are using the password() function under mysql yes it will be decrypted.
If you are using the md5() function (under php or mysql) then no. What will happen is that the username and/or password you enter into the login will then be encrypted to md5. If the two md5 strings match then it will let you in.

Which usernames/passwords are you talking about? Ones you created? or the ones for MySQL?
First, then you can change it. For the second I believe if I remember correctly uses the password() function already (a mysql thing). At any rate I know that mysql encrypts part of that data. It encrypts the password under a default mysql installation.

Jona
10-21-2003, 04:38 PM
Why not encrypt the password the user entered in the form, and check if it matches what's in the database?

[J]ona

eomer
10-21-2003, 04:48 PM
What will happen is that the username and/or password you enter into the login will then be encrypted to md5. If the two md5 strings match then it will let you in.
One step ahead of you :D. j/k. Same thing...just said really differently. One thing I have to correct myself on though the mysql user table is a one-way hash if those or the usernames and passwords you are refering to. I believe you can use the password() function to compare them in a sql statement. Jona put that a lot better then I did.

tinernet
10-22-2003, 03:58 PM
zoom zoom zoom (thats all this goin over my head!). im a total retard so can u post sum code? iv tried various things to no avail. iv tried puttin the password variable as password($_POST['pword']); and then leavin that as it was and usin password($pword) in the UPDATE query. iv dun the same with md5 and had no luck. ne ideas?
thanks a lot guys

Jona
10-22-2003, 04:05 PM
$username = $_POST["username"]; # assuming the field is named username
$password = $_POST["pass"]; # assuming the password field is named pass

$query = "SELECT * FROM `users_table` WHERE `username` = '". $username ."'";
$result = mysql_query($query);
if(!$result)
{echo("Mysql error: ". mysql_error()); exit;}
if(mysql_num_rows($result)==0)
{echo("Username does not exist in database."); exit;}
while($row=mysql_fetch_assoc($result)){
$realPass = $row["pass"];
}

if(md5($pass) == $realPass){
echo("Passwords match - good job!");
} else {
echo("Invalid password."); exit;
}


[J]ona

pyro
10-22-2003, 06:04 PM
You shouldn't need the while loop. The below should work for you.

$row=mysql_fetch_assoc($result);
$realPass = $row["pass"];I also would have formatted it a bit differently, mostly for easier readability, but that's probably more a personal preference than anything.

Jona
10-22-2003, 11:16 PM
Originally posted by pyro
You shouldn't need the while loop. The below should work for you.

Ahh... Movie Me starring Me, written by Me, errors by Me. Thanks. ;)


Originally posted by pyro
I also would have formatted it a bit differently, mostly for easier readability, but that's probably more a personal preference than anything.

I have a problem with coding things and making them hard to read for others... I'm kind of too used to it to change, although it makes no difference since it is server-side... :rolleyes: Bad or good habit? Even with bad eyesight, I continue to bang my head on the table, waiting for it to break in half so that I can grab the hammer from the ceiling fan and bust the window...

[J]ona

pyro
10-23-2003, 07:21 AM
It's actually not bad (if I remember right, it's pretty close to what php.net has for it's example). I just like to do it differently, so I don't have to use exit() -- that way, I can display the rest of the page (when needed) rather than just the error message.

Just for the heck of it, this is the jist of what I wrote up the other day when I was making a login for a site I'm working on:

<?PHP
$db = @mysql_connect('localhost','username','password') or die("Could not connect because: ".mysql_error());
mysql_select_db('database');

if (isset($_POST['submit'])) {
foreach ($_POST as $name => $val) {
$_POST[$name] = htmlspecialchars($val, ENT_QUOTES); #do some data scrubbing
}
$username = $_POST['username']; #set the username variable
$password = $_POST['password']; #set the password variable
if($username != "" && $password != "") { #if username and password are not blank
$sql = "SELECT * FROM `members` WHERE `username` = '".$username."'";
$results = mysql_query($sql);
if (mysql_num_rows($results) != 0) { #if no rows were found (username doesn't exist)
$data = mysql_fetch_array($results, MYSQL_ASSOC);
if ($data['password'] != md5($password)) { #if the password in the db does not equal the one they entered
$error = "That is an invalid password. Please try again.";
}
else { #everything is good
echo "LOGGED IN"; #do something if they are logged in. Maybe something like the below line
#header("Location:http://www.yourdomain.com/logedin.php");
}
}
else {
$error = "That is an invalid username. Please try again."; #set error for invalid username
}
}
else {
$error = "Please enter both a username and a password."; #set error if neither username nor password were filled out
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?PHP
if (isset($error)) {
echo "<p style=\"color: red;\">$error</p>";
}
?>
<form action="<?PHP echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="submit" name="submit" value="login"></p>
</form>
</body>
</html>

tinernet
10-26-2003, 07:20 AM
thanks pyro thats workin great.
for the home page, there is a table of all of the stats of each user, i.e. all of the data in the mysql table. is there a way that i can store the username that has logged in so that each time u go to a page it loads the correct data. maybe cookies or somethin?
and then would i display the like this:

$sql = "SELECT * FROM `epic` WHERE `username` = '".$username."'";
$results = mysql_query($sql);
$data = mysql_fetch_array($results, MYSQL_ASSOC);
echo($data['cash']);

thats where $username is the stored username variable and cash is the field name in the mysql table.
thanks.

pyro
10-26-2003, 08:53 AM
Yep, cookies should work fine, as long as users have them enabled.

$user = "someuser";
setcookie ("user", $user, time()+3600, "/");And to read it:

echo $_COOKIE['user'];See also: http://us2.php.net/manual/en/function.setcookie.php

tinernet
10-26-2003, 09:46 AM
ok, but what about when more than 1 user logs on at any one time, surely the cookie will be overwritten? the obvious answer is to get it to wirte different cookies for differnt users but how would you do that?

pyro
10-26-2003, 09:49 AM
Cookies are user specific. If you set it for one users, it has no effect on other users.

tinernet
10-26-2003, 09:53 AM
ahhhhhh sorry im a retard

pyro
10-26-2003, 09:58 AM
Hey, no problem, mate... :)

tinernet
10-26-2003, 10:00 AM
i really do think what u guys do is great. if it wasnt was superdudes like u guys retards like me would just get bored. but also im learnin a load, so that when sum1 els has a prob il b able to help them. thanks a lot! il prob b back soon...............

tinernet
10-26-2003, 10:30 AM
so do i just use the setcookie() code again with the same cookie code to edit it? iv hunted around on the net and it ses the best way to delete cookies is to set the time to -3600 (or the negative of what u created). is this the best way?

pyro
10-26-2003, 12:31 PM
Yes, to overwrite a cookie, just set a new value to the same name. Also, yes, to delete a cookie, just set it's exp date to some value in the past.

tinernet
10-26-2003, 02:06 PM
hey. it seems easier just to continue with this thread, and i told u id be back! iv used an INSERT INTO query to sign up users, but it doesnt check whether or not the username entered already exists. can this be done?
and also, a friend said there is a way of using a "loop" to make a league table, which displays a table of usernames and statistics in order of a field, but iv had no luck in making one. any ideas? thanks

pyro
10-26-2003, 09:25 PM
To check if a username exists, try something like this:

untested
$username = "someuser";
$sql = "SELECT `username` FROM `tablename` WHERE `username` = '$username'";
$results = mysql_query($sql);
if (mysql_num_rows($results) == 0) {
#no username was found
}
else {
#that username was found
}And, to print out a table, you'd just want to select all (*) from the table and print it out.

tinernet
10-27-2003, 07:48 AM
ok so id use echo $data['var']; then? if that is rite, that only writes one row of data, how do i get it to write ALL the rows, buta lso pu tthem into a html table with a new tr for each mysql row?

pyro
10-27-2003, 07:59 AM
Try something like this:

untested
<?PHP
$sql = "SELECT * FROM `tablename`";
$results = mysql_query($sql);
echo "<table>";
while($data = mysql_fetch_array($results, MYSQL_ASSOC)) {
echo "<tr>
<td>".$data['one']."</td>
<td>".$data['two']."</td>
<td>".$data['three']."</td>
</tr>";
}
echo "</table>";

tinernet
10-27-2003, 08:28 AM
i have tried to make a variable that is 3 mysql fields added together as below but it keeps returing this error:
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in /data/members/free/tripod/uk/e/p/i/epicgame/htdocs/table.php on line 8
line 8 is the $men = "" line so i assume it doesnt like the way iv tried to add them up.

<?PHP
$db = mysql_connect("localhost","epicgame","biffyclyro") or
die("Unable to connect to the server. Please try again later.");
mysql_select_db("epicgame_uk_db",$db);
$sql = "SELECT * FROM `epic`";
$results = mysql_query($sql);
$data = mysql_fetch_array($results, MYSQL_ASSOC);
$men = ".$data['inf']."+".$data['flam']."+".$data['com'].";
$veh = ".$data['jeep']."+".$data['tank']."+".$data['trans'].";
$ship = ".$data['aship']."+".$data['fight']."+".$data['bomb'].";
echo "<table>";
echo "<tr>
<td>".$data['uname']."</td>
<td>".$men."</td>
<td>".$veh."</td>
<td>".$ship."</td>
<td>".$data['worth']."</td>
</tr>";
echo "</table>";
mysql_close();
?>

how should this be done?

pyro
10-27-2003, 11:55 AM
Depends if you mean add as in add (mathematical) or add as in concatenate (join).

tinernet
10-27-2003, 02:08 PM
well i want to add it mathematically. is php like javascript where + puts to variables next to each other? in js u use eval(var) and then you can add them. is there somethin like that in php?

pyro
10-27-2003, 03:33 PM
No, in PHP, the . is the concatenation operator.

If the variables are numbers, try this:

$men = $data['inf']+$data['flam']+$data['com'];

tinernet
10-28-2003, 05:22 AM
ok, iv managed to put this together:

<html>
<head>
<title>Epic League Table</title>
</head>
<?php
$db = mysql_connect("localhost","epicgame","biffyclyro") or
die("Unable to connect");
mysql_select_db("epicgame_uk_db",$db);
$sql = "SELECT * FROM epic ORDER BY worth DESC";
$results = mysql_query($sql);
$data = mysql_fetch_array($results, MYSQL_ASSOC);
mysql_close();
echo("<body style='background:black'>");
echo("<h1 style='text-align:center;color:white;font-family:OCR A Extended'>Epic League Table</h1>");
echo("<table name='details' border=0 style='text-align:center;border:1px white solid;color:white;font-family:OCR A Extended;font-size:12pt'>");
echo("<tr>");
echo("<td width='20%' style='border-bottom:1px white solid'><b>Rank</b></td>");
echo("<td width='20%' style='border-bottom:1px white solid'><b>UserName</b></td>");
echo("<td width='20%' style='border-bottom:1px white solid'><b>Soldiers</b></td>");
echo("<td width='20%' style='border-bottom:1px white solid'><b>Vehicles</b></td>");
echo("<td width='20%' style='border-bottom:1px white solid'><b>Ships</b></td>");
echo("<td width='20%' style='border-bottom:1px white solid'><b>Worth</b></td>");
$num=mysql_num_rows($results);
$num++;
for($x=1;$x<=$num;$x++) {
$uname=$data['uname'];
$men = $data['inf']+$data['flam']+$data['com'];
$veh = $data['jeep']+$data['tank']+$data['trans'];
$ship = $data['aship']+$data['fight']+$data['bomb'];
$worth = $data['worth'];
echo("<tr><td>$x</td><td>$uname</td><td>$men</td><td>$veh</td><td>$ship</td><td>$worth</td></tr>");
}
echo("</table>");
?>
</body>
</html>

which is here (http://members.lycos.co.uk/epicgame/table.php). as you can see, its only displaying the first user in the table. how do i mkae it write a new row for each user in the mysql table? do you see what im gettin at now?

tinernet
10-28-2003, 05:24 AM
ok now iv spelt one of variables right......its puttin the right number of rows i think but there all for the same user. ARG!

tinernet
10-28-2003, 05:40 AM
ARG NOW ITS NOT DOIN NETHINAND I HAVENT CHANGED IT! WHY OH WHY OH WHY DID I DECIDE TO LEARN PHP!?

pyro
10-28-2003, 07:44 AM
This is untested, but give it a try:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Epic League Table</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body style="background:black;">
<h1 style="text-align:center;color:white;font-family:'OCR A Extended', arial, sans-serif;">Epic League Table</h1>
<table name="details" border="0" style="text-align:center;border:1px white solid;color:white;font-family:'OCR A Extended', arial, sans-serif;font-size:12pt;">
<tr>
<td width="17%" style="border-bottom:1px solid white;"><b>Rank</b></td>
<td width="17%" style="border-bottom:1px solid white;"><b>UserName</b></td>
<td width="17%" style="border-bottom:1px solid white;"><b>Soldiers</b></td>
<td width="17%" style="border-bottom:1px solid white;"><b>Vehicles</b></td>
<td width="16%" style="border-bottom:1px solid white;"><b>Ships</b></td>
<td width="16%" style="border-bottom:1px solid white;"><b>Worth</b></td>
</tr>
<?php
$db = mysql_connect("localhost","epicgame","biffyclyro") or die("Could not connect because: ".mysql_error());
mysql_select_db("epicgame_uk_db") or die("Could not select database because: ".mysql_error());
$sql = "SELECT * FROM `epic` ORDER BY `worth` DESC";
$results = mysql_query($sql);
$x = 0;
while ($data = mysql_fetch_array($results, MYSQL_ASSOC)) {
$x++;
$uname = $data['uname'];
$men = $data['inf']+$data['flam']+$data['com'];
$veh = $data['jeep']+$data['tank']+$data['trans'];
$ship = $data['aship']+$data['fight']+$data['bomb'];
$worth = $data['worth'];
echo "<tr>
<td>$x</td>
<td>$uname</td>
<td>$men</td>
<td>$veh</td>
<td>$ship</td>
<td>$worth</td>
</tr>";
}
?>
</table>
</body>
</html>

tinernet
10-28-2003, 09:59 AM
yeah that works great pyro thanks. it sometimes gets annoyin when i slave away for hours and u fix it in 2 secs lol. the benefit of expeience. the only thing im stuck with at the moment si a variable problem. in one set of <?php?> tags iv defined the variable $data as a mysql_fetch_array, and then iv called it in another but diferent set of <?php?> tags within the same document as echo $data[''];. this isnt working! is this like js where u hav to use global variables if you want to use a variable in mor than one function? if so how du define a global variable in php and if not how else can i do this?orginally i used cookies but it seems stupid to do mysqldb->cookie->page when i can just use mysqldb->page. help!

p.s. if im pissin people off with all these pros just say and il bugger off lol.

pyro
10-28-2003, 10:13 AM
If you are using functions, yes, you will have to define the variables as global. If you are just using seperate <?PHP ?> blocks, you shouldn't need to. Why don't you post you code, and we'll take a look... :)

tinernet
10-29-2003, 05:49 AM
<?php
if ($uname == "") {
header("Location=nouser.php");
}
else {
$db = @mysql_connect('localhost','epicgame','biffyclyro') or die("Could not connect because: ".mysql_error());
mysql_select_db('epic');
$uname = $_COOKIE['user'];
$sql = "SELECT * FROM 'epic' WHERE 'uname'='".$uname."'";
$results = mysql_query($sql);
$data = mysql_fetch_array($results, MYSQL_ASSOC);
mysql_close;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Epic Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
body {background:#CC0000;color:white;font-family:OCR A Extended;font-size:12pt}
#main {position:absolute;text-align:left;left:5%;top:7%;width:90%;height:80%;background:black;border:2px solid white;color:white;font-family:OCR A Extended;font-size:12pt}
.menu {position:absolute;left:25%;top:20%}
a{color:red;font-family:OCR A Extended;font-size:12pt;text-decoration:none;font-size:9pt}
a:hover{color:red;text-decoration:underline;font-size:9pt}
</style>
</head>
<body>
<map name="menu">
<area shape="rect" coords="6,6,106,111" href="infpage.php" alt="Skip to Infantry Section">
<area shape="rect" coords="114,8,230,112" href="veh.php" alt="Skip to Vehicle Section">
<area shape="rect" coords="233,11,346,108" href="ship.php" alt="Skip to Aerial Section">
<area shape="rect" coords="350,9,446,113" href="supp.php" alt="Skip to Supply Section">
<area shape="rect" coords="90,137,191,270" href="war.php" alt="Skip to War Section">
<area shape="rect" coords="237,139,390,267" href="profile.php" alt="View and Edit you User Profile">
</map>
<div id="main">
<div align=center style="font-size:14pt">Welcome, <?php echo $_COOKIE['user']; ?></div>
<table>
<tr><td style="font-size:9pt;border:solid 1px white">Cash<br>$<?php echo $data['cash']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Turns<br><?php echo $data['turns']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Fuel<br><?php echo $data['fuel']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Food<br><?php echo $data['food']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Workers<br><?php echo $data['work']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Infantry<br><?php echo $data['inf']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">FlameTroops<br><?php echo $data['flam']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Commandos<br><?php echo $data['com']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Jeeps<br><?php echo $data['jeep']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Tanks<br><?php echo $data['tank']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Transports<br><?php echo $data['trans']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Airships<br><?php echo $data['aship']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Bombers<br><?php echo $data['bomb']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Fighters<br><?php echo $data['fight']; ?></td></tr>
<tr><td style="font-size:9pt;border:solid 1px white">Worth<br><?php echo $data['worth']; ?></td></tr>
<tr><td style="background:white;font-size:9pt"><a href="table.php">League Table</a></td></tr>
<tr><td style="border:none"><form action="logout.php"><input type=submit value="LogOut"></form></td></tr>
</table>
<div class="menu"><img src="mainmenu.PNG" border="0" border="none" usemap="#menu"></div>
</div>
</body>
</html>

pyro
10-29-2003, 06:59 AM
You have an error in the SQL. Try this:

$sql = "SELECT * FROM `epic` WHERE `uname`='".$uname."'";Note that it uses backticks (`) rather than single quotes.

tinernet
10-29-2003, 08:04 AM
k iv done that, and its given me this error:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webadmin-uk@lycos-europe.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

it doesnt so it for any of my other pages, so is it somethin iv dun or is a problem with the lycos server thats nuthin to do with me?