/    Sign up×
Community /Pin to ProfileBookmark

Login Form using PHP

I have no problem, its that i was told to use php, java, ect. I know thats what im using holds PHP. If you know a login form to this please tell me! (If i need head and body, show me both!) I would like to do more then 1 usernames and passwords!

to post a comment
PHP

9 Comments(s)

Copy linkTweet thisAlerts:
@chestertbJul 02.2006 — do you also have mysql (or similar)? You're going to need somewhere convenient to store the usernames and passwords too.

if so, then you need to create a 'users' table in your database.

that table stores your usernames, passwords and any other information about the people trying to log-in.

the login form is just a standard html form. it's what happens to it after you submit it that will determine who can or can not log in.

here's the form...

<form name="f1" id="f1" method="POST" action="login.php" target="_self" >

<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></td><td><input type="submit" value="Submit" /></td></tr></table>

</form>

then you need to create 'login.php'. something like this...

<?php

//collect the posted variables

$user = $_POST['user'];

$password = $_
POST['password'];

//now connect to your database. in this example, i'm using mysql

$user = $your_database_user;//your mysql database will have a username, password etc

$pass = $connect[1];

$db = $connect[2];

$link = mysql_connect("localhost",$user, $pass);

if(! $link) die("Couldn't Connect To SQL - ".mysql_error());//will tell you that the connection to the database failed, and why

mysql_select_db($db, $link) or die("Couldn't open $db: ".mysql_error());//now the db is selected

//ok. now you need to cross check the log-in details against your database table of users

$query = "SELECT * FROM users WHERE username = '$user';//creates the sql query

$result = mysql_query($query, $link);//executes the query on the database resourced as "$link";

$rows = mysql_num_rows($result);//tells you how many records were returned by your query

now we have everything we need to check whether this is an authorised user

if($rows==0)

{

//the user's name wasn't found... therefore not authorised so send him/her back tot he login page with an error message

}

else

{

//user's name was found... get the password and compare

$row = $mysql_fetch_array($result);//put the result into an array

$pw = $row['password'];//gets the stored password value from your database

if($password==$pw)

{

//password matches... user is authorised

}

else

{

//password doesn't match... send the user back to the login page with an error

}

and that's pretty much it.

after that, you just need to store the authorisation somewhere. you can do that by putting an authorisation value into a cookie, or even passing an authorisation value from page to page (which is what I do).

hope this helps.

CTB
Copy linkTweet thisAlerts:
@Luke101authorJul 02.2006 — ???? WOW!!! SLOW DOWN!!!! THIS MIX ME AL UP! can you put 1 page all together in a code! (dont know how to put it in a code [ code ] text [ /code ] No spaces!) Where do i put the usernames and passwords! HELP!!
Copy linkTweet thisAlerts:
@Luke101authorJul 02.2006 — Please, some1 post something! 3 members 1 guest!
Copy linkTweet thisAlerts:
@chestertbJul 02.2006 — no.

that's what i was trying to get across to you.

there are four elements you need to create to make all this work.

1) you need an html page that contains a log-in form

2) you need to submit that log in form to a php script that processes the user name and password (can be the same page if you set some flags)

3) you need to access the database using sql to check that the user exists, and that he/she's using the correct password

4) you need to write a cookie, or create a value that's passed from page to page that authorises the user

creating a php log-in page isn't about creating an html page, it's about creating a server-side script that verifies some data

here's the a single page that will do the job for you

<?php

//first, collect the posted variables

$user = $_POST['user'];

$password = $_
POST['password'];

$act = $_POST['act'];//this tells the script is action is required

//now connect to your database. in this example, i'm using mysql

$user = $your_database_user;//your mysql database will have a username, password etc

$pass = $connect[1];

$db = $connect[2];

$link = mysql_connect("localhost",$user, $pass);

if(! $link) die("Couldn't Connect To SQL - ".mysql_error());//will tell you that the connection to the database failed, and why

mysql_select_db($db, $link) or die("Couldn't open $db: ".mysql_error());//now the db is selected

if($act=="login")

{

//ok. now you need to cross check the log-in details against your database table of users

$query = "SELECT * FROM users WHERE username = '$user';//creates the sql query

$result = mysql_query($query, $link);//executes the query on the database resourced as "$link";

$rows = mysql_num_rows($result);//tells you how many records were returned by your query

//now we have everything we need to check whether this is an authorised user

if($rows==0)

{

//the user's name wasn't found... therefore not authorised so send him/her back tot he login page with an error message

}

else

{

//user's name was found... get the password and compare

$row = $mysql_fetch_array($result);//put the result into an array

$pw = $row['password'];//gets the stored password value from your database

if($password==$pw)

{

//password matches... user is authorised

$ok="Y";

}

else

{

//password doesn't match... send the user back to the login page with an error

}

}

if(ok=="Y")

{
>?

<h1>This is secure content</h1>

<?php

}

else

{

?>

<h1>Log In</h1>

<form name="f1" id="f1" method="POST" action="login.php" target="_self" >

<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='hidden' name='act' value='login'></td><td><input type="submit" value="Submit" /></td></tr></table>

</form>

<?php

}

?>


I'm not sure I can be more specific than that. If you need to learn php, there are some really good books out there that will help you. I like "Teach Yourself php In 24 Hours", by Matt Zandstra and published by SAMS.

CTB
Copy linkTweet thisAlerts:
@Heavy_MetalJul 02.2006 — It depends if you want a flat file interface, which doesn't use a database, only files. Or if you want a SQL database which in that case, you'll need something along these lines.

[b]:.:sql query:.:[/b]
[code=php]
CREATE TABLE users
(username varchar(15),
password varchar(32),
email varchar(30));
[/code]


[b]:.:Login.php:.:[/b]
[code=php]<?
session_start();

$_SESSION['loged_in'];

if($_SESSION['loged_in'] == "1") {
die("You are already logged in.");
} else {
?>
<html>
<body>

<form method="POST" action="login2.php">
<b>Username:</b> <input type="text" name="username"><br>
<b>Password:</b> <input type="password" name="password"><br>
<input type="submit" value="Login" name="submited"><input type="reset" value="Clear">
</form>

</body>
</html>
<?
}
?> [/code]


[b]:.:Login2.php:.:[/b]
[code=php]
<?
session_start();
?>
<html>
<body>
<?
if(isset($_POST['submited']) && !$_SESSION['loged_in']) {
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5($password);

if(!$username || !$password) {
die("You did not enter a username or a password");
}

$sqlconn = "localhost";
$sqluser = "sql_username";
$sqlpass = "sql_password";
$sqldb = "name_of_sql_database";

$conn = mysql_connect($sqlconn, $sqluser, $sqlpass);
if(!$conn) {
die("Could not connect to: ".$sqlconn.":.:".mysql_error());
}

mysql_select_db($sqldb, $conn)
or die("Could not select:.:".$sqldb." - ".mysql_error());

$selectquery = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");


$num_rows = mysql_num_rows($selectquery);

if($num_rows > 0) {
echo "Login Successful!";
$_SESSION['username'] = $username;
$_SESSION['loged_in'] = "1";
echo "<meta http-equiv="Refresh" content="2;url=home.php">";
return;
} else {
echo "Wrong username or password, Please go back and try again.";
}
}
?>
</body>
</html>
[/code]


[b]:.:register.php:.:[/b]
[code=php]
<html>
<body>

<form action="register2.php" method="post">
<b><i>Note:</i></b>
<p>
<b>Username:</b> <input type="text" name="username" size="20"><br>
<b>Password:</b> <input type="password" name="password" size="20"><br>
<b>Email Address:</b> <input type="text" name="email" size="30"><br>
<input type="submit" value="Submit" Name="submited"><input type="reset">
</form>

</body>
</html>
[/code]


[b]:.:register2.php:.:[/b]
[code=php]
<?
session_start();
?>
<html>
<body>
<?
if(isset($_POST['submited'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$sqluser = "sql_username";
$sqlpass = "sql_password";
$db = "sql_database";
$sqlconn = "localhost";


$username = strip_tags($username);
$email = strip_tags($email);
$password = md5($password);

if(!$username || !$password || !$email) {
die("You did not enter a username or password or a email");
}

$conn = mysql_connect($sqlconn, $sqluser, $sqlpass);
if(!$conn) {
die("Could not connect: ".mysql_error());
}

$db_select = mysql_select_db($db, $conn);

if(!$db_select) {
die("Could Not select ".$db." Reason: ".mysql_error());
}


$selectquery = "SELECT * FROM users WHERE username='username'";
$insertquery = "INSERT INTO users (username, password, email, accesslvl) VALUES ('$username', '$password', '$email', '$access_lvl')";


$resultquery = mysql_query($selectquery, $conn);
$num_rows = mysql_num_rows($resultquery);
if($num_rows > 0) {
echo "The username that you have selected is currently in use, Please go back, And select A new one.";
} else {
mysql_query($insertquery, $conn)
or die("For unknown reasons, You could not be registered, Please go to <a href="/">Homepage Here</a>, And select Contact Us from the menu and feel out a support form.");

echo "Registration was successful, Login <a href="login.php">Here</a>.";

}
} else {
echo "You did not submit the form. Please go <a href="register.php">Here</a>";
}
?>
</body>
</html>
[/code]


I am still currently developing this heavily ? I hope I helped you. Later, In version 2.6 I am going to have a ACP, which I am currently developing, and alot of other helpful features including a full profile system, and hopefully, a pm system. Hope I helped.
Copy linkTweet thisAlerts:
@william232Jul 02.2006 — I Prefer Sessions it is more secure u will also need to make sure your password is secure by using either sah1 password or md5 password
Copy linkTweet thisAlerts:
@Luke101authorJul 02.2006 — Metal... Yours... I can understand more ?. Its easy to understand!
Copy linkTweet thisAlerts:
@NogDogJul 02.2006 — In case you (or anyone else) is interested, here's the flat-file login class I've been working on recently. It's still in development, and I still need to write the code for creating/editing the user data file; but it might give you some food for thought.
[code=php]
<?php
/*
Flat-file login control

USAGE:
Simply require() this file at the very beginning of any page which is to be
login controlled. For logouts, you can have any such controlled page link to
itself with a ?logout=1 query string:
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?logout=1">Log out</a>

see the "user-modifiable" attributes below for setting up your installation

FILES:
uses a plain text file for user data, one line per user, each line consisting
of:
0-n whitespaces
login_name
1-n whitespaces
md5-encoded_password
0-n whitespaces
*/
class Login
{
// ATTRIBUTES
// User-modifiable:
var $maxNameSize = 16; // max length of login name
var $maxPasswordSize = 16; // max length of password
var $userFile = 'c:/users.txt'; // pathname of user login data file
var $homePage = ""; // // redirect to this URI after logout

// Do not modify below this line....
var $formData = array();
var $userData = array();

// METHODS

// Constructor
function Login()
{
// init formData values:
$this->formData['loginId'] = "";
$this->formData['loginPassword'] = "";
$this->formData['loginAccess'] = "";
// start session
session_start();
// handle logout request:
if(!empty($_POST['logout']) or !empty($_GET['logout']))
{
$this->logout();
}
// handle login request:
elseif(isset($_POST['login']) and $this->validateLogin())
{
return(TRUE); // successful login
}
// see if we're already logged in:
elseif(!empty($_SESSION['loginId']))
{
return(TRUE); // already logged in
}
// display the login form instead of the requested page:
$this->loginForm();
exit;
}

function validateLogin()
{
$this->errorMessage = '';
$this->processLoginInput();
if($this->parseUserFile())
{
if(isset($this->userData[$_POST['name']]) and
md5($_POST['password']) == $this->userData[$_POST['name']])
{
$_SESSION['loginId'] = $_POST['name'];
return(TRUE);
}
else
{
$this->errorMessage = "Invalid user name and/or password";
}
}
else
{
$this->errorMessage = "Unable to read user login data file";
}
return(FALSE);
}

function parseUserFile()
{
$this->userData = array();
if(is_readable($this->userFile))
{
$lines = file($this->userFile);
foreach($lines as $line)
{
$line = trim($line);
if($line == "") { continue; }
list($user, $password) = preg_split('/s+/', trim($line));
$this->userData[$user] = $password;
}
}
return((count($this->userData)) ? count($this->userData) : FALSE );
}

function loginForm()
{
echo <<<EOD
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
<title>Login</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
background: silver;
font: medium arial, helvetica, sans-serif;
color: black;
}
form {
width: 20em;
margin: 5em auto 1em;
padding: 0.5em;
background-color: white;
color: black;
border: outset 3px gray;
}
fieldset {
margin: 0;
padding: 0.5em;
border: groove 2px gray;
}
p {
margin: 0.3em 0;
padding: 0;
line-height: 1.1em;
clear: both;
}
label {
float: left;
width: 7em;
text-align: right;
padding-right: 0.5em;
}
legend {
font-weight: bold;
font-size: 110%;
}
#login { /* submit button */
background-color: #fff;
color: black;
font-weight: bold;
border: outset silver 2px;
}
#error {
color: #c00;
text-align: center;
}
</style>
</head>
<body>
<form action="{$_SERVER['PHP_SELF']}" method="post">
<fieldset>
<legend>Please Log In</legend>
EOD;
if(!empty($this->errorMessage))
{
echo "<p id='error'>".$this->errorMessage."</p>n";
}
echo <<<EOD
<p><label for="name">Login Name:</label>
<input type="text" name="name" id="name" size="16"
maxlength="{$this->maxNameSize}"></p>
<p><label for="name">Password:</label>
<input type="password" name="password" id="password" size="16"
maxlength="{$this->maxPasswordSize}"></p>
<p style="text-align: center">
<input type="submit" name="login" id="login" value="Log In"></p>
</fieldset>
</form>
</body>
</html>
EOD;
return(TRUE);
}

function processLoginInput()
{
foreach($_POST as $value)
{
if(isset($this->formData[$key]))
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$this->formData[$key] = htmlentities(trim($value));
}
}
return(count($_POST));
}

function logout()
{
$_SESSION = array();
if (isset($_COOKIE[session_name()]))
{
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
if(!empty($this->homePage))
{
header("Location: " . $this->homePage);
exit;
}
}
}

// instantiate it:
$login = new Login();
?>
[/code]
Copy linkTweet thisAlerts:
@Luke101authorJul 09.2006 — Hey thanks
×

Success!

Help @Luke101 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...