Results

  • Photoshop
  • PHP
  • Linux
  • Photography by John Corney

PHP

Creating a simple password protection

Introduction:

Time to time you may want to protect some of your web pages but you don’t want to setup any complicated system and a database only for this. In this article I will present you a very simple solution how you can do it easily. I know this solution is not the best but some not mission critical cases it can be very useful.

Step 1.

The main idea is to insert only one line of code into each of your web pages you want to protect. This code includes a form processing script at the beginning of your original code. It first displays a small form to enter your password and if it is ok then shows the original page content.

So now we need to create a PHP script with a simple form processing. The form is very simple, only a password field and a submit button is present. The code is the following:

<?php
function showForm($error=“LOGIN”){
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“DTD/xhtml1-transitional.dtd”>
<html>
<body>
<?php echo $error; ?>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post” name=”pwd”>
Password:
<table>
<tr>
<td><input name=”passwd” type=”password”/></td>
</tr>
<tr>
<td align=”center”><br/>
<input type=”submit” name=”submit_pwd” value=”Login”/>
</td>
</tr>
</table>
</form>
</body>
<?php
}
?>

Step 2.

As we don’t want to show the form always we put it inside a function and this function will be called if necessary. The main application logic checks if the form was submitted or not. If not then displays the form else check the entered password. If it fails then informs the visitor and displays the login form again. If the password was right then we do nothing so the rest of the code will be displayed.

Don’t forget that in case of displaying the form we need to exit from the code processing to hide the important page content.

The application logic looks like this:

<?php
$Password
= ‘demo’; // Set your password here

if (isset($_POST[’submit_pwd’])){
$pass = isset($_POST[‘passwd’]) ? $_POST[‘passwd’] : ”;

if ($pass != $Password) {
showForm(“Wrong password”);
exit();
}
} else {
showForm();
exit();
}
?>

As you can see the password is hard coded and exists in human readable format. If you want you can store it in a separate file and encode it for example with md5() function. All is up to you.

Step 3.

Now we are ready with the script. Now if you want to protect any of your pages you need to insert the following line of code at the beginning of your PHP code:

<?php require_once(‘protector.php’); ?>

Speed up your site with caching

As your site is growing you need focus more and more on site performance. If your content is not changing in every minutes but you have a lot of visitors then your webserver is making a lot of unnecessary work. The server processes your PHP scripts always, however the output is the same. Using cache mechanism we will process the script once but use it more times.

 

How it works

 

The cache mechanism is not so complicated. The main idea is that we store the processed output in a file and in case of a new request we check if the file exists or not. If it exists and not to old then we just send the file content to the client. If the file doesn’t exists or to old then we process the PHP script. We can save a lot of time in case of scripts with  intensive database usage. 

 

Implementation 

 

We will create a separate new Cache class which has 3 important functions:

  • starteCache()
  • endCache()
  • cleanCache()

 

The class skeleton

 

Before we begin to implement the functions we need to create the skeleton of the class with the class variables. We need to define class variables to control cache behaviour. See the comments in the code below:

 

<?php

class Cache {
   var 
$status    = true;     // True to switch on cache and false to switch it off
   
var $cacheDir  = ‘cache/’; // The default directory where to store chached files
   
var $cacheFile = ”;       // The content of the actual cached file
   
var $timeOut   = 1000;     // The time how long the cached file remains reusable
   
var $startTime = 0;        // The startime to determine script execution time 
   
var $cache     = true;     // Shows if chaching actual content is needed
   
}
?>

 

Besides the class variables we define an internally used function to measure the time we spent with processing. This is the getMicroTime() function and looks like this:

 

<?php
    
function getMicroTime() {
           list(
$usec, $sec) = explode(“ ”,microtime());
          return ((float)
$usec + (float)$sec);
    }
?>

 

The startCache() function 

Now we can start with the most important function of our class. The use case of the startCache() function is the following:

  • Save actual time
  • Check file existence and age.
    • If file exists and not to old then display its content and exit.
  • If file doesn’t exists then set a caching flag to true.

The code is the following:

 

<?php
   
function startCache(){
      
$this->startTime = $this->getMicroTime();
      if (
$this->status){ 
         
$this->cacheFile = $this->cacheDir.urlencode( $_SERVER[‘REQUEST_URI’] );
         if ( (
file_exists($this->cacheFile)) && 
              ((
fileatime($this->cacheFile) + $this->timeOut) > time()) )
         {
            
//Read file from the cache
            
$handle = fopen($this->cacheFile , “r”);
            
$html   = fread($handle,filesize($this->cacheFile));
            
fclose($handle);
          
            
// Display the content
            
echo $html;

            //Display the rendering time
            
echo ‘<p>Total time: ’
                 
.round(($this->getMicroTime())-($this->startTime),4).‘</p>’;
            
            
//Exit from the code as we displayed cached data
            
exit();
          }
          else
          {
             
// Set to save generated content into file
             
$this->caching = true;
          }
      }
    }
?>

 

The endCache() function 

 

If the actual page was not cached yet and the caching flag is set to true then this function will save the output buffer to a file and of course displays it as well. At the end just for information it displays the total processing time as well. The source looks like this:

 

<?php
   
function endCache(){
      if (
$this->status){
         if ( 
$this->caching )
         {
            
//You were caching the contents so display them, and write the cache file
            
$html = ob_get_clean();
            echo 
$html;
            
$handle = fopen($this->cacheFile, ‘w’ );
            
fwrite ($handle, $html );
            
fclose ($handle);

            //Display the rendering time
            
echo ‘<p>Total time: ’.round(($this->getMicroTime()-$this->startTime),4).‘</p>’;
         }
      }       
    } 
?>

 

The cleanCache() 

This is the last function and it is quite simple. This function only checks the cache directory and removes all of the files in it.

 

<?php
    
function cleanCache(){
       if (
$handle = opendir($this->cacheDir)) {
          while (
false !== ($file = readdir($handle))) {
             if (
is_file($this->cacheDir.$file)) unlink($this->cacheDir.$file);
          }

          closedir($handle);       
       }
    }
?>

 

Usage of the class 

If you want to cache your pages you need to extend your code a bit with the new cache class. It only takes some line of code. First we need to import the cache class and create a cache object afterwards. As we have the object we can call the startCache() function. At the end of the file we need to insert the endCache() function and we are ready.

 

An example code looks like this:

 

<?php
   
require_once(‘cache.class.php’);
   
$CacheManager = new Cache();
   
$CacheManager->startCache();
   
   echo 
“Start Cache example at: ”.date(‘H:i:s’).“<br/>”;
   
sleep(2);
   echo 
“End Cache example at: ”.date(‘H:i:s’).“<br/>”;

   echo “<br/><a href=’clear.php’>Clean the cache</a><br/>”;
   
   
$CacheManager->endCache();
   
?>

Check your server status - a basic ping

In this tutorial I will show you how to check whether a domain, server is up or down and how fast it is. Generally speaking we will implement a ping command with PHP.

Step 1.
PHP has no built in function for the ping functionality so we need to find a way how to realize it. We want to know two information about the given domain. First of all we want to know whether it is available or not and as second it would be nice to get information about how fast the response is.

The main concept is that we try to connect to the server with socket connection on port 80 and measure the time how long does it take. To do this we will use the built in PHP function fsockopen() which opens Internet or Unix domain socket connection. On depends the return value we can decide whether the actual domain is available at the moment or not.

Let’s do some coding.

Step 2.
First we will implement the main function which will get a domain name as parameter and try to open it. The function will returns with the response time if the connection was success and -1 in other case. The function makes no input validation so it must be done before calling it. I will show it later.

Let’s see the main steps:

  • Save current time as startTime
  • Try to connect to the domain
  • Save current time again as stopTime
  • Check the return value
    • In case of error return with -1
    • In case of successfully connection calculate the time in ms and return with it.

The code looks like this:

<?php

// Function to check response time
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;

if (!$file) $status = -1; // Site is down
else {
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return
$status;
}
?>

Step 3.
Now let’s create some usable environment for our function. It means that we will create a HTML form where the visitor can define the domain name in a normal text field. As action parameter we will call our script again. I use no any special formatting and CSS to make this example as simple as it can be and focus only on the main topic.

The resulted form is quite simple:

<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post” name=”domain”>
Domain name:
<table>
<tr><td><input name=”domainname” type=”text” ></td></tr>
<tr><td><input type=”submit” name=”submitBtn” value=”Ping domain”></td></tr>
</table>
</form>

During the form processing we need to validate the domain name. In this case it means that to be sure we remove the http:// prefix if it was submitted with the domain name. Here you can add more validation routines if you want. Now we can call the above implemented function with the given domain and display the result depending on the return value.

<?php
// Check whether the for was submitted
if (isset($_POST[’submitBtn’])){
$domainbase = (isset($_POST[‘domainname’])) ? $_POST[‘domainname’] : ”;
$domainbase = str_replace(“http://”,“”,strtolower($domainbase));

echo ‘<table>’;

$status = pingDomain($domainbase);
if (
$status != -1) echo “<tr><td>http://$domainbase is ALIVE ($status ms)</td><tr>”;
else echo
“<tr><td>http://$domainbase is DOWN</td><tr>”;

echo ‘</table>’;
}
?>

And we are all done.

The complete code looks like this:

<?php
// Function to check response time
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;

if (!$file) $status = -1; // Site is down
else {
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return
$status;
}
?>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “DTD/xhtml1-transitional.dtd”>
<html>
<body>
<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post” name=”domain”>
Domain name:
<table>
<tr><td><input name=”domainname” type=”text” ></td></tr>
<tr><td><input type=”submit” name=”submitBtn” value=”Ping domain”></td></tr>
</table>
</form>
<?php
// Check whether the for was submitted
if (isset($_POST[’submitBtn’])){
$domainbase = (isset($_POST[‘domainname’])) ? $_POST[‘domainname’] : ”;
$domainbase = str_replace(“http://”,“”,strtolower($domainbase));

echo ‘<table>’;

$status = pingDomain($domainbase);
if (
$status != -1) echo “<tr><td>http://$domainbase is ALIVE ($status ms)</td><tr>”;
else echo
“<tr><td>http://$domainbase is DOWN</td><tr>”;

echo ‘</table>’;
}
?>
</body>

Beginners Guide To PHP

What is PHP?

PHP originally stood for Personal Home Page, it was created in 1994 by Rasmus Lerdof to the visitors to his online resume. It in time grew in capabilities and popularity. As this occurred PHP became known as PHP: Hypertext PreProcessor. This means that PHP handles data before it becomes HTML.

Why use PHP?

I can’t put it more simply than, PHP is better, quicker and easier to learn than any alternative

How PHP works?

PHP is a server-side language. This means that the code you write in PHP resides on the host computer/server that serves the Website. The computer/server reads the PHP code and processes it according to the PHP directions. PHP creates a HTML page based upon the paramounts you set in the PHP code, so the actual PHP code contains no static HTML. This differs from a HTML generated site.

What Is The Syntax Like?

PHP is similar in structure to Perl and C. You use curly braces { } to define blocks of code, and the semi-colon to specify the end of a statement. Having a knowledge of Perl is a good basis to learn PHP. It has all the similar if/else, loops, subroutines that are standard with any programming language.

An Example of PHP code


<?php
function hello($name)
{
return
‘hello ‘ . $name;
}
?>
<html>
<head>
<title>My First PHP Page</title>
</head>

<body>
<?php echo hello(’world’); ?>
</body>
</html>

What you’ll Need

Well the first obvious need is access to a PHP-enabled server. Your ISP or webhost should be able to help you with this, or you could locally host it.
The second need is some form of text-based editor. I personally use Editplus i’ve used it for along long time, i have tried pretty much every other popular text editor and found that Editplus fits my needs exactly.

Thirdly you will require an FTP program, i suggest FlashFXP if on windows or Transmit if your on a mac, to enable you to upload your scripts. However if your hosting them locally you do not require and FTP program.

You will also require good reference books around you, this is for PHP and HTML and no matter how good you are at programming you will at some point need to pickup a good book.

Where to go from here

Well simply go start coding! Look at tutorials use the PHP.net site to help you with different functions. Go now! It’s your chance to conquer to PHP world!

Thank you for reading

Copyright MMVII Go3 Media