Jump to content

PHP Tips and Tutorials


justsomeguy

Recommended Posts

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.

  • Like 5
Link to comment
Share on other sites

  • 9 months later...

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 than 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.

Link to comment
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 than 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.php

The manual also has a section on general security considerations in PHP here:http://www.php.net/manual/en/security.php

And 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.php

For 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.php

The 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.

  • Like 1
Link to comment
Share on other sites

Processing Forms in PHP

Forms 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 method

Information 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 than 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 method

Like 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 submitted

It 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.

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

More than one form on a page

Many pages contain more than 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.

<?php

if ($_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
}

?>
 
<?php

switch ($_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 than one submit button in a form

Some forms contain more than 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:

<?php

if ($_POST['submit_button'] == "Preview Post") {  
  //preview the post
}

if ($_POST['submit_button'] == "Submit Post") {  
  //submit the post
}

?>
 
  • Like 1
Link to comment
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].

  • Like 1
Link to comment
Share on other sites

Registering users, logging in, and the session

 

Note: the information in this post is old and outdated.  Database queries should use PDO or mysqli, not the old mysql extension, and queries with any user data should be prepared statements where the variables are passed as parameters instead of manually escaping data.  Password hashing should be done using password_hash and password_verify, not SHA-1.  Email address validation should be done using filter_var instead of a regular expression.

This 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.

Database

This 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.php

The 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.php

To 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.php

The 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.php

For 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.php

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

<?php

session_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 2

Now 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.

<?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>    
  <?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.php

The 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.

<?php
session_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.

  • Like 3
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...