Home arrow PHP arrow Static HTML Generation With PHP
PHP

Static HTML Generation With PHP


In this article Eric, expresses how to may reduce the workload of your server by using PHP to CRON your PHP based web site. He will demostrate how this is done by refering to his own web site.

Author Info:
By: Eric 'phpfreak' Rosebrock
Rating: 4 stars4 stars4 stars4 stars4 stars / 20
April 10, 2003
TABLE OF CONTENTS:
  1. · Static HTML Generation With PHP
  2. · Page 2

print this article
SEARCH DEVARTICLES

Static HTML Generation With PHP
(Page 1 of 2 )

When you are running a large volume website that requires alot of mysql_query action you'll probably want to consider ways to reduce the impact of your server's performance. We can do this by generating static html pages from the pages that require all of these queries.

By writing a few simple PHP scripts you can prepare to CRON your PHP driven site and have it automatically update for you at set intervals. Or you can have direct control over the updates via your web browser. This makes your website run alot faster and reduces your MySQL database queries dramatically.

Let's say that we have a tutorial index just like on phpfreaks.com. This tutorial index starts out by pulling queries for the following:

First Query:

Category ID (auto incremented number)
Category Title
Category Description

Second Query Based on cat_id from First Query:

Tutorial ID (auto incremented number)
Tutorial Title
Tutorial Caption
Tutorial Date
Tutorial Read Count
Tutorial Author ID

Third Query:

Get the Author's Name from the authors table where the author_id FROM second query matches the author's ID in the authors table. (We like to keep this dynamic in case the author changes his/her name later on.)

As you can see, the above queries are not that dramatic. In fact, it's quite a small query compared to some functions that you can get into using PHP and MySQL. Let's think about it this way. I can run this query every single time a reader clicks on our tutorial index page or I can generate a static HTML page that updates every 12 hours to update the information on the index page or I can just let the queries run every time the page is viewed. When you get about 2,000 page views of your index a day, that's about 6,000 queries right there. Why do that when we can do 6 queries a day?

Let's learn how to minimize the impact of your server.

Preparation

Let's start by preparing our web server with the proper directories for this operation to be performed.

First, let's determine where we want our static html to live and where we want our static generator scripts to live. I'll use this example:

/www/htdocs/mysite (Document Root)
-- / static_html (Where static html pages will be copied)
-- / static_genenerator (Where our static generator php scripts will live)
-- / cron_jobs (Where our master cron jobs will live)

The most important step is to get your permissions right or this entire setup will fail due to the fact the server can't write to the directories or files. Here's what I recommend:

chown -R noboby.nobody /www/htdocs/mysite/static_html
chmod +w /www/htdocs/mysite/static_html

Note: your web server may be running as user/group 'apache' instead of nobody. It depends on how you installed Apache. If you have it pre-installed as an RPM, it's probably running as 'apache'. If you compiled from source, the default is 'nobody'. You should check your httpd.conf file to see what user and group your web server runs at.

If you do not have access to change these permissions, try to CHMOD to 775 or at the worse case, 777. Keep in mind that you are opening your web server up for a possible attack by using 777. If all else fails, contact your system administrator and have them set the permissions correctly. I am sure they would not give you any resistance about it.

Build the Script

Now that we have that step completed, we can write our script. Here's the code, I'll break it down on the next page.

<?php
$url = "
http://www.mysite.com
";
$sourcepage = "$url/static_generator/tutorial_index.php";
$tempfilename = "/tmp/temp_tutorials.html";
$targetfilename = "/www/htdocs/mysite/static_html/tutorial_index.html";
if (!$dynamic_source) {
echo "<strong>Unable to load $sourcepage
- Static page! Update Failed!</strong>";
exit();
}
$htmldata = fread($dynamic_source, 1024*1024);
fclose($dynamic_source);
$tempfile = fopen($tempfilename, 'w');
if (!$tempfile) {
echo"<strong>Unable to open temporary file $tempfilename for writing!
Static page update aborted!</strong>";
exit();
}
fwrite($tempfile, $htmldata);
fclose($tempfile);
copy($tempfilename, $targetfilename);
unlink($tempfilename);
echo "<strong>Tutorial Index Updated!</strong>";
?>

Code Breakdown

Ok, I have some explaining to do! Here we go:

$url = "http://www.mysite.com";
$sourcepage = "$url/static_generator/tutorial_index.php";
$tempfilename  = "/tmp/temp_tutorials.html";
$targetfilename = "/www/htdocs/mysite/static_html/tutorial_index.html";
     
This step is preparing the script to use the proper files. I'll show you later on in this tutorial why I use the $url varialbe instead of typing it in to the $sourcepage values

$url variable is the URL of your website without a trailing slash.

$sourcepage is the file that we're going to prepare in the next step that performs all of your MySQL queries and formats your html for you. It should be the file that is currently on your web server.

$tempfilename is the temporary file that we're going to write. The reason why we do this is to not write directly to the page that is being used by the website right now. While you are writing your page, you don't want it being called by the viewer's browser, so we'll create a temporary one and then delete it later after done copying over the current one.

$targetfilename is the actual file being included into your PHP script in place of the $sourcepage that we're working on replacing. I hope you can see where this is going.

$dynamic_source = fopen($sourcepage, 'r'); 

Here we are going open the $sourcepage for reading, we'll also be creating a new operator called $dynamic_source that we can do some error checking and use this fopen function in other places.

if(!$dynamic_source){
echo "<strong>Unable to load $sourcepage 
- Static page! Update Failed!</strong>";
exit();
}

This step performs an error check on the $dynamic_source file to see if we had any problems running the fopen() function in the previous step. Basically if "error" (!) $dynamic_source we'll tell the user: "Unable to load $sourcepage - Static page! Update Failed" and then exit the script.

$htmldata = fread($dynamic_source, 1024*1024);
fclose($dynamic_source);
$tempfile = fopen($tempfilename, 'w');

 
Ok, now we're getting into it!

$htmldata will read the $sourcepage through the fopen() functions defined in $dynamic_source and we'll create a new string out of htis called $htmldata

fclose($dynamic_source); will close out the $sourcepage and end the $dynamic_source operator and we'll begin working on our temporary file with $tempfile.

$tempfile is going to open the $tempfilename that we defined in the first step of this script and write to it with the 'w' in this function. We'll also be creating a new operator to work off of called $tempfile.

if(!$tempfile){ 
echo"<strong>Unable to open temporary file $tempfilename for writing!
Static page update aborted!</strong>";
exit();
}

Just like before, we're going to perform an error checking on this tempfile. If you have your directory permissions set properly, you won't have to create blank files for this step. When you run this script, your web server should create an empty file for you.

fwrite($tempfile, $htmldata);
fclose($tempfile);

     
This step writes the $tempfile with the $htmldata that we recieved from $dynamic_source. AS you can see it's one big chain reaction. After we are done writing the file, we'll close the $tempfile because we don't have it opened any longer.

copy($tempfilename, $targetfilename); 
unlink($tempfilename);
echo "<strong>Tutorial Index Updated!</strong>";

 
Now we'll go ahead and copy the temporary file to the final location where it will be displayed on your web pages.

After we have copied the file over, we'll go ahead and delete the temporary file since it is no longer required until we are ready to run this script again. This unlink() is completely optional and it's not required to make this script run. You can decide if you want to delete the temoporary files or just open them again and rewrite the file when it comes time.

The final step is also optional, echo a success message. Regardless if this fails or succeeds, you'll still see this message so it's up to you to use it.
 
Well, we've got our basic script written. Let's look at how to perform static generation of multiple pages.

Next: Page 2 >>

blog comments powered by Disqus
PHP ARTICLES

- Removing Singletons in PHP
- Singletons in PHP
- Implement Facebook Javascript SDK with PHP
- Making Usage Statistics in PHP
- Installing PHP under Windows: Further Config...
- File Version Management in PHP
- Statistical View of Data in a Clustered Bar ...
- Creating a Multi-File Upload Script in PHP
- Executing Microsoft SQL Server Stored Proced...
- Code 10x More Efficiently Using Data Access ...
- A Few Tips for Speeding Up PHP Code
- The Modular Web Page
- Quick E-Commerce with PHP and PayPal
- Regression Testing With JMeter
- Building an Iterator with PHP

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials