Jump to content
xisto Community
HmmZ

Php Simple Login Tutorial Learn how to make a simple login

Recommended Posts

can you explain this code

if ( $obj = @mysql_fetch_object($r) )  {  // Login good, create session variables  [b]$_SESSION["valid_id"] = $obj->id;[/b]  $_SESSION["valid_user"] = $_POST["username"];  $_SESSION["valid_time"] = time();

Share this post


Link to post
Share on other sites

can you explain this code

if ( $obj = @mysql_fetch_object($r) )  {  // Login good, create session variables  [b]$_SESSION["valid_id"] = $obj->id;[/b]  $_SESSION["valid_user"] = $_POST["username"];  $_SESSION["valid_time"] = time();


hm if i got it right

if ( $obj = @mysql_fetch_object($r) )  {  // Login good, create session variables  [b]$_SESSION["valid_id"] = $obj->id;[/b]  $_SESSION["valid_user"] = $_POST["username"];  $_SESSION["valid_time"] = time();

it registres if the login is valid.. then fix so that the sessions register the logins so that when you got to a protected page " also can only be accessed if you have loged in" a basic a login is made with session with a slighly cookies mix :D.. so

$_SESSION["valid_id"] = $obj->id;[/b] // basicly stores the id..
$_SESSION["valid_user"] = $_POST["username"]; / this makes the valid_user to your user name
$_SESSION["valid_time"] = time(); // this input the time mby when you loged in..

am i right if not.. please say so :P

did you understand now =D?
Edited by coldasice (see edit history)

Share this post


Link to post
Share on other sites

Includes

Php Simple Login Tutorial

 

Make sure that you are not including any files from another directory. I was including dbconfig from /includes/dbConfig.Php and it would not work. I have no idea as I am a total novice to php, but maybe someone else can explain this.

Share this post


Link to post
Share on other sites

php code not working

Php Simple Login Tutorial

 

<?// Replace the variable values below// with your specific database information.$host = "localhost";$user = "UserName";$pass = "Password";$db   = "dbName";// This part sets up the connection to the // database (so you don't need to reopen the connection// again on the same page).$ms = mysql_pconnect($host, $user, $pass);If ( !$ms ){Echo "Error connecting to database.and";}// Then you need to make sure the database you want// is selected.Mysql_select_db($dbUsers);?>
How do I set the variables to my own? EXPLAIN GOOD PLEASE

 

-ryanreese

Share this post


Link to post
Share on other sites

How to create a login form for different users.

Php Simple Login Tutorial

 

I have created a password.Php file and the following code init :

 

<?

$USERS["username1"] = "password1";

$USERS["username2"] = "password2";

$USERS["username3"] = "password3";

 

Function check_logged(){

global $_SESSION, $USERS;

if (!array_key_exists($_SESSION["logged"],$USERS)) {

header("Location: login.Php");

};

};

?>

Above code creates an $USER array with 3 username/password combinations. Now it created a login page (called login.Php) where users will enter their username and password and will login.

 

<?

Session_start();

Include("passwords.Php");

If ($_POST["ac"]=="log") { /// do after login form is submitted

if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted username and password exist in $USERS array

$_SESSION["logged"]=$_POST["username"];

} else {

echo 'Incorrect username/password. Please, try again.';

};

};

If (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not

echo "You are logged in."; //// if user is logged show a message

} else { //// if not logged show login form

echo '<form action="login.Php" method="post"><input type="hidden" name="ac" value="log"> ';

echo 'Username: <input type="text" name="username" /><br />';

echo 'Password: <input type="password" name="password" /><br />';

echo '<input type="submit" value="Login" />';

echo '</form>';

};

?>

 

 

Now when I'm trying to enter username and password it shows me Invalid username and password.Please help me with this script

 

Thanks

 

-reply by Fawaz

Share this post


Link to post
Share on other sites

Answere to multiple logins

Php Simple Login Tutorial

 

Just for anybody who wants to put the login script around places with getting errors or more coding:

<?php echo "<form action="login.Php?op=login" method="POST">"; echo "Username: <input name="username" size="15"><br />"; echo "Password: <input type="password" name="password" size="8"><br />"; echo "<input type="submit" value="Login">"; echo "</form>";?>

The link may change for name or location of login.Php!Yay!

 

-reply by The Answere

Share this post


Link to post
Share on other sites

No Security

Php Simple Login Tutorial

 

Great tutorial, but you should also explain how to prevent SQL Injection (which I forgot how to do), as well as md5 encrypting the passwords, at minimum. Anyone who adds this should read up on how to md5 encrypt their passwords, or 'hash' the passwords, and how to 'salt' them as well.

 

Overall though, it helped me out a lot, thanks for this great tutorial! I just need to add my own algorithm for the passwords and such.

 

-Chris

 

-reply by Chris

Share this post


Link to post
Share on other sites

No Security (Help)

Php Simple Login Tutorial

 

So, I looked into it, and here's what must be done to secure yourself from these SQL injections. In login.Php, find this:

 

If ($_GET["op"] == "login") {

if (!$_POST["username"] || !$_POST["password"])

 

Now replace it with this. Anything besides A-Z, a-z, or 0-9 will be denied, and the script will let them know that they entered values Not Accepted. You want this since if they can put in characters such as ", ', or ;, it could be very harmful to your databases.

 

If ($_GET["op"] == "login") {

If (preg_match("/[^A-Za-z0-9]/", $_POST["username"]) && preg_match("/[^A-Za-z0-9]/", $_POST["password"])){ echo "Error! You may only enter numbers/letters here";}else{

if (!$_POST["username"] || !$_POST["password"])

 

 

 

 

In addition, you may want to MD5 your passwords. I won't get too far into this. If you're interested in hashing and salting though, take a look at these articles! Make sure that if you want to hash/salt a password that goes into your database, you also hash/salt the password submitted at login the same way, this way, when compared, they are presented as the same codes (if the submitted pass is the real deal)

http://forums.xisto.com/no_longer_exists/

http://forums.xisto.com/no_longer_exists/

 

I hope this helps someone! Great article, I'm just hoping that this can help with security, as your code as some easily made sql injections :P

 

-Chris

 

-reply by Chris

Share this post


Link to post
Share on other sites

Wots wrong with this script?plss help!

Php Simple Login Tutorial

 

Iam using XAMPPLITE version 2.5.Am trying to create a table using PHP but its throwing up an error.The code am using is

 

 

<?php

//connect to MySQL; note we�ve used our own parameters- you should use

//your own for hostname, user, and password

$connect = mysql_connect("localhost", "root", "crazybull") or

Die ("hey loser, check your server connection.");

//create the main database if it doesn�t already exist

$create = mysql_query("CREATE DATABASE userlogin")

Or die(mysql_error());

//make sure our recently created database is the active one

Mysql_select_db("userlogin");

//create "movie" table

$movie = "CREATE TABLE login (

Id int(11) NOT NULL auto_increment,

Username varchar(255) NOT NULL,

Password varchar(255) NOT NULL,

Email varchar(255) NOT NULL,

PRIMARY KEY (movie_id),

)";

$results = mysql_query($movie)

Or die (mysql_error());

Echo "Movie Database successfully created!";

?>

 

And the error is

 

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 7

 

Somebody pls help!

 

-question by Pranav

Share this post


Link to post
Share on other sites

I have been quite busy lately, trying to design and code my site (far from done XD). And after having learned how to make a simple login, I will try to write my own tutorial, for you :P

 

<span style='font-size:14pt;line-height:100%'>the tutorial</span>

 

Step 1:

The first step in designing a member system is to plan out exactly what you need. A common impulse among programmers is to jump right in and start coding. I'll be honest and admit that I'm guilty of this more so than anyone. However, since I'm in control of this conversation (yes!), you'll have it all planned out by reading through this before you even see any code.

 

What will you need to start?

First of all, you need a server that supports a CGI or Server-side language. For this tutorial, it's PHP. I won't be directing any attention to any other language at this time, so although the concepts will be similar, the code will be entirely different than something you might use in Perl or ASP. As a side note, it is possible to perform a member system simply using JavaScript, but it would not be remotely secure because JavaScript is client-side (thus able to be viewed by anyone), and even if you had a one-way encryption script it would not be feasible because of the pain of hard-coding usernames and encrypted passwords into the HTML document.

 

Second, at least for our purposes, you need a database. Preferably MySQL. PHP and MySQL go hand-in-hand, so a lot of servers tend to match the two up. Thus, since we're talking PHP, we may as well talk MySQL.

 

Third, you will need 4 blank PHP web pages entitled: register.php, login.php, members.php, and logout.php. After you have these pages created and open, we're ready to start.

 

Step 2: Database

 

If we want to design a members system, we'll need a database. So all we need to do in this step is to create the table we will use to manage the user's login information. Note that the schema we use here is quite simple, and is only simplified to help you see how it works.

 

Name the table "dbUsers." It will need 4 fields:[I]Name			 Type				 Addition[/I]id				  int(10)			  Primary Key, AUTO_INCREMENTusername			varchar(16)		  Uniquepassword			char(16)		   email			   varchar(25)

Once you've made the database table, you're ready to design and code the registration page.

 

Create a File to Connect to your Database

 

Create a new file and name it dbConfig.php. This file will contain the PHP code that will connect to the MySQL database, and select the correct database. Make sure you have added users to your MySQL database with read/write or admin access, then place this type of code into the dbConfig.php file:

 

<?// Replace the variable values below// with your specific database information.$host = "localhost";$user = "UserName";$pass = "Password";$db   = "dbName";// This part sets up the connection to the // database (so you don't need to reopen the connection// again on the same page).$ms = mysql_pconnect($host, $user, $pass);if ( !$ms )	{	echo "Error connecting to database.\n";	}// Then you need to make sure the database you want// is selected.mysql_select_db($db);?>

Step 3: Register

 

register.php

 

On your registration page, you need to create a web form that will allow the user to plugin a username, password, and their e-mail address. Then, also on your page, add code that runs only when information has been passed via the form. Finally, display a "Registration Successful!" message to the user.

 

<?php	// dbConfig.php is a file that contains your	// database connection information. This	// tutorial assumes a connection is made from	// this existing file.	include ("dbConfig.php");//Input vaildation and the dbase code	if ( $_GET["op"] == "reg" )  {  $bInputFlag = false;  foreach ( $_POST as $field )	  {	  if ($field == "")	{	$bInputFlag = false;	}	  else	{	$bInputFlag = true;	}	  }  // If we had problems with the input, exit with error  if ($bInputFlag == false)	  {	  die( "Problem with your registration info. "	."Please go back and try again.");	  }  // Fields are clear, add user to database  //  Setup query  $q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "	  ."VALUES ('".$_POST["username"]."', "	  ."PASSWORD('".$_POST["password"]."'), "	  ."'".$_POST["email"]."')";  //  Run query  $r = mysql_query($q);    // Make sure query inserted user successfully  if ( !mysql_insert_id() )	  {	  die("Error: User not added to database.");	  }  else	  {	  // Redirect to thank you page.	  Header("Location: register.php?op=thanks");	  }  } // end if//The thank you page	elseif ( $_GET["op"] == "thanks" )  {  echo "<h2>Thanks for registering!</h2>";  }  //The web form for input ability	else  {  echo "<form action=\"?op=reg\" method=\"POST\">\n";  echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";  echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16\"><br />\n";  echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";  echo "<input type=\"submit\">\n";  echo "</form>\n";  }	// EOF	?>

Step 4: Login

 

login.php

 

Now in PHP, first we need to check the username and password against the information stored in the database. Since when the user registered, we encrypted their password using the MySQL PASSWORD() function, we re-encrypt the password the user supplied in the login form and cross-check this with the existing value in the dBase. If login information is O.K., then we need to use sessions to store the user's ID so they can access member-only content.

 

<?php	session_start();	// dBase file	include "dbConfig.php";	if ($_GET["op"] == "login")  {  if (!$_POST["username"] || !$_POST["password"])	  {	  die("You need to provide a username and password.");	  }    // Create query  $q = "SELECT * FROM `dbUsers` "	  ."WHERE `username`='".$_POST["username"]."' "	  ."AND `password`=PASSWORD('".$_POST["password"]."') "	  ."LIMIT 1";  // Run query  $r = mysql_query($q);  if ( $obj = @mysql_fetch_object($r) )	  {	  // Login good, create session variables	  $_SESSION["valid_id"] = $obj->id;	  $_SESSION["valid_user"] = $_POST["username"];	  $_SESSION["valid_time"] = time();	  // Redirect to member page	  Header("Location: members.php");	  }  else	  {	  // Login not successful	  die("Sorry, could not log you in. Wrong login information.");	  }  }	else  {//If all went right the Web form appears and users can log in  echo "<form action=\"?op=login\" method=\"POST\">";  echo "Username: <input name=\"username\" size=\"15\"><br />";  echo "Password: <input type=\"password\" name=\"password\" size=\"8\"><br />";  echo "<input type=\"submit\" value=\"Login\">";  echo "</form>";  }	?>

Step 5: Members Area

 

members.php

 

Now that the user has logged in successfully, and has his id, username, and login stored in session variables, we can start working with member-only content. A major thing to remember is that any page you want to carry session data over to you must declare a session_start(); at the top of your code.

 

<?phpsession_start();if (!$_SESSION["valid_user"])	{	// User not logged in, redirect to login page	Header("Location: login.php");	}// Member only content// ...// ...// ...// Display Member informationecho "<p>User ID: " . $_SESSION["valid_id"];echo "<p>Username: " . $_SESSION["valid_user"];echo "<p>Logged in: " . date("m/d/Y", $_SESSION["valid_time"]);// Display logout linkecho "<p><a href=\"logout.php\">Click here to logout!</a></p>";?>

Step 6: Logout

 

logout.php

 

Ah, although it would be nice if our user's never left our web sites, we should give them to opportunity to log out and destroy the session variables if they so choose. It's quite easy to do, and you can just copy and paste this one.

 

<?phpsession_start();session_unset();session_destroy();// Logged out, return home.Header("Location: index.php");?>

That's about it!. I used many simple examples hoping that you will learn how the internal systems work so you can expand on them and design a system that's just right for your needs. Have fun! ^_^

why that? a CMS system make all for you, try php-fusion or joomla

Share this post


Link to post
Share on other sites

Well there are several reasons why person would want to build their own login system without the need to install large software on their hosting site. Another reason it is a good way to learn how to program in php and be able to pick up on things, like functions if/else statements and stuff like that. Also you could build your own CMS software by using this as part of the scripts. Mind you this would have to be completely rewritten in order to be compatible with php5, and make it more secured as well.

Share this post


Link to post
Share on other sites

i want to know more

Php Simple Login Tutorial

 

I want codes that will be needed at the time of making a web site completely in php. First of all iwant to know that how to make a job site.There you can find login,logout,create a new user,(if any thing filled wrong then it will show you that you have inserted awrong statement in login and new user form)and how to insert intractive dhtml menus and where in php codes.Form validation.How can I know that how mamy users have visited my site.How to send email,upload files , images.How anyone can download a file from a site using php codes.

 

-reply by pratap kumar tripathy

Share this post


Link to post
Share on other sites

Hi, i'm new to php. Actually i was handed with a school project which is to create a e-commerce site. However i have no basic knowledge on php. Right now i'm actually trying to create a login/register page. I tried out your tutorial in the 1st page of this thread but ends up with errors here and there. So if you could provide me with more understanding on these coding, i'll be gratful.

1) I keep getting this error when trying to register... kept trying.. but all it came out was "Error: User not added to database."

2) I have tried creating a user n pass in the database (mysql) and then went on to tried to login.. but all i get was "Sorry, could not log you in. Wrong login information."

And also on top of the login box n password box, there are a few error message:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Inetpub\wwwroot\login.php:4) in C:\Inetpub\wwwroot\login.php on line 5
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\Inetpub\wwwroot\login.php:4) in C:\Inetpub\wwwroot\login.php on line 5

3) On the members page as well:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Inetpub\wwwroot\members.php:10) in C:\Inetpub\wwwroot\members.php on line 11
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\Inetpub\wwwroot\members.php:10) in C:\Inetpub\wwwroot\members.php on line 11

Warning: Cannot modify header information - headers already sent by (output started at C:\Inetpub\wwwroot\members.php:10) in C:\Inetpub\wwwroot\members.php on line 16

4) Logout page display:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\Inetpub\wwwroot\logout.php:10) in C:\Inetpub\wwwroot\logout.php on line 11
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\Inetpub\wwwroot\logout.php:10) in C:\Inetpub\wwwroot\logout.php on line 11

Warning: Cannot modify header information - headers already sent by (output started at C:\Inetpub\wwwroot\logout.php:10) in C:\Inetpub\wwwroot\logout.php on line 16


Notice from rvalkass:

Quotes added around error messages.

Share this post


Link to post
Share on other sites

ahh - thats how you use sessions, i have been using cookies to use to login scripts - no other tutorial gives me info on how to use SESSIONS, great tut, all i really needed to know was the sessions lol. Thanks :lol:

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.