February 22, 2008

auto_prepend_file - Parse PHP before the requested PHP loads

You will find other articles relevant to this document in these sections:
Richard Lee @ 4:57 pm

Ever had to do some legacy hacking or changing of $_SERVER vars for different OS and wish you didn’t have to ruin your beautiful application? Well maybe auto_prepend_file is the answer! This is a little known core php directive, which when used  in a HTACCESS can let specify a php document to be parsed before the document that has been called is parsed - and for every document in the given directory for that matter. Personally I’ve been using it to set constants which may/ or may not be set and for workarounds when libraries dont exits, but even more simple use it to include a global config file with paths to various assets etc for your website ;)

February 4, 2008

PHP 4 still kickin

You will find other articles relevant to this document in these sections:
Richard Lee @ 2:04 pm

Earlier this month the PHP dev team released 4.4.8 a security/ stability patch, supposedly the last patch of the 4 branch*. I was pretty surprised, as to my knowledge official support of version 4 had finished as of 2007. I’ve always commended the PHP dev team on their ongoing support for PHP 4 since so many apps and shared hosts still support PHP 4, but as developers we must move on, familiarity breeds content as they say, so if your thinking of updating to 4.8.8 I strongly recommend you GoPHP5.

Recommended reading on PHP 4 to PHP5 migration;

August 22, 2007

PHP File Upload Woes

You will find other articles relevant to this document in these sections:
Richard Lee @ 11:51 am

I’ve spent the last 2 days trying to get a file uploading script working on my shared host. It’s driving me crazy. Files 1MB and under upload completely fine, but anything above and the browser bombs out with “server busy..” errors! Before you say “update your max_upload_size, post_max_size and max_execution_time ini settings“. Forget it. Been there done that. No success. Is Apache overriding my settings? Some investigation into the possibility has unveiled 4 possibilities. The Apache directives LimitReqestBody, TimeOut, RLimitMEM and RLimitCPU. I’ve read that LimitRequestBody will limit the size of the incomming request, and TimeOut is pretty self explanatory. Still reading into the affects of RLimit*.

If you’ve experienced php upload problems and can offer any insight please let me know! Anyway i’ll keep you posted on further developments on the issue..

UPDATE:
Ok it seems my server tweaks were not the problem, it’s actually Firefox timing out. IE after some time eventually uploads the file as expected. The file is being uploaded at roughly 1 minute per MB over our broadband connection, and FF seems to be bomb out after 2 and half minutes. There seems to be some tweaks in the FF about:config that can me made just not sure what yet!
(for the record i am testing in FF 2.0.0.5 and IE 7 on XP)

August 17, 2007

Multiple INSERT’s in MySQL

You will find other articles relevant to this document in these sections:
Richard Lee @ 12:04 pm

Did you know you can actually do multiple record inserts in one mysql query? Well, since version 3.22.5 anyway… Just group each value set in parenthesis and seperate via commas - and bobs your uncle!

< ?php
 
$query = "INSERT INTO results (firstname, lastname, score) 
VALUES 
 ('joe', 'bloggs', 77),
 ('mary', 'jane', 80),
 ('matthew', 'heinze', 60)";
 
mysql_query($query);
 
?>

August 13, 2007

PHP File Manipulation on Apache

You will find other articles relevant to this document in these sections:
Richard Lee @ 3:36 pm

Without a doubt the biggest “gotcha” when working with files in PHP is permissions. Simply put in order for any PHP script to write to a file the Apache needs to have privileges to that file. This can be a bit of an issue in a shared hosting environment especially. Your webhost maybe running Apache under one user and for manipulating files and directories you are required to use FTP or shell which operates under a different user. So how can you make sure you have the correct permissions? First port of call is definitely your webhost. They should indicate in their support information the permissions required in order for your PHP scripts to write to a file on the server. For most it will be 777, which means EVERYONE has read/write/execute access - so be weary sensitive files may be accessible!

How to set permissions on your webserver:

1. Using FTP:

Probably the easiest way of setting permissions is through an FTP Application (Eg Core FTP & Filezilla). Usually it’s simply a matter of right-clicking and entering the numeric permission (777) or checking the correct boxes for “Owner” “Group” and “Other” (all for 777). You may also be able to recursively set permissions on any child files.
2. Through Linux Shell:

Linux shell is a little more advanced, offering a few more options but not all webhosts offer shell access. If you do have shell access you can run the chmod command followed by the numeric permission like so:

$ chmod 777 uploads

Additional options are set by passing -flags. For example for recursive permission setting of the uploads directory:

$ chmod -R 777 uploads

3. In PHP script:

A number of PHP functions allow you to set file permissions on the fly. However, to do this Apache needs to have permission to write to the parent directory in the first place! Here are some examples:

Creating a directory with 777 permissions -

// Under Linux
mkdir('/absolute/path/to/uploads/images', 0777); // beginning '/' is important!
// Under Windows
mkdir('E:/absolute/path/to/uploads/images', 0777); // windows has driver name instead of beginning slash
// Creating a directory recursively
// (see below)

(note: mkdir() actually sets directories to 777 by default)

Setting an image file to 777 so we can manipulate it with PHP’s various image functions -

chmod('/absolute/path/to/uploads/images/pic_thumb.jpg', 0777);

Getting around open_basedir restrictions

One little speedhump I discovered recently was the effect of open_basedir restrictions on directory creation. I was creating a directory tree recursively by passing the absolute path, then splitting it up into directories and creating each directory incrementally based on whether is existed or not.

$folder = preg_split( "/[/]/" , '/absolute/path/to/uploads/images' );
// append beginning slash for Linux
$mkfolder =  strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? '' : DIRECTORY_SEPARATOR;
for(  $i=0 ; isset( $folder[$i] ) ; $i++ )
{
if(!strlen(trim($folder[$i])))continue;
$mkfolder .= $folder[$i];
if( !is_dir( $mkfolder ) ){
mkdir( "$mkfolder" ,  0777);
}
$mkfolder .= DIRECTORY_SEPARATOR;
}

Problem was being an absolute path some of the directories were outside of the webroot and PHP was unable to run any checks on the directories due to permissions! The solution was to do the checks using shell instead via PHP’s exec() function so i created by own is_dir function open_basedir_is_dir():

// open_basedir safe is_dir function
function open_basedir_is_dir($dir) {
 
// get base_dir settings
$open_basedir = @ini_get('open_basedir');
 
// if open_basedir has  not been set we'll use normal check
if (empty($open_basedir)) {
return is_dir($dir);
} else {
// run shell command
exec("ls -dl $dir", $tmp_cmd);
// if nothing set assuming dir doesn't exist, or if not "d" flag its not a dir
// [d] directory [l] link [-] regular file)
return (isset($tmp_cmd[0]) && substr($tmp_cmd[0], 0, 1) == 'd');
}
}
 
$folder = preg_split( "/[/]/" , '/absolute/path/to/uploads/images' );
// append beginning slash for Linux
$mkfolder =  strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? '' : DIRECTORY_SEPARATOR;
for(  $i=0 ; isset( $folder[$i] ) ; $i++ )
{
if(!strlen(trim($folder[$i])))continue;
$mkfolder .= $folder[$i];
if( !open_base_dir_is_dir( $mkfolder ) ){
mkdir( "$mkfolder" ,  0777);
}
$mkfolder .= DIRECTORY_SEPARATOR;
}

July 17, 2007

PHP4 to be discontinued end of year

You will find other articles relevant to this document in these sections:
Richard Lee @ 5:03 pm

Its been 3 years since the first release of PHP 5, and it was surprising to see that as of last month the penetration for PHP 5 was still floating around 15% (source http://www.nexen.ne). That’s a hell of a lot of PHP 4 development still going on! Myself included (did i say that out loud?). Many hosting providers and popular applications like WordPress are still widely supporting 4, but be weary, with the discontinuation of 4 there’s going to be a lot of rewriting and migration going on (FYI Migration Guide). Gees i hate updates!

February 15, 2007

Delphi for PHP

You will find other articles relevant to this document in these sections:
Richard Lee @ 1:50 pm

Seems to be a lot of exciting things going on in the world of PHP lately. In addition to Zend Framework there is now a plans to release Delphi for PHP. In a recent Delphi Seminar held in India, CodeGear (a subsidary of Borland)  announced in addition to their release of Delphi 2007 they will release a brand new product line aimed at Rapid Application Development in PHP.

January 19, 2007

Intro to Mod Rewrite for SEO URLs

You will find other articles relevant to this document in these sections:
Richard Lee @ 10:37 am

Mod Rewrite is an Apache module commonly used with PHP to create Search Engine friendly URLs. Essentially this module lets us mask ugly querystrings with much more meaningful URLs. For example take a products page in a database driven catalog:

http://www.mysite.com.au/catalog/product.php?pid=123

At the moment this URL tells us nothing about the destination page and searchbots lare deterred from indexing such URLs - Wouldn’t it be better if we included the product name?

http://www.mysite.com.au/catalog/products/t-shirt/123

Much better :) . Using the power of regular expressions we can extract the information from our new URL and pass this information onto the correct PHP page behind the scenes.

So how do we do it? In the case of our new URL all we need to do is extract the last part which carries the product id and pass this onto the product.php page. We can do this easily in a .htaccess file:

First we enable the Mod Rewrite engine using RewriteEngine on:

# HTACCESS
 
RewriteEngine On # enable the module

Then we set the base url we will be writing from using RewriteBase base

RewriteBase /catalog/ # base URL which in our case is 'catalog' since this is where our app is sitting

Now we do our Rewrite using the RewriteRule pattern substitution directive - pattern is our Regular Expression which we use to evaluate the incomming URL, substitute is the string which is substituted for (or replaces) the original URL for which Pattern matched.

RewriteRule ^products/[a-zA-Z0-9-_]+/([0-9]+)$ product.php?pid=$1
# End HTACCESS

The Regular Expression:

- Caret ^ and dollar $ sign characters signify the start and end of our pattern string

- Square brackets specify ranges of allowed characters, such as A to Z, 0 to 9

- Round brackets are used to “capture” parts matched in our pattern - in this case the product id - which we later reference in our substitute URL using back referencing $1
(ref numbers are indexed according to each set of round brackets i.e. if we had enclosed the product name match in rounded brackets this would be $1 and the product id would be $2)
Easy enough? This is a relatively simple rewrite and I have explained it in fairly layman terms, more complicated rewrites require some knowledge of Regular Expressions. If you haven’t played with Regular Expression I highly recommend you checkout Wikipedia, DevShed articles and the cheat sheets supplied by ILoveJackDaniels.com.

December 20, 2006

Zend Framework Example

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 1:34 pm

A sophisticated example built by IBM showing off some of the features of the Zend Framework: QEDWiki

December 11, 2006

Regular Expression Tester

You will find other articles relevant to this document in these sections:
Richard Lee @ 2:18 pm

Regular Expressions are tricky at the best of times, wouldn’t it be great if you could test your patterns ? - Well you can -  Checkout this handy online tester http://www.quanetic.com/regex.php

Next Page »