WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : complete, simple, working example of a login screen/system using php functions, cookies, and a mysql database for begginers.
Categories : Authentication, Complete Programs, PHP, MySQL, Databases Update Picture
Graham Hart
Date : Apr 16th 2000
Grade : 3 of 5 (graded 19 times)
Viewed : 79502
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Graham Hart
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

/*
This is an example of a login screen I made. In addition there is some code to be placed in an include file to go with it that you can include on each page on
your site that varifies
that the user has used the login screen to login to the site. This will protect pages from unregistered users etc.

Ok, the way this script works is it presents the user with an HTML form that prompts the user to enter their username and password.
note: this script is to login an already registered user, it does not add users to database.
The username and password get submitted back to the same page, because the code that validates the login resides on the same page with the code that presents
the screen. This
is one of the beauties of PHP, saves from having to create a bunch of scripts to do the job.
ok anyways, it submits back to the page and checks submited username/pass with the ones already in the database.
Another note:
Database used: MySQL
Database name used: register
Database table used: login
Field names in table: username and password (only two fields)
consult www.php.net/manual/ for additional information on functions used.
That was an overview, more details are in the comments in the code.
I know if you're a begginer I didn't explain the functions varry well, nore did I explain the arrays at the end, please refer to the manual if you have any
questions, it is actually
fairly straight forward, but if you still have questions drop into #PHP on irc.openprojects.net
*/

<?
// This first if statement checks to see if we have a username/pass submited by the form, if it does then it attempts to validate it.
if($username && $password) {
mysql_connect() or die ("Whoops"); // Connect to the database, or if connection fails print error message.
$password = md5($password); // encode submited password with MD5 encryption and store it back in the same variable. If not on a windows box, I
suggest you use crypt()
$sql = "select * from login where username='$username'"; // query statment that gets the username/password from 'login' where the username is the same as
the one you
submited
$r = mysql_db_query("register",$sql); // Execute Query

// if no rows for that database come up, redirect.
if(!mysql_num_rows($r))
header("Location: $SCRIPT_NAME"); // This is the redirection, notice it uses $SCRIPT_NAME which is a predefined variable with the name of the script in it.

$user = mysql_fetch_array($r); // if we got passed the last if statment means we have a registered username, get the rest of the info and put it in an array
named $user
if($user["password"] == $password) { // If the password stored in the database is the same as the password the user entered (which is now encryped with MD5)
$password = serialize($password); // if we get this far we know we have a registered username, and the password matches.
// serialize() the already incrypted password just for fun and mabey some extra security for when we
store it in a cookie
setcookie("candle_login","$username $password"); // Set the cookie named 'candle_login' with the value of the username (in plain text) and the password
(which has been
encrypted and serialized.)

// set variable $msg with an HTML statement that basically says redirect to the next page. The reason we didn't use header() is that using setcookie() and
header() at the same
time isn't 100% compatible with all browsers, this is more compatible.

$msg = "<meta http-equiv=\"Refresh\" content=\"0;url=./nextpage.php\">";
}else{
header("Location: $SCRIPT_NAME"); //If the password didn't match, redirect to this page in which $username and $password are reset therefore the first if
() never gets executed
}
}
if($msg) echo $msg; //if $msg is set echo it, resulting in a redirect to the next page.
?>

// This is the login screen
<html>
<title>Login to PHP Coders DB</title>
<body bgcolor="yellow" text="black">
<form method="post" action="<?echo $SCRIPT_NAME;?>"> // submit form data to this page

<center><font size=+5><b>Welcome!</b></font></center>
<br>
<br>
<br>
<table cellspacing=0 cellpadding=0 width=320 align="center">
<tr><td>
Username:
</td><td>
<input name="username" type="text" width=10>
</td></tr>
<tr><td>
Password:
</td><td>
<input name="password" type="password" width=10>
</td></tr>
<tr><td colspan=2 align="center">
<input name="login" type="submit">
</td></tr>
</table>
</form>
</html>


/* That was the login page
Next is some code you can put into a different file (named 'login_check.inc' or something)
that you include() on each page you want protected on your site.
It uses the cookie from the first script to verify user has already been there.
*/

<?
// if the cookie doesn't exsist means the user hasn't been verified by the login page so send them back to the login page.
if(!$candle_login)
header("Location: ./login.php");

if($phpcoders) { // if the cookie does exsist
mysql_connect() or die ("Whoops"); //connect to db
$user = explode(" ","$phpcoders"); //explode cookie value (which is the '$username $password (note seperated by space)) and store values in $user. Check
manual for more info
on explode()

$sql = "select * from login where username='$user[0]'"; //sql statment that uses the username from the cookie.
$r = mysql_db_query("register",$sql); //execute sql

if(!mysql_num_rows($r)) { // if there are no rows, means no matches for that username
header("Location: ./login.php"); // so go back to the login page
}

$chkusr = mysql_fetch_array($r); //if we got passed the last part, then get the username/password set that match that username
if(unserialize($user[1]) != $chkusr[1]) //if the password from cookie (notice we have to unserialize it) doesn't match the one from the database
header("Location: ./login.php"); // go back to the login page
} // if it did match then continue on to page and this ends up doing nothing :)
?>

/* thats all, feel free to drop me an email or catch me on in #PHP on irc.openprojects.net */



This program allows you to upload an ODBC ressource - i.e. an MS-Access database to a MySQL server.
Categories : Databases, MySQL, Complete Programs, PHP, Databases
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
Accepts a database & hostname from a user and then HTTP username and password. Uses this to connect to a MySQL database. Produces a form based on the tables it finds there to allow the user to do SELECTs, INSERTs, and DELETEs.
Categories : Databases, PHP, MySQL, Complete Programs
phpAds, a complete banner and ad management system with detailled tracking and stats.
Categories : MySQL, Complete Programs, Ecommerce, PHP, Databases
Point and Click Interface ala MS Access for creating SQL statements.
Categories : MySQL, Complete Programs, General SQL, PHP, Databases
Tropicalm Genetree Family (MySQL based family tree)
Categories : PHP, Interfaces, Databases, MySQL, Complete Programs
Authorize Me! An authentication script.
Categories : MySQL, Databases, Authentication, PHP
Shopping Basket On-Line Ordering System.
Categories : Complete Programs, MySQL, PHP, Ecommerce, Databases
free, search engine, indexing, system, information, web, ftp, http, free, software, cgi, php, MySQL, database, php3, FreeBSD, Linux, Unix, UdmSearch
Categories : MySQL, Complete Programs, PHP, Databases, Search
Full membership authentication system.
Categories : Authentication, MySQL, PHP, Databases
Example voting script. Lets people enter suggestions and vote for existing ones.
Categories : MySQL, PHP, Cookies, Complete Programs, Databases
Simple Mini Poll class library (SimPoll)
Categories : PHP, PHP Classes, Databases, MySQL, Complete Programs
Browse a MySQL database & draw a tree view & load final items into a template page.
Categories : MySQL, Complete Programs, Algorithms, PHP, Databases
Shopping Cart e-Commerce Solution
Categories : Complete Programs, PHP, MySQL, Databases
Implementing a "Members ONLY" area
Categories : PHP, MySQL, Databases, Authentication
 Mariano Neves wrote : 342
Hi,

I have created the MySQL database and the login table, 
where i put an username and password.
Thatīs perfect.

When I enter the login page, and then press submit, I 
get the following message:
No input file specified. Thatīs pretty strange, īcause 
the FORM action is &lt;form method="post" 
action="/php3/php.exe"&gt;.

I am using PHP 3, Apache 1.3 and Win NT.

Can you help me??

Thanks,

Mariano - Brazil
 
 Boaz Yahav wrote : 343
From the FAQ :

When I try to use authentication with IIS I get `No Input 
file specified` 
The security model of IIS is at fault here. This is a 
problem common to all CGI programs running under IIS. 
A workaround is to create a plain HTML file (not parsed 
by php) as the entry page into an authenticated 
directory. Then use a META tag to redirect to the PHP 
page, or have a link to the PHP page. PHP will then 
recognize the authentication correctly. When the ISAPI 
module is ready, this will no longer be a problem. This 
should not effect other NT web servers. For more 
information, see: 
http://support.microsoft.com/support/kb/articles/q160/4/
22.asp. 
 
 John Przybylski wrote : 368
The action line should include the script file name.  
Having just php.exe is just starting the php application 
without a script.  I`d say it was a typo.  As to what goes 
into the action depends on the server.  If your using the 
same script to create the form and handle the 
interaction, I believe you can leave the action out.  
Otherwise you need to put in the complete relative url 
of the script.  I would try to configure your web server 
so you don`t put /php/php3.exe/script.php3.  Try setting 
the Action/AddType commands in apache.  That will tell 
the web server where to find the php3.exe application.
 
 John Doe wrote : 372
Hi,

I tried this script, but it isn`t working at all.
Question: what is $phpcoders for variable?????

It isn`t mentioned in the first script...
 
 David Keaveny wrote : 379
Great script, but I`m having a small problem. Having 
authenticated through the login.inc, I`m having 
problems reading the cookie from within the &lt;body&gt; 
tags. How can I findout what the user`s login name is?
 
 Graham Hart wrote : 380
OK there is a massive typo in my script.  It`s a result of forgetting to rename a variable and it`s on this line:

if($phpcoders) {     // if the cookie does exsist 

that should be:

if($candle_login) {

it should be the name of the cookie.  Sorry about that!

-Graham

PS Sorry about the formatting, just that the real long screens kinda throw me off :)
 
 Graham Hart wrote : 381
I have no clue where you guys are getting that:

action="php.exe" 

from.  that should be:

action=&lt;?echo $SCRIPT_NAME;?&gt;

which should start php parsing right after the equals sign, therefore echoing $SCRIPT_NAME, which if you 
look in the manual is a pre defined variable which holds the name of the current script.  There is another one 
that would work but I forget what it is.

Anyways, I hope this helps a little at least :)

Graham
 
 chad nantais wrote : 398
I am getting a 403 error: dont have permission to access.
This is strange because other php scripts work in this 
same directory.  Is that error the result of not successfully 
logging in to the sql server? or is it something obvious I am 
not adept enough to see?
 
 kim soenderup wrote : 410
I get this error :

Warning: 0 is not a MySQL result index in 
d:\inetpub\wwwroot\login.php on line 7

Warning: Cannot add more header information - the 
header was already sent (header information may be 
added only before any output is generated from the 
script - check for text or whitespace outside PHP tags, 
or calls to functions that output text) in 
d:\inetpub\wwwroot\login.php on line 8

Warning: 0 is not a MySQL result index in 
d:\inetpub\wwwroot\login.php on line 9

Warning: Cannot add more header information - the 
header was already sent (header information may be 
added only before any output is generated from the 
script - check for text or whitespace outside PHP tags, 
or calls to functions that output text) in 
d:\inetpub\wwwroot\login.php on line 14

I am using win2000  iis5 / php3 / mysql

can you help me ???

Best Regard
      Kim Soenderup (DK)
 
 Rafael Silva wrote : 419
I`m trying to use this autentication code but some erros 
are disturbing me...

Fatal error: Call to undefined function: mysql_connect() 
in C:\HTTPD\HTDOCS\teste\autenticacao.php on line 4

I named the script: autenticacao.php
I named the login page: login.php
I created the database like the manual but I already 
add a data user:rafael pass:1234 using the function 
password of the Mysql
When I try to login in login.php this error that I describe 
happen...if possible
Can anyone help me... I didn`t understand why is this 
problem hapenning?

Thank You

Rafael Oliveira  - Brazil
 
 Fred Moi wrote : 511
I get an error message:
Parse error: parse error, expecting ``,`` or ``;`` in /home/Genmut/GenMut.php3 on line 71
and the pics on the menu bar does not appear.
Any idea what`s wrong ?
 
 Aureliano Rama wrote : 542
This could be a more optimized version.
"Complete, simple working example of login screen and check on a unique page using php functions, cookies and mysql database."
 
http://www.weberdev.com/get_example.php3?count=1779
 
 Raoul Zon wrote : 610
To MOI FRED,

The problem you`re encountering, is really very simple.
Somewhere in the script you haven`t closed down a line.
Search for a quote like "" or a function at the end of it you must have a ; or else you`ll get that error message
 
 Koko Delicious wrote : 641
i`ve tried it n got this message ....

Warning: Cannot add header information - headers already sent by (output started at c:/program files/abria merlin/apache/htdocs/log/login.php:2) in c:/program files/abria merlin/apache/htdocs/log/login.php on line 32

helppppp!!
 
 Mandor vo Mimbre wrote : 668
This script looks great, but Im a total beginner in MySQL. How do I make the database and add users/passwords to it?
 
 seekwin beng wrote : 715
I`ve key in the username and password into my database but when I key in the correct username and password, it doesn`t direct me to the required page. what`s is wrong?
My code is shown below, please I need help.
=====================================
&lt;?php
/*This file is created for a login session.  
 *  Database used:            MySQL 
 *  Database name used:       software
 *  Database table used:      company
 *  page directed to :          comlistlink.php    
 *  Field names in table:  user and passwd (two relevant fields) 
 */ 
 
//Checks made to see if  user & passwd submited by the form is in database, 
if($user && $password) { 
  $db = mysql_connect("localhost", "software","") or die ("Could not connect");
  
mysql_select_db("software",$db) or die ("Could not select database");
//Already have passwords not in encryted form in database.   
  $passwd = $password;
  // query statement that gets the username/password from `login` where 
  //the username is the same as the one you submited.
  $sql = "SELECT * FROM company WHERE user=`$user`";
  $result = mysql_query($sql,$db)or die ("Query failed");  // Execute Query 

  // if no rows for that database come up, redirect. 
  if(!mysql_num_rows($result)){ 
    // This is the redirection, which uses $PHP_SELF/$SCRIPT_NAME which are a predefined variables 
    // with the name of the script in it. 
    header("Location: $PHP_SELF");
    // if we got passed the last if statment means we have a registered username,
    // get the rest of the info and put it in an array named $user 
    $myrow = mysql_fetch_array($result);
  }
  
  if($myrow["passwd"] == $passwd) {   
    // If the password stored in the database is the same as the password the user entered
        $passwd = serialize($passwd);
    
    // if we get this far we know we have a registered username, and the password matches. 
    // serialize() the already encrypted password maybe for some extra security
    // for when we store it in a cookie. 
    // Set the cookie named `page_login` with the value of the username (in plain text) 
    //and the password (which has been serialized.) 
    setcookie("page_login","$user $passwd");  
    // set variable $msg to 1 that basically says redirect to the next page.
    $msg =`1`; 
  }else{ 
     //If the password didn`t match, redirect to this page in which $user and $passwd
     //are reset therefore the first if () never gets executed 
     header("Location: $PHP_SELF");
  } 


if($msg != NULL) 
     //if $msg is set echo it, resulting in a redirect to the next page. 
     header("Location: http://loacalhost/comadmin.php");  
?&gt; 

&lt;?php
//Include the header for the page.
echo"&lt;center&gt;";
INCLUDE "header.inc";
echo"&lt;/center&gt;";
?&gt;


&lt;form method="post" action="&lt;?echo $PHP_SELF?&gt;"&gt;  
&lt;center&gt;&lt;font size=+5&gt;&lt;b&gt;Login Page&lt;/b&gt;&lt;/font&gt;&lt;/center&gt; 
&lt;br&gt; 
&lt;br&gt; 
&lt;br&gt;
&lt;center&gt; 
&lt;table cellspacing=0 cellpadding=0 width=320 align="center"&gt; 
&lt;table&gt;
  &lt;tr&gt;&lt;td&gt;&lt;b&gt;User&lt;/b&gt;&lt;/td&gt;    &lt;td&gt;&lt;input type=Text name=user&gt;&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td&gt;&lt;b&gt;Password&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type=password name=password&gt;&lt;/td&gt;&lt;/tr&gt;
  &lt;tr&gt;&lt;td colspan=2 align="center"&gt;&lt;input type=submit name=login &gt;&lt;/td&gt;&lt;/tr&gt; 
&lt;/table&gt;
&lt;/center&gt; 
&lt;/form&gt; 

&lt;?php
//Include the footer for the page.
echo"&lt;center&gt;";
INCLUDE "footer.inc";
echo"&lt;/center&gt;";
?&gt;


Your help will be greatly appreciated.
 
 D. Kovacs Istvan wrote : 722
login screen
 
 net mastan wrote : 759
it would be nice if u mentioned about creating the table for user and password.. and the form to registered..it will be a complete solution.

1. Regisetering user
2. Login processing

thanks
 
 ma junsheng wrote :1648
good