image


Valora:  3.75/5
Inicio » PHP » PHP Tutorial » Security




Restrict access

In this section we are going to explain how to restrict access depending on the pages, so that only authorized personnel can access certain parts of our website.

Attention: Restricted access to pages using the global variables $PHP_AUTH_USER, $PHP_AUTH_PW and $PHP_AUTH_TYPE only work if PHP has been installed as an Apache module, if it has been installed as a CGI module the examples in this section will not work.

In order to get validation in the pages, we will use the HTTP protocol validation system, this system is based on the global variables $PHP_AUTH_USER and $PHP_AUTH_PW.

  • $PHP_AUTH_USER. Username inserted.
  • $PHP_AUTH_PW. Password inserted.

So the browser shows the window to request username and password, it is only necessary to send the following header:

<?php // Manual de PHP de WebEstilo.com
   if (!isset($PHP_AUTH_USER)) {
      header('WWW-Authenticate: Basic realm="Acceso restringido"');
      header('HTTP/1.0 401 Unauthorized');
      echo 'Authorization Required.';
      exit;
   }
   else {
      echo "Ha introducido el nombre de usuario: $PHP_AUTH_USER<br>";
      echo "Ha introducido la contraseña: $PHP_AUTH_PW<br>";
   }
?>


Execute View code

This causes the user name and password window to appear and the data inserted is assigned to the variables $PHP_AUTH_USER and $PHP_AUTH_PW.

Starting here, we will perform the necessary verification to ensure data inserted is correct.

In the following example, we will request authorization and verify whether the username is Joe and the password 123, if so we will have access to the rest of the page.

<?php // Manual de PHP de WebEstilo.com
   if (($PHP_AUTH_USER!="Joe") || ($PHP_AUTH_PW!="123")) {
      header('WWW-Authenticate: Basic realm="Acceso restringido"');
      header('HTTP/1.0 401 Unauthorized');
      echo 'Authorization Required.';
      exit;
   }
?>

<!-- PHP Tutorial WebEstilo.com -->
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
Ha conseguido el acceso a la <B>zona restringida</B>.
</body>
</html>

Execute View code





WebEstilo.com - Introduzca su e-mail y conozca las novedades. No hacemos Spam.
Google
  Web WebEstilo.com   
 
Valid HTML 4.01!
Última modificación:11 de Mayo de 2009. Spain - España.
© 1998-2004 por Joaquin Gracia. Todos los derechos reservados.