• Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
justsomeguy

PHP Tips and Tutorials

6 posts in this topic

Please send me a PM with any comments, corrections, additions, or requests. Please do not reply to this topic. Replies will be deleted to avoid clutter.Official PHP site: http://www.php.net/PHP Installation Packages: http://www.php.net/downloads.phpPHP Installation Instructions: http://www.php.net/manual/en/install.general.phpPHP Online Manual: http://www.php.net/manual/note: links given to the manual are in English, but the manual can be read in several languagesPlease send me a PM to request specific topics.

5 people like this

Share this post


Link to post
Share on other sites

What is PHP? What can PHP do? Should I use PHP for my project?The most basic common question that people ask about PHP is whether or not they should use it. This question can be answered by you better then most other people, because you know the details of your project. You just need to learn what PHP can do and what it is used for. The best place to get that information is from the PHP manual online. Any PHP beginner and even some novices can benefit from taking the time to read the introduction for the PHP manual. The introduction can be found here:http://www.php.net/manual/en/introduction.phpTake the time to read at least that page, and follow the links on the bottom to learn about what PHP is capable of and to look at the introductory tutorial. PHP is primarily a server-side scripting language that people use to provide the processing power behind interactive websites, but it can also be used for command-line scripting or to make graphical standalone applications.

Share this post


Link to post
Share on other sites

How can I find help with what I'm doing?For complex questions, you will probably find it helpful to post your questions in this forum. However, most questions you can answer yourself more quickly then waiting for someone to answer your question here. My education has given me a lot of good information with regard to programming theory, but every day my primary resource for programming is an online reference. It is important for a programmer to understand the concepts, but programmers are not expected to memorize the language. That is what the online reference is for. You can use the PHP manual online to find information, clarification, and user-supplied tips and examples on any of the language features or functions found in PHP. For information about the language itself, including topics such as variables and constants, control structures like if statements or loops, operators like math operations and comparison, you can check in the Language Reference section of the PHP manual:http://www.php.net/manual/en/langref.phpThe manual also has a section on general security considerations in PHP here:http://www.php.net/manual/en/security.phpAnd there is a section on features that explains some concepts like cookies, sessions, and dealing with file uploads:http://www.php.net/manual/en/features.phpFor questions about specific functions, or even just to find the function you are looking for, you can check the Function Reference:http://www.php.net/manual/en/funcref.phpThe built-in PHP functions are separated into several categories, grouped by purpose. If you wanted to find information about functions that you can use to work with files, such as opening, reading, writing, or deleting files, you would click on the Filesystem Functions entry. For information about functions that you can use to work with dates, you would click on the Date/Time Functions entry. If you know the name of the function you would like information about, you can type the name into the search box to jump to the reference page for that function. The function reference pages will have information about the syntax required to use that function, any prerequisites for using the function, a description of what the function does, examples of how to use it, links to related functions, and user-contributed notes and examples. The user-contributed content in particular can help you solve many common problems, and give you new ideas about how to solve old problems. The online PHP reference is the single most-used resource in my day-to-day programming, it is the first place I go for any questions with regard to the language or its functions.

1 person likes this

Share this post


Link to post
Share on other sites

Processing Forms in PHPForms are the most common means of communication between the user and the server. Information from forms arrives at the server in one of two methods. The first method is through the URL itself in the querystring, and the second method is inside the body of the HTTP request, which is normally transparent to users. When information is passed through the URL the method is referred to as the "get" method, and when information is passed through the request it is referred to as the "post" method. PHP can access information in either place. To specify which method to use with the form, the "method" attribute of the HTML form tag should be set to either "get" or "post".

<form action="index.php" method="get"><form action="index.php" method="post">

The get methodInformation is passed through the URL using the querystring. The querystring begins with a question mark (?) and contains key/value pairs. The keys are separated from the values with an equal sign (=). As an example, the URL for this thread is the following:

http://w3schools.invisionzone.com/index.php?showtopic=12509

The querystring for this page contains a key called "showtopic" with a value of "12509". To pass more then one key/value pair, the pairs should be separated with an ampersand (&). As an example, the URL for this post is the following:

http://w3schools.invisionzone.com/index.php?showtopic=12509&view=findpost&p=67512

This querystring contains the key "showtopic" with the value "12509", the key "view" with the value "findpost", and the key "p" with the value "67512". PHP has access to the querystring through the superglobal array $_GET. The $_GET array is automatically a global variable in every scope and never needs to be declared using the global keyword. To read the above values in the index.php file, the following code could be used:

<?php$showtopic = $_GET['showtopic'];$view = $_GET['view'];$p = $_GET['p'];?>

In this example, the PHP variables $showtopic, $view, and $p would contain the values from the querystring. The post methodLike the get method, PHP has a superglobal array called $_POST to access values passed using the post method. Forms such as login forms, file upload forms, or email forms are typically passed using the post method, since it is often the case that the programmer prefers that the submitted information does not appear in the URL. As an example, a basic login form would contain fields for the username and the password:

<form action="login.php" method="post"><input type="text" name="username"><br><input type="password" name="password"><br><input type="submit"></form>

The login.php page would contain code such as this to retrieve the username and password that were typed in:

<?php$username = $_POST['username'];$password = $_POST['password'];?>

How to determine if a form was submittedIt is often useful for a PHP page to determine if a form was submitted. Some PHP pages perform several functions, and one of them might be to process a form. So, the page needs a way to determine if the form was submitted so that it knows whether or not to process the form. A common way to determine this is to check if a variable in the $_POST array has been set. To do this, you only need to put a name on one of the form elements, such as the submit button:

<input type="submit" name="submit_button">

The PHP page that processes that form can check if the value in $_POST has been set, and if so then the form has been submitted. PHP has the isset function to determine if a variable has been set.

<?phpif (isset($_POST['submit_button'])){  //the form was submitted}?>

More then one form on a pageMany pages contain more then one form, and typically a PHP form handler will be responsible for several different forms. For example, a page called users.php might be responsible for adding a user, editing a user, or deleting a user. The page needs some way to determine not only if a form has been submitted, but which one. The easiest way to do this is to use a hidden form element to tell the page which form has been submitted, or which action to take.

<input type="hidden" name="page_mode" value="add_user">

<input type="hidden" name="page_mode" value="edit_user">

<input type="hidden" name="page_mode" value="delete_user">

The PHP page that processes this form can use a series of if statements or a switch statement to determine which action to take.

<?phpif ($_POST['page_mode'] == "add_user"){  //add the user}if ($_POST['page_mode'] == "edit_user"){   //edit the user}if ($_POST['page_mode'] == "delete_user"){  //delete the user}?>

<?phpswitch ($_POST['page_mode']){   case "add_user":     //add the user   break;   case "edit_user":     //edit the user   break;   case "delete_user":     //delete the user   break;}?>

More then one submit button in a formSome forms contain more then one submit button. A text box on a forum might have one button to submit the post, and one to preview the post. In order for PHP to determine which button was pressed, all buttons should be given the same name with different values.

<input type="submit" name="submit_button" value="Preview Post"><input type="submit" name="submit_button" value="Submit Post">

PHP can determine which button was pressed by checking the value of the "submit_button" key of the $_POST array:

<?phpif ($_POST['submit_button'] == "Preview Post"){  //preview the post}if ($_POST['submit_button'] == "Submit Post"){  //submit the post}?>

1 person likes this

Share this post


Link to post
Share on other sites

I get an error like "Warning: Cannot modify header information - headers already sent..."This warning appears when you try to send a header after you have already sent output to the web browser. Headers are sent when you try to start the session, set a cookie, or use the header function to do something like redirect someone to another page. You cannot set a cookie or send a header after you have already started output on the page. The first time PHP sends any output to the web browser it sends all of the HTTP headers that go along with the response. This means that after sending the headers the first time, if you try to set a cookie or otherwise send a header you will receive the warning message. "Output" includes anything sent using echo or print, or anything that is not inside PHP tags.

<!-- this is sent to the browser as output --> <?php echo "send more output"; ?>

To solve this warning, identify the point at which you send output, and move the code that is sending the header before any output. Ideally, you should have all of your PHP code on the top of your file only, and all HTML code after that. All PHP processing should be finished by the time you start sending output to the browser. The warning message takes this format: Warning: Cannot modify header information - headers already sent by (output started at [output file]:[output line]) in [source file] on line [source line] [source file] is the script that eventually caused the error, this is where the call to setcookie, session_start, or the header function appeared that actually caused the error. The [output file] and [output line] is the location where the output was first sent to the browser which caused PHP to send all of the response headers. In order to solve the error, you need to move your code on [source line] before the code on [output line].

1 person likes this

Share this post


Link to post
Share on other sites

Registering users, logging in, and the sessionThis will be a basic example of registering users and allowing them to log in and log out. User information will be kept track of using the session. Many of the techniques used are just for illustrative purposes, there are usually better ways to handle many of the tasks. For instance, a database class could be used to replace the small database include file used here if more advanced functionality is needed. DatabaseThis will use a MySQL database. This basic example will only use one table with four fields in it. This is the structure of the users table:

CREATE TABLE `users` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,`email` VARCHAR( 255 ) NOT NULL ,`name` VARCHAR( 255 ) NOT NULL ,`password` VARCHAR( 40 ) NOT NULL)

We have an autonumber ID field for the primary key, and fields for email address, name, and password. In this example people will be logging in using their email address. db.phpThe register, login, and index pages all need to access the database so they will all include a file that will allow that. The include file in this example connects to the database server, selects the database, and defines a small wrapper function for queries that uses the connection returned from mysql_connect. You need to fill in the correct database details for your server.

<?php $database_host = 'localhost';$database_user = 'user';$database_password = 'password';$database_name = 'db_name'; $con = mysql_connect($database_host, $database_user, $database_password) or exit(mysql_error());mysql_select_db($database_name, $con) or exit (mysql_error()); function db_query($sql){  return mysql_query($sql, $GLOBALS['con']);} ?>

index.phpTo start, we make an index page called index.php. The index page will start the session using the session_start function, and eventually it will check to see if there is a user logged in. Right now all it will contain are links to register and log in:

<?php session_start(); ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>  <head>	<title>Index</title>  </head>  <body>	Click <a href="register.php">here</a> to register or click <a href="login.php">here</a> to log in.  </body></html>

register.phpThe register page will start as a basic form with fields for email address, name, and password. This is the form layout:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>  <head>	<title>Register</title>	<style type="text/css">	.error_text {	  color: #FF0000;	  width: 400px;	  text-align: center;	}	.left_box {	  float: left;	  width: 150px;	  text-align: right;	  padding-right: 5px;	}	.right_box {	  clear: right;	}	</style>  </head>  <body>	<form action="register.php" method="post">	<input type="hidden" name="page_mode" value="register"> 	<div class="left_box">Email address</div>	<div class="right_box"><input type="text" name="email" size="30" maxlength="255"></div> 	<div class="left_box">Name</div>	<div class="right_box"><input type="text" name="name" size="30" maxlength="255"></div> 	<div class="left_box">Password</div>	<div class="right_box"><input type="password" name="password" size="30"></div> 	<div class="left_box">Confirm Password</div>	<div class="right_box"><input type="password" name="conf_password" size="30"></div> 	<div class="left_box"> </div>	<div class="right_box"><input type="submit" value="Register" size="30"></div> 	</form>  </body></html>

The form contains a hidden input element called "page_mode" that has the value "register" that will be used to determine if the form was submitted. When the form gets submitted we will need to connect with the database, initialize some variables, and process the form. This is what we start with:

<?php require_once 'db.php'; $page_mode = isset($_POST['page_mode']) ? $_POST['page_mode'] : ''; $error_string = ''; if ($page_mode == 'register'){  // process form} ?>

First the database file gets included. Next, the $page_mode variable gets set to the value of $_POST['page_mode'] if it was set, or the empty string ('') if it was not set. Next we declare a variable to keep track of errors and then set up the if block to process the submitted form. The first step in processing the form is obviously to get the submitted values. I use the trim function on the email address and name to remove any excess whitespace.

if ($page_mode == 'register'){   $email = trim($_POST['email']); // trim to remove whitespace   $name = trim($_POST['name']); // trim to remove whitespace   $password = $_POST['password'];   $conf_password = $_POST['conf_password'];}

Once we have the values from the form we need to validate everything. Since one of the values is an email address, I included a function that uses a regular expression to validate the email address. This regular expression came from http://snipplr.com/v...ail-validation/ and should pick up almost any email address according to the spec, without explicitly checking for specific top-level domain names like com or org. This function definition can go inside an include file or inside the script that uses it:

function isValidEmail($email = ''){   return preg_match("/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix",$email);}

We use that function to test the email address and validate each of the other values. Any error messages go inside the variable that was initialized earlier.

if (!isValidEmail($email))  $error_string .= 'Please enter a valid email address.<br>';if ($name == '')  $error_string .= 'Please enter your name.<br>';if (strlen(trim($password)) < 6)  $error_string .= 'You must enter a password of at least 6 characters.<br>';if ($password != $conf_password)  $error_string .= 'The password and confirmation password do not match.<br>';

At this point the $error_string variable will contain error messages if there were any errors. We can check that variable to determine if we should proceed. If there haven't been any errors yet then we first need to check for duplicate email addresses. If there aren't any duplicate addresses registered, then we add the new information to the database. After that we redirect to a "thank you" page. We use the mysql_real_escape_string function to protect against SQL attacks, and the SHA-1 hash function to hash the password before we store it in the database. The db_query function comes from the db.php file that was already included.

if ($error_string == ''){  $result = db_query("SELECT id FROM users WHERE email='" . mysql_real_escape_string($email) . "'");  if (mysql_num_rows($result) > 0)	$error_string .= 'That email address is already registerd.<br>';  else  {	$email = mysql_real_escape_string($email); // protect against SQL attacks	$name = mysql_real_escape_string($name);	$password = sha1($password); // hash password 	db_query("INSERT INTO users (email, name, password) VALUES ('{$email}', '{$name}', '{$password}')");	header('Location: thankyou.php');	exit();  }}

Now we have the register form, the form processing code, and error messages. We need to modify the page to show error messages if there were any, and we also want to fill in any values back into the form so that the user doesn't need to type everything over again. The email input would be modified like this, so that it checks if the $email variable is set and prints the value if so:

<input type="text" name="email" size="30" maxlength="255" value="<?php if (isset($email)) echo $email; ?>">

With everything combined, the final register.php page looks like this:

<?php require_once 'db.php'; $page_mode = isset($_POST['page_mode']) ? $_POST['page_mode'] : ''; $error_string = ''; if ($page_mode == 'register'){   $email = trim($_POST['email']); // trim to remove whitespace   $name = trim($_POST['name']); // trim to remove whitespace   $password = $_POST['password'];   $conf_password = $_POST['conf_password'];    if (!isValidEmail($email))	 $error_string .= 'Please enter a valid email address.<br>';   if ($name == '')	 $error_string .= 'Please enter your name.<br>';   if (strlen(trim($password)) < 6)	 $error_string .= 'You must enter a password of at least 6 characters.<br>';   if ($password != $conf_password)	 $error_string .= 'The password and confirmation password do not match.<br>';    if ($error_string == '')   {	 $result = db_query("SELECT id FROM users WHERE email='" . mysql_real_escape_string($email) . "'");	 if (mysql_num_rows($result) > 0)	   $error_string .= 'That email address is already registerd.<br>';	 else	 {	   $email = mysql_real_escape_string($email); // protect against SQL attacks	   $name = mysql_real_escape_string($name);	   $password = sha1($password); // hash password 	   db_query("INSERT INTO users (email, name, password) VALUES ('{$email}', '{$name}', '{$password}')");	   header('Location: thankyou.php');	   exit();	 }   }}   function isValidEmail($email = ''){  return preg_match("/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*@[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix",$email);} ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>   <head>	 <title>Register</title>	 <style type="text/css">	 .error_text {	   color: #FF0000;	   width: 400px;	   text-align: center;	 }	 .left_box {	   float: left;	   width: 150px;	   text-align: right;	   padding-right: 5px;	 }	 .right_box {	   clear: right;	 }	 </style>   </head>   <body>	 <div class="error_text"><?php echo $error_string; ?></div> 	 <form action="register.php" method="post">	 <input type="hidden" name="page_mode" value="register"> 	 <div class="left_box">Email address</div>	 <div class="right_box"><input type="text" name="email" size="30" maxlength="255" value="<?php if (isset($email)) echo $email; ?>"></div> 	 <div class="left_box">Name</div>	 <div class="right_box"><input type="text" name="name" size="30" maxlength="255" value="<?php if (isset($name)) echo $name; ?>"></div> 	 <div class="left_box">Password</div>	 <div class="right_box"><input type="password" name="password" size="30"></div> 	 <div class="left_box">Confirm Password</div>	 <div class="right_box"><input type="password" name="conf_password" size="30"></div> 	 <div class="left_box"> </div>	 <div class="right_box"><input type="submit" value="Register" size="30"></div> 	 </form>   </body></html>

thankyou.phpFor this example the only thing this page does is to give the user a link to log in. In other situations it could be used to set cookies or show other information.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>  <head>	<title>Thank You</title>  </head>  <body>	Thank you for registering, click <a href="login.php">here</a> to log in.  </body></html>

login.phpWith the register page in mind, we create the login form with places for the error messages and the auto-complete, but it only needs fields for the email address and password. The initial PHP code is similar to the register.php page, with the addition of the session_start function. Any page that uses the session needs a call to session_start, and this page will be storing user information in the session.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>  <head>    <title>Register</title>    <style type="text/css">    .error_text {	  color: #FF0000;	  width: 400px;	  text-align: center;    }    .left_box {	  float: left;	  width: 150px;	  text-align: right;	  padding-right: 5px;    }    .right_box {	  clear: right;    }    </style>  </head>  <body>    <div class="error_text"><?php echo $error_string; ?></div>    <form action="login.php" method="post">    <input type="hidden" name="page_mode" value="login">    <div class="left_box">Email address</div>    <div class="right_box"><input type="text" name="email" size="30" maxlength="255" value="<?php if (isset($email)) echo $email; ?>"></div>    <div class="left_box">Password</div>    <div class="right_box"><input type="password" name="password" size="30"></div>    <div class="left_box"> </div>    <div class="right_box"><input type="submit" value="Log In" size="30"></div>    </form>  </body></html>

If the form was submitted then again we want to get the submitted values and validate them. For logging in, first we'll just check if they filled out an email address and password at all before checking with the database:

  $email = $_POST['email'];  $password = $_POST['password'];  if (trim($email) == '' || trim($password) == '')    $error_string .= 'Please enter your email address and password.<br>';  else  {    // check db  }

To verify the user, first we send a query to the database for the row that matches the email address. If the query did not return a row then we set an error message, or else we compare the passwords. If everything is OK then we set some variables in the session and redirect back to the index.

    $result = db_query("SELECT id, name, password FROM users WHERE email='" . mysql_real_escape_string($email) . "'");    if (!($row = mysql_fetch_assoc($result)))	  $error_string .= 'The email address was not found.<br>';    elseif ($row['password'] != sha1($password))	  $error_string .= 'The password did not match.<br>';    else    {	  $_SESSION['user_id'] = $row['id'];	  $_SESSION['user_name'] = $row['name'];	  $_SESSION['user_email'] = $row['email'];	  header('Location: index.php');	  exit();    }

With everything combined the login.php page looks like this:

<?phpsession_start();require_once 'db.php';$page_mode = isset($_POST['page_mode']) ? $_POST['page_mode'] : '';$error_string = '';if ($page_mode == 'login'){  $email = $_POST['email'];  $password = $_POST['password'];  if (trim($email) == '' || trim($password) == '')    $error_string .= 'Please enter your email address and password.<br>';  else  {    $result = db_query("SELECT id, name, password FROM users WHERE email='" . mysql_real_escape_string($email) . "'");    if (!($row = mysql_fetch_assoc($result)))	  $error_string .= 'The email address was not found.<br>';    elseif ($row['password'] != sha1($password))	  $error_string .= 'The password did not match.<br>';    else    {	  $_SESSION['user_id'] = $row['id'];	  $_SESSION['user_name'] = $row['name'];	  $_SESSION['user_email'] = $row['email'];	  header('Location: index.php');	  exit();    }  }}?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>  <head>    <title>Register</title>    <style type="text/css">    .error_text {	  color: #FF0000;	  width: 400px;	  text-align: center;    }    .left_box {	  float: left;	  width: 150px;	  text-align: right;	  padding-right: 5px;    }    .right_box {	  clear: right;    }    </style>  </head>  <body>    <div class="error_text"><?php echo $error_string; ?></div>    <form action="login.php" method="post">    <input type="hidden" name="page_mode" value="login">    <div class="left_box">Email address</div>    <div class="right_box"><input type="text" name="email" size="30" maxlength="255" value="<?php if (isset($email)) echo $email; ?>"></div>    <div class="left_box">Password</div>    <div class="right_box"><input type="password" name="password" size="30"></div>    <div class="left_box"> </div>    <div class="right_box"><input type="submit" value="Log In" size="30"></div>    </form>  </body></html>

index.php, part 2Now that we can determine whether or not someone is logged in, we can modify the index.php page to check for that and display the user's name if they are logged in. If not, then the links to register and log in will be displayed.

<?phpsession_start();?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>  <head>    <title>Index</title>  </head>  <body>    <?php    if (isset($_SESSION['user_id']))    {    ?>    Hello, <?php echo $_SESSION['user_name']; ?>, what do you think you're doing?  I'm sorry, <?php echo $_SESSION['user_name']; ?>, I can't let you do that.    <br><br>    <a href="logout.php">Log out</a>    <?php    }    else    {    ?>    Click <a href="register.php">here</a> to register or click <a href="login.php">here</a> to log in.    <?php    }    ?>  </body></html>

logout.phpThe final part of this is the log out page, which is linked to if someone is logged in. All the page needs to do is unset everything that was previously set in the session, and redirect back to the index page.

<?phpsession_start();unset($_SESSION['user_id']);unset($_SESSION['user_name']);unset($_SESSION['user_email']);header('Location: index.php');exit();?>

Hopefully this will give you a basic start for your own application. On any other pages on your website you can use the session_start function to use the session and access the information that you stored in it during the log in process. The session is a collection of data that is kept on the server and is associated with a certain user using a cookie. When the session_start function gets called the server will send the browser a cookie called PHPSESSID by default. Whenever the browser requests a page from the server it will send the session ID cookie back to the server, and the server will use the ID to look up all of the data that it has saved for that user. You can store most types of data in the session such as scalar data (strings, numbers, etc), arrays, objects, etc, but you cannot store resources such as database connections or file connections in the session.

3 people like this

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.