WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
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
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



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 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 : 83402
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 
 

<?php
/*
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."
http://www.weberdev.com/get_example.php3?count=1553) posted at www.weberdev.com 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.
Thanks.");
$db="DBClients";

/*
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) {
         include("./dbConn.php3");
// 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.
         }else{
                header($loc);
         }
        }else{
?>

                <html>
                <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>
                <br><br><br>
                <table cellspacing=0 cellpadding=0 width=320 align="center">
                <tr><td>Username:</td><td>
                <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>
</form>                
</table>
                <body>
                </html>

                <?php
                die(); //This will prevent PHP from showing actual page. See above.
        }
}else{
        //include("./dbConn.php3");
        $chk=0;
// 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.
         setcookie("mysql_login");
// 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
PHP and MySQL scripting for Muyltiple CheckBoxes
Categories : HTML and PHP, MySQL, Databases, PHP
Password protection for Phorum 3.1.x with userlevels and log.
Categories : PHP, MySQL, Authentication, Security
Amazon book cover handling
Categories : HTML and PHP, PHP, MySQL, Ecommerce
Authorize Me! An authentication script.
Categories : MySQL, Databases, Authentication, PHP
PHP3: Formmail. Just a cgi formmail, but than in PHP. It is easy to use!
Categories : HTML and PHP, Email, PHP, Perl, HTML and PHP
Secure Login
Categories : PHP, MySQL, Cookies, Security
Pull Down Surfing - Surf on Change
Categories : Java Script, MySQL, HTML and PHP, PHP, Databases
PHP4 AND MySQL Authentication
Categories : PHP, MySQL, Authentication, Databases
dynamic table columns
Categories : PHP, HTML and PHP, Arrays, Databases, MySQL
Authentication script to authenticate users in Active Directory through LDAP.
Categories : LDAP, Authentication, Cookies, PHP
Complex paging with no resultset limit
Categories : PHP, MySQL, Databases, Output Control, HTML and PHP
Functions for loading images into a MySQL database and displaying them.
Categories : Graphics, HTML and PHP, MySQL, PHP, Databases
Message of the Day - Random Message (Needs MySQL!)
Categories : Databases, HTML and PHP, PHP, MySQL
phpFormGenerator for Dynamic Form Generation from MySQL
Categories : PHP, PHP Classes, MySQL, Databases, HTML and 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 newbie...so forgive me...

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

Thanks,
Andrea

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:
&lt;code&gt;
$loc="Location: http://$SERVER_NAME$SCRIPT_NAME"; 
$sql = "select Password from users_t where username=`$username`"; 
$r = mysql_db_query($db,$sql); 
&lt;/code&gt;

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