PHP and MySQL Code

Start typing to search for PHP and MySQL Code Snippets and Articles Search

Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
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 Resources
Web Development Content
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder

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.
Title : Complete, simple working example of login screen and check on a unique page using php functions, cookies and mysql database.
Categories : PHP, Cookies, MySQL, HTML and PHP, Authentication Update Picture
Aureliano Rama
Date : Jan 03rd 2001
Grade : 3 of 5 (graded 21 times)
Viewed : 84474
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Aureliano Rama
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 

Complete, simple working example of login screen and check on a unique page using php functions,
cookies and mysql database.

This script is widely base on the example N 1553 ("Complete, simple, working example of a login
screen/system using php functions, cookies, and a mysql database for beginners." posted at by Hart
Graham, which I wish to thank a lot for its precious work. Altought I have partially modificated
it, it's still
the original script for large parts.
Note: this script is to login an already registered user, it does not add users to database.
Another note:
Database engine used: MySQL
Database name used: DBClients
Database table used: users
Field names in table: username and password (at least these two)

This script is sintetically explained here in an indented format. This indentation is the same I
have used with the nested IFs in the script.

check if the cookie exist.
if it doesn't exist, it will check if $username and $password are passed throught as query string
if so, they are checked against the datas in the database if they are correct then the cookie is
set and the page is reloaded otherwise if they are incorrect, the page is simply reloaded if
$username and $password don't exist, it shows the login page where the datas are collected and sent
back to the same page.         otherwise if the cookie exists it will check the username and passwd stored
in with the database. if the datas in the cookie are incorrect, it clears the cookie and reloads
the page otherwise, it shows the actual page

The following lines assume you have a MySQL database on the same server running PHP and you can
access it with the user DBUser. It assumes also you have a file called "dbConn.php3" with the
following lines inside.

mysql_connect("localhost","DBUser") or die ("Error connecting with the server. Try again later.

I have placed them in a separate file to be able to modify at will the db used without having to
change all the php pages that use the database. If you do so, then remeber to uncomment lines with
the include instruction and to delete the lines above.

The actual page where this script is inserted and executed is after the end of the script. If the
script enters the first IF statement then you will end with the login page or with a redirection to
$SCRIPT_NAME, which contains the location of the actual page. If the script enter the ELSE part of
the first IF, you will end with a redirection or with the actual page. This is obtained by placing
the html after the script. The use of die() instruction after the login page is to stop the script
and to prevent the visualization of the actual page at the end.

if (!$mysql_login) {
// check if $username and $password are passed through as query string
        if($username && $password) {
// If you want to have the passwords in the databases crypted.
         $password = md5($password);

         $loc="Location: http://$SERVER_NAME$SCRIPT_NAME";.
         $sql = "select Password from users_t where Username='$username'";
         $r = mysql_db_query($db,$sql);

//check if the result of the query has at least one row.Or it will redirect the page.
         if(!mysql_num_rows($r)) header($loc);

         $user = mysql_fetch_array($r);
         if($user["Password"] == $password) {
//note the space between the username and the passoword. It will be
//used below to slice the cookie.
         setcookie("mysql_login","$username $password");
                $msg = "<meta http-equiv=\"Refresh\" content=\"0;url=$SCRIPT_NAME\">";
                //The use of the http header is inconsistent with many browser if you have
//already setted a cookie. So, after the setcookie command the script uses
//the meta tag to obtain the same result.

                <title>Login to PHP Coders DB</title>
                <body bgcolor="yellow" text="black">
                <form method="post" action="<?php echo($SCRIPT_NAME)?>">
                <center><font size=+5><b>Welcome!</b></font></center>
                <table cellspacing=0 cellpadding=0 width=320 align="center">
                <tr><td><input name="username" type="text" width=10></td></tr>
                <tr><td>Password: </td><td>
                <tr><td><input name="password" type="password" width=10></td></tr>
                <tr><td colspan=2 align="center"><input name="login" type="submit"></td></tr>

                die(); //This will prevent PHP from showing actual page. See above.
// Set an array called $user with the contents of the cookie
//sliced at the space between username and password, see above.
        $user = explode(" ","$mysql_login");
        $sql = "select Password from users_t where username='$user[0]'";
        $r = mysql_db_query($db,$sql);

//check if the result of the query has at least one row.Or it set the $chk variable.
        if(!mysql_num_rows($r)) $chk=1;
        $chkusr = mysql_fetch_array($r);
        if ($user[1]!=$chkusr["Password"]) $chk=1;
        if ($chk) {
// To reset the cookie, the setcookie function is used here without argoument.
// see above.
         echo("<meta http-equiv=\"Refresh\" content=\"0;url=$SCRIPT_NAME\">");


//After here the actual page starts and only registered user can see it.

PHP4 MYSQL Authentication Script with cookie. Short & Sweet
Categories : Authentication, Apache, Cookies, PHP, MySQL
This functions makes it easy to use session-variables known from ASP. With one Cookie the array "session" will save and restore from a db-record. In this version MySQL is used but it's should very easy to change
Categories : PHP, Arrays, Cookies, MySQL, Databases
How to Create a Shoutbox Using PHP & MySQL
Categories : PHP, MySQL, Web Applications, Beginner Guides, HTML and PHP
Make old style (PHP3) scripts using GET, POST, COOKIE and File uploads (POST) compatible with PHP 4.2.0
Categories : PHP, HTML and PHP, Global Variables, Cookies, Variables
Message of the Day - Random Message (Needs MySQL!)
Categories : Databases, HTML and PHP, PHP, MySQL
a function that builds an HTML select list from any mysql table.
Categories : PHP, MySQL, HTML and PHP
PHP and MySQL scripting for Muyltiple CheckBoxes
Categories : HTML and PHP, MySQL, Databases, PHP
Required form fields that pull from MySQL database
Categories : PHP, HTML and PHP, Databases, MySQL
The Best Authorize
Categories : PHP, MySQL, Cookies
phpCards - PHP/mySQL postcard script with web based admin to add, edit, and delete cards and categories. Very easy to install.
Categories : PHP, Complete Programs, HTML and PHP, MySQL
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
Storing / Retrieving pictures from database This can be used for banner / ads exchange. very useful for people developing big portal with ads in the site........
Categories : PHP, MySQL, Databases, HTML and PHP
Secure Login
Categories : PHP, MySQL, Cookies, Security
dynamic table columns
Categories : PHP, HTML and PHP, Arrays, Databases, MySQL
html split bar used to split in multiple pages a database result
Categories : HTML and PHP, Databases, MySQL, PHP
 D. Kovacs Istvan wrote : 723
complet login screen
 Leon Williams wrote : 840
I found by adding a time to the setcookie would make the cookie last for the specified amount of time rather than expiring to quickly.

ie. For 100 hours :

setcookie("mysql_login","$username $password",time() + 360000); 
 andrea fowler wrote : 860
I`m a forgive me...

What do these error messages mean and how do I fix these problems.


Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 60

Warning: Cannot add header information - headers already sent by (output started at C:\Inetpub\wwwroot\a_heather\forms\login.php:60) in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 60

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 61

Warning: Cannot add header information - headers already sent by (output started at C:\Inetpub\wwwroot\a_heather\forms\login.php:60) in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 72
 Jaan Ustinov wrote : 1126

&gt; Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 60 
I think that your mysql_db_query wasn`t successful and didn`t return a proper result.

&gt;Warning: Cannot add header information - headers already sent by (output started at C:\Inetpub\wwwroot\a_heather\forms\login.php:60) in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 60 
Cookies must be set before ANY output is displayed on page. That means you must not have even whitespaces before PHP tag &lt;?

&gt;Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 61 
Same as first.

Warning: Cannot add header information - headers already sent by (output started at C:\Inetpub\wwwroot\a_heather\forms\login.php:60) in C:\Inetpub\wwwroot\a_heather\forms\login.php on line 72 
Same as second :)
 Zgembo Adishlich wrote :1239
I am a BRAND NEW newbie, it is possible that I am doing something wrong but its killing me because I spent hours and hours trying to figure out why it does not work. Well first I encountered some errors which I got rid off by fixing following:
$loc="Location: http://$SERVER_NAME$SCRIPT_NAME"; 
$sql = "select Password from users_t where username=`$username`"; 
$r = mysql_db_query($db,$sql); 

I believe you are calling field Password from table users_t even thought you mentioned previously it should be called `users` only. Now, I am a newbie so I might be makin a mistake, please forgive me if I did. Well to get to my point, I got the login page with no errors, however it does not do anything once I enter my username and password. It just reloads once I click on SUBMIT. Few questions:

1: How does it know where to transfer me/redirect once I click on the submit button?
2: What kind of role does $SCRIPT_NAME play in all this? 

Please, forgive me for my ignorance, I am new to all this. Any help is more then welcome. thanks a bunch