Tag Archives: Apache

Update 2/22/2010: It looks like changing .htaccess is no longer necessary. After you select PHP 5.x, your site will begin using version 5.2.5 without any further configuration.

The following applies to older domains. As of early 2009, newly purchased linux hosting plans are running PHP 5.2.8, while older plans, once updated, only go up to PHP 5.2.5. I’ve had Ardamis.com hosted at GoDaddy since 2005, and quite awhile ago I thought I had upgraded to PHP version 5 from 4.3.11, but tonight I happened to check with phpinfo and found I was still on version 4.

In the unheard of ten minutes that I was on hold waiting for technical support, I figured out how to really run my pages on PHP 5.x (in this case, 5.2.5).

Log in and go to your Hosting Control Center. You must be running Hosting Configuration 2.0 to go any further, so if you haven’t touched your domain in years, do that first.

Click on Content, then Add-On Languages. Next to PHP Version, select PHP 5.x and click Continue. You’ll get a message that “Changing to PHP 5.x may make your PHP files run incorrectly.” Highly unlikely these days, but OK, you’ve been warned. Notice, too that it says “PHP 5.x will be activated“. Click Update.

It may take awhile for this change to be processed by the server, but once your Account Summary is displaying PHP Version: 5.x, it’s time for the really important part.

You see, you’ve only made PHP 5.x available at this point. Your *.php files are still running in 4.x. Go ahead and check phpinfo again.

Now, you could simply edit .htaccess to change the extensions, like so:

AddHandler x-httpd-php5 .php
AddHandler x-httpd-php .php4

More details at http://help.godaddy.com/article/1082

But if you’re squeamish about changing .htaccess yourself, there’s another way to set 5.x to be the default handler for *.php files. All the following does, strangely enough, is to add the AddHandler x-httpd-php5 .php to the beginning of your .htaccess file.

Back in the Hosting Control Center, click on Settings, then File Extension. If the change to 5.x has been completed, you’ll see at the bottom of the available extensions list, “Extension -> .php | Runs Under -> PHP 5.x” If it’s not there, stop here and come back in an hour or so.

Click on Custom Extensions at the left. This should be empty, with a message stating “No custom extensions have been created.”

Click on Default Extensions and then click on the Edit button (it looks like a piece of paper and a pencil) to the right of .php | PHP 5.x. Click on Continue.

Click again on the Custom Extensions button on the left, and you should now see “Extension -> .php | Runs Under -> PHP 5.x”. Check your phpinfo page one more time, and it should report PHP 5.x.

It’s unfortunate we even have to do this for our older domains, but I asked the tech support guy if I could somehow get on to PHP 5.2.8, and he said nope, that the newer servers have the more recent version but the older servers are stuck back in 2007.

This is a collection of php code snippets that seem to come in handy rather often. They are assembled here more for my own organization than anything else.

String: trim and convert to lowercase

A very straightforward but useful snippet. A string is first trimmed of any leading or trailing white space, and then converted to lowercase letters. Good for normalizing user input.

<?php
$string = "Orange";
$string = strtolower(trim($string));
echo $string;
?>

String: truncate and break at word

This will attempt to shorten a string to $length characters, but will then increase the string (if necessary) to break at the next whole word and then append an ellipses to the end of the string. Good for shortening readable text while keeping it looking pretty.

<?php 
function truncate($string, $length) {
	if (strlen($string) > $length) {
		$pos = strpos($string, " ", $length);
		return substr($string, 0, $pos) . "...";
	}
	
	return $string;
}

	echo truncate('the quick brown fox jumped over the lazy dog', 10);
?> 

In the above example, the resultant output will be the quick brown…, because the 10th character is the space immediately before the ‘b’ in ‘brown’, which is counted as part of the word ‘brown’.

What season is it?

Note that this is only a very rough approximation of when a season begins and ends. This snippet would be good for rotating a seasonal background or something, but it’s not astronomically correct, and I wouldn’t use it as a calendar. Reckoning a season is rather complex.

<?php echo "It is day " . date('z') . " of the year. <br />"; ?>
<?php $theday = date('z');
	if($theday >= "79" && $theday <= "171") { 
	$season = "Spring";
	} elseif($theday >= "172" && $theday <= "264") { 
	$season = "Summer";
	} elseif($theday >= "265" && $theday <= "355") { 
	$season = "Autumn";
	} else { 
	$season = "Winter";
	}
	echo "It's " . $season . "!";
?>

Get the number of days since something happened

This function takes a date (formatted as a Unix timestamp) and calculates the number of days since that date. The floor() function shouldn’t really be necessary, but it’s a hold-over from a less accurate function that used only the hours elapsed. In that function, the results would vary depending on the time of day the function was called. In this method, the times are normalized to 12:00:00 AM.

function calc_days_ago($date){
	// The function accepts a date formatted as a Unix timestamp
	
	// First, normalize the current date down to the Unix time at 12:00:00 AM (to the second)
	$now = time() - ( (date('G')*(60*60)) + date('i')*60 + date('s') );
	// Second, normalize the given date down to the Unix time at 12:00:00 AM (to the second)
	$then = $date - ( (date('G', $date)*(60*60)) + date('i', $date)*60 + date('s', $date) );
	$diff = $now - $then;
	$days = floor($diff/(24*60*60));
	switch ($days) {
	case 0:
 		$days_ago = "today";
		break;
	case 1:
		$days_ago = $days . " day ago";
		break;
	default:
		$days_ago = $days . " days ago";
	}
	return $days_ago;
}

Get the hours and minutes remaining until something happens

This function takes a time (formatted as a Unix timestamp) and calculates the number of hours and minutes remaining until that time. If the time has already passed, the function returns “historical”. Example outputs would be “7 hours”, “6 hours and 34 minutes”, and “12 minutes”. It could probably be made even more accurate if you changed it to use 3 decimal places and then round to 2 decimal places, but this is good enough for my purposes.

function calc_time_left($date){
	// The function accepts a date formatted as a Unix timestamp

	$now = time();
	$event = $date;
	if ($event >= $now) {
		$diff = $event - $now;
		$unroundedhours = $diff/(60*60);
		// Find the hours, if any, and assemble a string
		$hours = floor($unroundedhours);
		if ($hours > "0") {
			$hourtext = ($hours == "1")? " hour" : " hours";
			$thehours = $hours . $hourtext;
		}else{
			$thehours = "";
		}
		// Find the minutes, if any, and assemble a string
		if (strpos($unroundedhours, '.')) {
			$pos = strpos($unroundedhours, '.') + 1;
			$remainder = substr($unroundedhours, $pos, 2);
			$minutes = floor($remainder * .6);
			$minutetext = ($minutes == "1")? " minute" : " minutes";
			$theminutes = $minutes . $minutetext;
		}elseif ($minutes == "0") {
			$theminutes = "";
		}else{
			$theminutes = "";
		}
		if ($thehours && $theminutes) {
			$sep = " and ";
		}
		$timeleft = $thehours . $sep . $theminutes;
	}else{
		$timeleft = "historical";
	}
	return $timeleft;
}

Get the path of the containing directory

This one really comes in handy. It will give you the URL of the folder where the executing script resides, so you can reference the full path to other files in that folder, no matter where the folder may be located. It works on both Linux and Windows servers, and it adds a trailing slash to the path if one doesn’t already exist, so that root looks the same as a subfolder.

<?php 
function get_path() {
	// Get the path of the folder where the executing script resides, with the trailing slash
	
	// Determine HTTPS or HTTP
	$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
	$url .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
	// Convert the trailing backslash (on Windows root) to a forward slash
	$url = str_replace('\\', '/', $url);
	// Determine whether the current location is root by looking for a trailing slash (Windows or Linux)
	if (strlen($url) != strrpos($url, '/') +1) {
		$url .= '/';
	}
	return $url;
}
?>

Centering unordered list items

I wrote this script because I wanted to center the thumbnails in the Plogger image gallery while still using an unordered list item to contain each thumbnail. The script figures out how many thumbnails exist on a page and how many will fit in the space provided, then adds sufficient left padding to each to give the appearance of them being centered. It can be easily adapted for other uses. The full explanation and code example is at //ardamis.com/2007/08/05/centering-the-thumbnails-in-plogger/.

Parse .html as .php (Apache .htaccess)

This isn’t actually a PHP script, but it’s still handy. If you need to write pages with a .html or .htm extension but still want to use PHP in those pages, adding the following line to your .htaccess file will force an Apache server to parse .html files as .php files. I have confirmed this to work with GoDaddy’s hosting (GoDaddy runs PHP as CGI).

AddHandler x-httpd-php .php .htm .html

If you are running an Apache server as part of an XAMPP installation on top of Windows, try using this instead:

AddType application/x-httpd-php .html .htm

I needed to find a satisfactory way of adding WordPress tags and theme elements (such as the sidebar) to pages that exist outside of WordPress. A non-WordPress page could then appear to be seemlessly incorporated into the site, wherein the layout automatically updates with changes to the theme template files, and could use the same header, sidebar, and footer as a normal WordPress page.

The first few solutions that I found involved adding a line to each non-WordPress page. This does indeed allow the page to incorporate WordPress tags, theme elements and styles, but there is a serious drawback to this method because of the way WP manages a web site.

When you click on the link to a WP page, or enter it into the address bar, you aren’t actually going to a file that resides at that address. Instead, WP uses that address as an instruction to pull various database entries and form an index.php page that resides in the WP installation directory. For example, while the address for this page appears to be https://ardamis.com/2006/07/10/wordpress-googlebot-404-error/ , the actual page is at https://ardamis.com/index.php.

WordPress assumes that it is responsible for every page on the site, and that there are no pages on the site that it doesn’t know about. If you try to browse to a page that WP doesn’t know about, it sends you a 404 error page instead. This is what you want it to do, so long as you don’t create any pages outside of WordPress.

But a problem arises when you do want to create a page that WP doesn’t know about. When you visit the page, WP checks the database and finds that it doesn’t exist, so it puts a 404 error in the http header, but the page does exist, so Apache sends the page with the 404 error. This behavior seemed to cause some problems with some versions of IE but none with Firefox. It did, however, result in a 404 header being given to Googlebot, so that non-WordPress pages would incorrectly show up in Google Sitemaps as Not Found.

To get around this problem and send the correct http header code: HTTP Status Code: HTTP/1.1 200 OK, I needed to require a different file, wp-config.php, and then select specific functions for use in the page. results in a page that can use all of the desired tags and theme elements and also sends the correct header code: HTTP Status Code: HTTP/1.1 200 OK

The following code results in a page that can use all of the tags and theme elements (you may need to adjust the path to wp-config.php):

<?php require('./wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
?>

<?php get_header(); ?>

<div id="content">
<div class="post">
<h2>*** Heading Goes Here ***</h2>
<div class="entry">
*** Content in Paragraph Tags Goes Here ***
</div>
</div>
</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Testing the method

Using wp-blog-header.php as the include, I created a GoogleBot/WordPress 404 test page as the index.php file in a /testing/ directory. I added the url https://ardamis.com/testing/ to my Google XML sitemap file, and waited for the sitemap to be downloaded. Sure enough, a few days later, Google Sitemaps was listing the /testing/ url among the Not Found errors.

The next step was to remove what I suspected was the culprit, the include of the WordPress header, wp-blog-header.php, and see if Googlebot could again access the page. A few days after removing the include, and after the sitemap was downloaded, the Not Found error disappeared. I’m interpreting this as Googlebot once again successfully crawling the page.

The third step was to use the above code, including wp-config.php and then testing the HTTP Request and Response Header. The header looks ok, and Googlebot likes it. It looks like this does the trick.

Updated for XAMPP version 1.6.5

Some time ago, I decided to start phasing out static xhtml in favor of pages using PHP includes. To test these new pages, I used apachefriends.org’s wonderful XAMPP (which I really can’t recommend highly enough) to install Apache, MySQL, and PHP (among other things). Once I had my local server running, I put each dev site into its own folder in \htdocs\ and navigated to them by http://127.0.0.1/foldername/.

This setup was functional but far from ideal, as the index pages for these local sites weren’t in what could be considered a root directory, which lead to some tip-toeing around when creating links.

Then I discovered the NameVirtualHost feature in Apache. NameVirtualHost allows the server admin to set up multiple domains/hostnames on a single Apache installation by using VirtualHost containers. In other words, you can run more than one web site on a single machine. This means that each dev site (or domain) can then consider itself to have a root directory. You will be able to access each local site as a subdomain of “localhost” by making a change to the HOSTS file. For example, I access the local dev version of this site at http://ardamis.localhost/.

This works great for all sorts of applications that rely on the site having a discernible root directory, such as WordPress.

Unfortunately, setting up NameVirtualHost can be kind of tricky. If you are having problems configuring your Apache installation to use the NameVirtualHost feature, you’re in good company. Here’s how I managed to get it working:

For XAMPP version 1.6.5

  1. Create a folder in drive:\xampp\htdocs\ for each dev site (adjust for your directory structure). For example, if I’m creating a development site for ardamis.com on my d: drive, I’d create a folder at:
    d:\xampp\htdocs\ardamis\
  2. Edit your HOSTS file (in Windows XP, the HOSTS file is located in C:\WINDOWS\system32\drivers\etc\) to add the following line, where sitename is the name of the folder you created in step 1. Don’t change or delete the existing “127.0.0.1 localhost” line.
    127.0.0.1 sitename.localhost
    

    Add a new line for each dev site folder you create.

    Continuing with the example, I’ve added the line:
    127.0.0.1 ardamis.localhost

  3. Open your drive:\xampp\apache\conf\extra\httpd-vhosts.conf file and add the following lines to the end of the file, using the appropriate letter in place of drive. Do this step only once. We’ll add code for each dev site’s folder in the next step. (Yes, keep the asterisk.)
    NameVirtualHost *:80
    <VirtualHost *:80>
        DocumentRoot "drive:/xampp/htdocs"
    ServerName localhost
    </VirtualHost>
    

    My DocumentRoot line would be:
    DocumentRoot "d:/xampp/htdocs"

  4. Immediately after that, add the following lines, changing sitename to the name of the new dev site’s folder, again using the appropriate letter in place of drive. Repeat this step for every folder you’ve created.
    <VirtualHost *:80>
        DocumentRoot "drive:/xampp/htdocs/sitename"
        ServerName sitename.localhost
    </VirtualHost>
    

    My DocumentRoot line would be:
    DocumentRoot "d:/xampp/htdocs/ardamis"
    My ServerName line would be:
    ServerName ardamis.localhost

  5. Reboot your computer to be sure it’s using the new HOSTS file (you’ll have to at least restart Apache). You should now be able to access each dev domain by way of:
    http://sitename.localhost/

For XAMPP version 1.4

If you are using an older version of XAMPP (like XAMPP version 1.4) without the httpd-vhosts.conf file, use the instructions below.

  1. Create a folder in your drive:\apachefriends\xampp\htdocs\ for each local version of your site. For example, if I’m creating a development site for ardamis.com on my f: drive, I’d create a folder at:
    f:\apachefriends\xampp\htdocs\ardamis\
  2. Open your HOSTS file (in Windows XP, the HOSTS file is located in C:\WINDOWS\system32\drivers\etc\) and add the following line, where sitename is the name of the folder you created in step 1. Repeat this step, as necessary, for each folder you create. Don’t change or delete the existing “127.0.0.1 localhost” line.
    127.0.0.1 sitename.localhost
    

    Continuing with the example, I’ve added the line:
    127.0.0.1 ardamis.localhost

  3. Open your drive:\apachefriends\xampp\apache\conf\httpd.conf file and add the following lines to the end of the file, using the appropriate letter for drive. Do this step only once. We’ll add code for each dev site’s folder in the next step. (Yes, keep the asterisk.)
    NameVirtualHost *:80
    <VirtualHost *:80>
        DocumentRoot "drive:/apachefriends/xampp/htdocs"
    ServerName localhost
    </VirtualHost>
    

    My DocumentRoot line would be:
    DocumentRoot "f:/apachefriends/xampp/htdocs"

  4. Immediately after that, add the following lines, changing sitename to the name of the new folder, using the appropriate letter for drive and repeating this step for every folder you’ve created.
    <VirtualHost *:80>
        DocumentRoot "drive:/apachefriends/xampp/htdocs/sitename"
        ServerName sitename.localhost
    </VirtualHost>
    

    My DocumentRoot line would be:
    DocumentRoot "f:/apachefriends/xampp/htdocs/ardamis"

  5. Reboot and restart Apache. Open a browser; you should now be able to access each folder by way of:
    http://sitename.localhost

I’m assuming that you could change the DocumentRoot line to point to any folder on any drive. I’ll experiment with pointing this at a folder on another drive later.

The official Apache.org documentation for VirtualHost is at http://httpd.apache.org/docs/2.2/vhosts/. You may want to read that for further details before you try to set up virtual hosts.

If you have any questions about the above instructions, the Apache NameVirtualHost function, XAMPP, or anything in between, post a comment, but I can’t promise that I’ll be able to help. I’m learning as I go along, too.