PDA

View Full Version : how to login as a user with php?


hope
04-04-2010, 08:41 PM
hi, i am hope
i am a new developer using php language.

i need to know the steps of making the code of logging in as a user on a website using php.

i.e: i have a website and need to make users login my site

what is the steps of writing this login code ?

thanks in advance

tux
04-04-2010, 10:22 PM
login.php


<?php
require_once("your connection here"); // or your database connection code here instead
///////////////////////////////////////////
session_start();
/////////////////////////////////////////
$username = $_POST['username'];
$password = $_POST['password'];
$submitted = $_POST['submitted'];//hidden field in your form
/////////////////////////////////////////

if($username && $password){
///////////////////////////////////////// edit 'users' to the name of your database table
$query = sprintf("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
$result = @mysql_query($query);
$user = @mysql_fetch_array($result);
/////////////////////////////////////////
}
if($user){
$_SESSION['id'] = $user['userID'];
header("location:your_account.php");//change this to the page you are protecting
exit;
}elseif($submitted){
echo "LOGIN FAILED. Your username and password combination was not correct. Please try again.";
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login</title>

</head>

<body>

<form name="login" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="submitted" value="1" />

Username<input name="username" type="text" id="username" />

Password<input name="password" type="password" id="password" />

<input type="submit" name="login" id="login" value="login" />
</form>

</body>
</html>


logout.php

<?php

session_start();

session_destroy();

header("location:login_script.php");
exit;

?>

davidj
04-05-2010, 09:58 AM
echo "LOGIN FAILED. Your username and password combination was not correct. Please try again.";

You shouldn't echo anything above the <html

Its invalid and you have no control over positioning

tux
04-05-2010, 11:34 AM
Yes David, but this was just so Hope could understand how to do it.