Denied access with pure PHP

Written by lexa on December 8, 2009 – 12:05 -

Often you have to protect a directory or website, so that not everybody has access to it. Besides, there are several possibilities as for example using .htaccess, but the best and quickest method as it seems to me is with PHP code.

You create a file with the name login.php, with following contents:

<?php

$user = "test";
$pw = "12345";

function authenticate () {
  Header("WWW-authenticate: basic realm=\"Restricted Area\"");
  Header("HTTP/1.0 401 Unauthorized");
  echo "Restricted Area!";
  exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != $user || $_SERVER['PHP_AUTH_PW'] != $pw) {
  authenticate();
}
?>

Then you have to include the login.php to the top of index.php:

<?php
  include ("login.php");
?>

Thats all! It is important that there are no other index.* files in the directory.


Tags: , , , , ,
Posted in General, PHP | 1 Comment »

Browser detection in PHP

Written by lexa on November 12, 2008 – 22:32 -

browsersIt was short time ago. I was sitting in my room and thinking about browser-problems in this great and sick world. Then I went to the kitchen to make a tea, but made a coffee, because I was thinking about another things. Just like the programmers of the browsers, they wanted to make a best browser ever, but they failed.

So, now about our problem. We want make our application working in all browsers, because it’s good to make it work everywhere. So we have to aks the user agent (basically the client program, not the agent Smith from Matrix), what browser are you using? And we want make it so flexible, that we can ask him this every time. For this purpose we introduce a function:

function getBrowser()
{
  $ua = $_SERVER['HTTP_USER_AGENT']
  if (strstr($ua,'Opera')) {  // Opera
    $browser = ereg_replace(".+\(.+\) (Opera |v){0,1}([0-9,\.]+)[^0-9]*","Opera\\2",$ua);
    if(ereg('^Opera/.*',$ua)) {
      $browser = ereg_replace("Opera/([0-9,\.]+).*","Opera \\1",$ua);
    }
  } elseif (strstr($ua,'MSIE')) { // MSIE
    $browser=ereg_replace(".+\(.+MSIE ([0-9,\.]+).+", "Internet Explorer \\1",$ua);
  } elseif (strstr($ua,'Firefox')) { // Firefox
    $browser=ereg_replace(".+\(.+rv:.+\).+Firefox/(.*)", "Firefox \\1", $ua);
  } elseif (strstr($ua,'Mozilla')) {  //  Mozilla
    $browser=ereg_replace(".+\(.+rv:([0-9,\.]+).+","Mozilla \\1",$ua);
  } else {  // None of them.
    $browser=$ua;
  }
  return $browser;
}

If we want our PHP script to show us the browser, we write:

echo(getBrowser());

Now we can see, what kind of browser is used and use it in our aplication:

if (getBrowser() == 'Internet Explorer 6.0') {
echo ("Please install another Browser");
}

Thats it!


Tags: , , , , , ,
Posted in General, PHP, Web Design | No Comments »