Archive for the ‘PHP Tutorials’ Category

Apr 17 Integrating Wordpress into dynamic templates Posted at 3:52 pm | No Comments »

I installed a Wordpress blog on my development server the other day and began playing with it. The first real challenge I faced was how to pull my Wordpress installation into my Web site’s template.

My issue is, I’m using a content management system (CMS) to manage the bulk of my Web site’s content. However, I wanted to use Wordpress to manage my various blogs. I obviously wanted my blogs to look like the rest of my Web site, so I needed to come up with a plan to integrate my Wordpress installation into my CMS, somehow.

Basically, what it came down to was that I needed to find a way to store all of my Wordpress output into PHP variables. Once I had done that, I could plug those variables into my template. The main problem I ran across, however, was the fact that 99% of the functions Wordpress uses to build its output utilize echo commands rather than simply returning the output.

That was no good for me, obviously, as it started printing content onto my page before the template had been processed.

PHP came to my rescue, and with very little headache. PHP’s output buffer was the simple answer to my problem.

(more…)

Mar 15 Running PHP Scripts with Cron Posted at 5:01 pm | 4 Comments »

Lots of programmers like PHP for its ability to code and develop web applications fast. Code-debugging is a lot easier than with PERL or C. However, there is one thing a lot of developers are puzzled about, “How to run PHP Scripts with crontab?”

Cron is normally available on all Unix and Linux distributions; if you cannot access it, contact your root or server administrator. It is a daemon which allows you to schedule a program or script for a specific time of execution. If you want to learn more about cron, click here or type “man crontab” at your command prompt.

I have found myself in the need to run PHP scripts at specific times. For example, to update the content of a website, to remove expired articles, to send out e-mails on a given date and a lot more. While some may think that this is were PHP is doomed, I will show you how it’s done.

A Manual crontab?

The first solution that came to my mind was to run the script directly from my browser (e.g. http://www.mydomain.com/script.php). Since I need to run my script on a regular basis, I squashed that idea. My goodness, all the extra hassle is ridiculous.

(more…)

Feb 23 phpCache — speed up your website Posted at 9:00 am | No Comments »

Caching seems to be the new trend. But aside from all the marketing, it’s really a lot more than that. If you don’t have the money to buy those lovely Zend products, you might find yourself turning to the world of Open Source (again). And viola! You’ll be helped.

There are two ways to cache with PHP - as far as I know -, one is using PEAR’s Cache_lite class. There’s an article already about it on Devshed, but since someone already spoiled it and I am not too much of a pear-lover myself (I like wine-berries, oranges and stuff), I’ll talk about phpCache. So here we go.

So, at first we’ll start with the principals. What does this caching thing do? And why do I want it?
Caching is used in a million things. For example, there is your browser’s cache, which saves a website to your harddrive so next time, you go to this website, it’ll come up a lot more faster on your screen. Your ISP probably also offers caching through a proxy server. In this case, highly frequented websites are downloaded to the ISPs proxy server and delivered to you a lot faster than if you would go to the site directly. Thumbnails of larger images are a way of caching too.

In this case, phpCache will save the contents of a so called “dynamic website” to the filesystem and read it until the scripts says, “Outdated!”, and regrabs the contents from the database to store them in the filesystem again, and again, and again. That’s basically how they all work. Basically - without the tech mumbo jumbo!
The reason “Why?!” is that for example if you have a high traffic site and a frontpage that pulls a lot of news from your database, you might run into a small problem. Thousands of visitors come to your site each hour (or minute) and each of those thousand requests equals an SELECT-statement which pulls the desired information from your database. The pulls equal load on the database which in return consumes memory and CPU and we would like to stay as slim as possible, won’t we?

Now that we found out, that we want to cache and since we have the latest package of phpCache handy, let’s hop on the shell and get the magic going.

Get the party started!

phpCache is a small little something, that can be found at http://0×00.org/php/phpCache/. Go there, grab the latest version and off we go.

On my servers, I like to organize my webs in the following manner:

/web/htmlcenter.com/
/web/htmlcenter.com/forums/
/web/htmlcenter.com/forums/docroot/
/web/htmlcenter.com/forums/logs/
/web/htmlcenter.com/www/
/web/htmlcenter.com/www/docroot/
/web/htmlcenter.com/www/logs/
...

The reason why I do it, I like to have everything that belongs to a web in one place. Whenever I need to get rid off a web, or in case of a backup, I just delete or tar the directory and get virtually everything that belongs to the web. In my case, everything except the database and mail.

Now that we downloaded the archive into /web/htmlcenter.com/forums/, we’ll extract it.

shell# tar zxvf phpCache1.4.tgz
phpCache-1.4/
phpCache-1.4/ChangeLog
phpCache-1.4/KentuckyFriedCache.pl
phpCache-1.4/LICENSE
phpCache-1.4/README
phpCache-1.4/gc.php
phpCache-1.4/phpCache.inc
phpCache-1.4/demo/
phpCache-1.4/demo/all.php
phpCache-1.4/demo/eatCPU.inc
phpCache-1.4/demo/expire_every10s.php
phpCache-1.4/demo/expire_mtime.php
phpCache-1.4/demo/pager.php
phpCache-1.4/demo/session.php
phpCache-1.4/demo/simple.php
phpCache-1.4/demo/thumbnails.php

(Hint: 1.4 was the latest version when I wrote this article.)

To make it look more pretty you can use the following:

shell# mv phpCache-1.4 phpCache

Which renames the directory. And makes it more easy to remember the name.
If you’d like to change the path, where phpCache saves the files to, you should use your favorite editor (vim, vi, pico, ee, joe, …) and edit phpCache.inc. If you can live with /tmp/phpCache, you keep it that way. Since I like to keep everything together, I adjusted the path to /web/htmlcenter.com/forums/phpCache/cache/ and saved the file.

If you create another directory, make sure that you set the correct permissions. In general:

chmod 777 directory_name/

Since the directory that we create for phpCache needs to be writable for everyone, I like to keep it outside the document root. Otherwise, people who go to my website could exploit the fact that a directory, that is writable for everyone is accessable to the public. Of course there is not just one way of doing it, but keeping the cache outside the document root might just be the most easiest/convenient one.

Cache it, baby!

Now, let’s assume, our script looks the following:

// pull the three latest records
$query=”SELECT title, id, teaser FROM news ORDER BY date DESC LIMIT 3″;
// execute query
$rawdb=@mysql_query($query);
// check if the query was successful AND if it returned records
if($rawdb AND @mysql_num_rows($rawdb)>0){
  // outputs the records
  while($array=@mysql_fetch_array($rawdb)){
    extract($array);
    echo ‘
include(’../path/to/phpCache.inc’);
if(!($et=cache(60)){ // We’ll cache the database output for 60 seconds. :-)
  $my_news=array(); // Create an array to store the news in
  $query=”SELECT title, id, teaser FROM news ORDER BY date DESC LIMIT 3″;
  $rawdb=@mysql_query($query);
  if($rawdb AND @mysql_num_rows($rawdb)>0){
    while($array=@mysql_fetch_array($rawdb)){
      extract($array);
      // store the info in the array
      // the info is appened
      $my_news[]=htmlentities(’     endcache();
  }else{
    if(!$rawdb){
      echo ‘Error: ‘.mysql_error().’
Query: ‘.$query;
    }else{
      echo ‘No news…’;
    }
  }
}
/*
  debugging
  echo ‘The cache expires in ‘.$et.’ seconds!’;
*/
// output the cached array
for($i=0;$i<;count($my_news);$i++){
  echo $my_news[$i]; // prints the news
}
// That’s all folks!
?>

So what did we do?

At first, we’ll check if the cache that was created still fits our needs or if it’s too old already. If the cache is just fine, we’ll skip to the output. If the cache is too old, we’ll pull the records once more from the database, store it into the array, cache the array and continue to the output.

Where do we go from here?

Well, at first you should eliminate the bottlenecks on your site. While phpCache comes in handy when you cache database queries and lookups, you shouldn’t use it as an excuse for your poor SQL skills. Whatever type of SQL you use, always debug (check the index, query speed, …). Depending on your type of SQL there might also be a thing called “Query Cache”, consult your manual and read up on it, if you are lucky to have it.

Maintainance?

phpCache comes with a neat little script called “gc.php”. It’s meant to clean up the cache it created. As the author put it, “Running this once a day is recommend.”. If you have questions about how to run PHP scripts with cron, check my
“Running PHP Scripts with Cron Tutorial”.

Jan 20 PHP Form Validation Posted at 9:59 pm | 1 Comment »

Want to learn more about Web Technology? Check out the new HTMLCenter Blog!

The validation of data that has been entered in a form is necessary in most cases. Why is important? For example, what good is holding a contest or sweepstakes if you can’t notify the winner, because he or she entered an invalid telephone number or an incorrect address. What good is having a mailing list if the e-mail addresses on it aren’t verified, and your mailing list just bounces back to you without reaching the subscribers and target audience.

Validating form entries saves you time and more importantly, it can save you money. And since somebody embossed the slogan “Time is money!”, this should be very important for your web site!

Well when should we validate? There are two types of validation; client side and server side.

For reference, client side means that you are depending on what browser the user is currently using. On the client side, validation is performed using JavaScript. And that can be very tricky, because some users turn off JavaScript support in their browsers before they even come to your site. If you encounter of one those users, client side validation won’t help you much if you try to verify data from a form because your JavaScript code will not be executed or interpreted by the browser, means you are back to square 1. Remember, the winner of your competition entered a wrong address.

This is where server side validation comes in handy. It will always work, no matter what. Of course assuming that you have access to the technology on your server. Server side validation can be done with Perl, PHP, ASP, ColdFusion, JSP and almost any other scripting language. For this tutorial, I’ll use PHP. A quite popular and easy to master server side scripting language.


Now that you know the differences between client side and server side validation, you might ask, “Why use client side validation at all?” The reason is, that especially high traffic web sites, should seize the opportunity to take off the load of the server and distribute it to the client browser. This means that if you can verify the content of a field before it is submitted and processed by the server, it makes sense to do so. And there is a user friendly side of it as well. Since most people assume that once they have clicked the submit button on a form, the process is over. A nifty popup explaining what is missing or incorrect, improves their chance of entering correct data into the form. Who wants to miss out on that lottery jackpot just because he or she forgot to verify the data they entered on an online entry form.

Enough explanation, now let’s examine the code. We’ll start with server side validation.

Server side validation with PHP

For one of my last projects, I decided to use the following validation. I checked with JavaScript if anything was inserted in a field and the used server side validation to figure out if the content was ok.

Let’s start off with my favorite server side validation. I am verifying a field for numbers only (e.g. a zip code), numbers and spaces (e.g. a telephone number), etc. Here’s my setup; I have a form.php and a error.php.

form.php

<html>
<head> ...</head>
<body>
<form action="error.php" method="post">
<table>
<tr><td>Your name:</td><td>
<input type="text" name="your_name"></td></tr>
<tr><td>Your phone:</td><td>
<input type="text" name="your_phone"></td></tr>
<tr><td>Zip code:</td><td>
<input type="text" name="your_zip"></td></tr>
</table> <br>
<input type="submit">
</form>
</body>
</html>

Pretty easy, eh? The table is not necessary, but it helps to make the form look nice.

error.php

<?php
extract($_POST);
/* Validation */

function check_field1($field_name_1)
{
  if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\
   ]+$/s",$field_name_1))
    return TRUE;
  else
    return FALSE;
}

function check_field2($field_name_2)
{
  if(!preg_match("/[^0-9\ ]+$/",$field_name_2))
    return TRUE;
  else
    return FALSE;
}

function check_field3($field_name_3)
{
  if(!preg_match("/[^0-9]+$/ ",$field_name_3))
    return TRUE;
  else
    return FALSE;
}

/* Validation */

$error=0; // check up variable

/* get it checking */

if(!check_field1($your_name))
{
  echo "Illegal input $your_name in 'your_name'";
  $error++; // $error=$error+1;
}
if(!check_field2($your_phone))
{
  echo "Illegal input $your_phone in 'your_phone'";
  $error++;
}
if(!check_field3($your_zip))
{
  echo "Illegal input $your_zip in 'your_zip'";
  $error++;
}

if($error == 0)
{
  echo
  "
  The data you entred was correct, thank you!<p>
  Your data:<br>
  Your name: $your_name<br>
  Your phone: $your_phone<br>
  ZIP code: $your_zip
  ";
}else{
  echo "Number of errors: $error";
}

?>

Now for the code explanation. First of all, we have three functions to do the error checking. All three utilize a PHP function called preg_match (http://www.php.net/manual/en/function.preg-match.php). We call the function, tell it what field to check and when the entered data matches the string it looks by it returns true, or false if it doesn’t.

If the function returns true it does nothing, if it returns false, it outputs the error message and increments the value of $error by 1.

Now what’s that really do?


/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/

The slashes “/” and “/” are delimiters, “^” marks the start of string or line and the Dollar sign “$” the end of the string, or line. The plus-symbol “+” means required.

Knowing what the special characters mean, it actually says the following: A string, from start to finish, may contain this characters (a to z (lower case), A to Z (upper case), the numbers from 0 to 9, a dot (”.”), a hiven (”-”) and the special characters ä, ö ü (both upper and lower case) and space (” “)), and these characters only.

preg_match() is a case sensitiv function, which means it treats “a” and “A” differently. I included upper (”A-Z”) and lower case (”a-z”). So called “special characters” (Special, because they have another meaning in PHP as well. But that’s another story.) have to be escaped, which means you write a backslash in front of it. For example: \- (the hiven) or \. (the dot). Other special characters are: “^[$()|*+?{\”.

The other two functions are self explanatory, as they check only for numbers, and numbers and space (”\ “).

I hope you have learned the basics of server side scripting. Feel free to use the above code on your web site. If you need any more help, post a message in our discussion area.

Jan 20 Hotlink Protection with PHP Posted at 9:58 pm | 1 Comment »

What is Hotlinking?

Hotlinking is when another website links directly to one or more of your images or multimedia files and includes it on their web page. Not only is this theft of your intellectual property, but further more, you are paying for the bandwidth used by that site. Which can result in a problem with your budget.
The most common way to prevent others from hotlinking your content is Apache’s mod_rewrite. While this a solution that free available to use, there are a couple drawbacks. One being, that Apache has to be configured to use mod_rewrite (–enable-rewrite). Another one being, that for a lot of people writing regular expressions is not the most easiest thing to do.

Of course there are commercial solutions to the problem. Probably the most common one is cPanel. An administration interface for webserver, which let’s you create all the necessary items for your hotlink protection with a matter of clicks, in a matter of seconds.

Problems with common Hotlink Protection

While it may certainly sound promising to take the steps necessary to stop other sites from leaching your bandwidth, there are issues that can come about as a result. There is one major setback to all the server to prevent hotlinking that I have come across, and that is they all rely on using the HTTP_REFERER environment variable to work.

The main problem these days is that people are becoming more and more cautious about the way that web sites use their information. If you do decide to implement anti-leaching techniques that rely on the referer on your site then you should be aware that you could be blocking otherwise legitimate requests. A visitor who chooses to block or cipher their browsers HTTP_REFERER may have come from a page within your domain, but yet they will pass on any recognised values to the server and therefor will be stopped from viewing your images or downloading your files.

My approach to hotlinking

Whenever a surfer enters one of my websites, I always assign a session to him. The session holds a couple infos, for example: agent, IP, language, date, … etc., and gets passed along via cookie or via GET (as parameter to each one of my pages).

Since I deal with a lot of image content, I started databasing my collection. Which basically means that for administration and clustering purposes, I am saving all my images to a SQL database which is multi-homed and spread accross several servers. One could argue if that is a smart thing to do, but we can argue that on another day and in another article.

I wrote a little script which is used throughout my site:

<img src="/display.php?id=34" border="0">

With an ever changing ID of course. That’s the part referencing my images in the database.
The following is the code from the script which I use to retrieve the image from the database:

<?

$connection=@mysql_connect(...);

@mysql_select_db(...);

$query="SELECT mime, file FROM images 

WHERE id=".$_GET["id"];

$rawdb=@mysql_query ($query,$connection);

if($rawdb AND @mysql_num_rows($rawdb)>0){

  $array=@ mysql_fetch_array($result);

  if (!empty($array["fileContents"])){

    // Output the MIME header

    header("Content-Type: ".$array["mime"]}");

    // Output the image

    echo $array["file"];

  }else{

    // something else...

  }

  @mysql_free_result($rawdb);

}else{

  // something else...

}

@mysql_close($connection);

?>

Since I already have a session for each user that comes to my website, I just added the following:

<img src="/display.php?id=34&sid=383829" border="0">

And implement a small session checkup in the script itself:

<?

session_start();

if($_SESSION["is_known"]){

  // do database calls

}else{

  header("Location:http://mydomain.tld/dontsteal.html");

}

?>

The main advantage to my method is, that the session is entirely server side. A user can not rid himself off it, or fake information. Since I have a timeout and save all the necessary info (IP!) to validate against, it looks pretty perfect to me and fit my needs.

One of the setbacks here are resources and performance. But since I am not forcing you, you may test and evaluate. Hope that helps!

Jan 20 PHP Form Validation - Part II Posted at 9:57 pm | No Comments »

In this tutorial, we will show you how to validate an email address using PHP. PHP is a server-side technology, which is not dependant on the user like client-side validation is.

First, let’s begin with a very simple form where we ask the visitor to supply an email address. A real world example could be a form used to subscribe or unsubsribe from your newsletter and since newsletters are delivered to an email address we would not want to collect anything but a valid email address.

The only real disadvantage to the method I am about to describe is that we will not verify if the email address itself is valid and if it really exists but we will check its formatting, which works well in over 90% of all cases.

To check if an email address really exists, there are ways to query the mailserver - though those do not work in many cases because it also opens the door for spammers - or the more popular method called “double-opt-in”, which involves sending an email to the subscriber with a mandatory action - for example, to click a link, or a reply - to confirm subscription or unsubscription from a service. Confirming a subscription is part of the CANSPAM act.

For purposes of this tutorial, newsletters and CANSPAM are not the objective, so let’s get started with the form.

<html>
<head></head>
<body>
<form action="handler.php" method="post">
<label for="the_email_id">Email</label>:<br />
<input type="text" name="the_email"
id="the_email_id" size="20" maxlength="60" /><br />
<input type="submit" name="submit_btn"
value="check email address" />
</form>
</body>
</html>

The form is fairly self-explanatory, a single text field and a submit button. The script to handle the validation process will be named “handler.php”, as the form’s “action” suggests.

Here is the script:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
  die('No post.');
}
$email = (string) $_POST['the_email'];
if (empty($email))
{
  die('You did not enter anything. Please go
<a href="javascript:history.back(-1);">back</a>.');
}
if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+
(.[a-z0-9-]+)*(.[a-z]{2,4})$", $email))
{
  die('Your email address does not follow the
basic format. Sorry, please try again!');
}
echo sprintf('Your email address "%s"
looks valid. Thank you!', $email);

/*
  continue here with further processing, for example
subscribe/unsubscribe process
*/
?>

Now let’s walk through this piece of code step by step.

At first, we verify that the form was submitted via “post” (remember the HTML?). Why is this important? Well, we do not want people to tinker with our code. Tinkering leads to exploiting, and since we expect the email address to be in PHP’s $_POST (which also hints on a required “post” method), this is a good way to start.

If we pass the “post”-check, we continue to check if anything was entered at all. This is not a necessary step as the following step will catch this as well, but a check performed on empty() is also a lot faster than a regular expression. Doing this gives us the possibility to exit early and actually save resources.

(On a sidenote: This is also a preferred measure when you deal with databases and maybe more critical data on other levels. You always want to verify what you got and if you got anything at all and prevent malicous code from entering further layers of your application.)

Last but not least we use a regular expression to test the format of the string/email supplied by the user.

"^[_a-z0-9-]+(.[_a-z0-9-]+)
*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$"

A more closer look reveals that we allow characters from a to z, 0 to 9, a underscore, hyphen, and a dot to come in front of the “@”-symbol. Following the “@” we basically allow the same, but force an extension in the end. And the extension on email addresses are supposed to be characters only, with a minimum length of two characters and maxmimum length of (currently) four.

Using this full method, we have email validation up and running in virtually no time. The code is small and could be wrapped into a function - which for example returns true or false testing the email address - to refactor the code and could therefore be used inside your existing projects.

KickApps
Clicky Web Analytics

community discussion