How to Access Cookies & Redirect in PHP

A cookie is a small file that a server stores on a user's PC and that a Web browser sends with every Web page request. Cookies are a useful way for Web applications to store information across pages. In PHP, you might want to access and set cookies, then redirect the user to another Web page, for example after a successful login. You can do this with PHP's built-in cookie and HTTP header functions.

Instructions

    • 1

      Create a new PHP file with an editor or Notepad. Begin the file by buffering the output to avoid error messages from the browser when redirecting or setting cookies. For example, type:

      <?php

      ob_start();

    • 2

      Begin a PHP session if accessing session variables:

      session_start();

    • 3

      Access a cookie by referencing the PHP associative array "_COOKIE" with the cookie name:

      $lang = $_COOKIE['language'];

    • 4

      Set a cookie by calling the PHP "setcookie()" function. Pass the cookie name, value, expiration and the root path so the cookie is available across the entire domain. For example, type:

      if (isset($_SESSION['login_successful'])) {

      setcookie('id', $id, time() + 60*60*24*30, '/');

    • 5

      Redirect the user to another Web page with the PHP "header()" function. Pass "Location: " and the redirect URL:

      header("Location: $URL");

      exit(0);

      }

    • 6

      Flush the output buffer and continue with the Web page. For example, type:

      ob_end_flush();

      ?>

      <!DOCTYPE HTML>

      <html lang="en">

      <head>

      <meta charset="utf-8">

      <title>Page</title>

      </head>

      <body>

      Web Page

      </body>

      </html>

Related Searches:

References

Comments

Related Ads

Featured