Posts Tagged ‘PHP’
The Global Recession Enhanced Prospects for Freelance Developers
4/4/2011 9:18 AM By ArtisanWhile the recent recession crippled many businesses and some entire industries, at least one professional group, freelance developers, may have been helped. As company after company downsized and cut operating expenses, the effectiveness and reliability of their websites became ever more important.
With fewer personnel and buyers, organizations put more emphasis on their cost-effective websites to fill in the “revenue gaps.” Relying more heavily on freelance web designers to attract serious visitors and PHP web developers to improve their servers’ speed and reliability, employers who want to gain an advantage during the recovery will be offering new freelance web developer jobs in 2011.
There is a particular demand for senior talent with strong web designer qualifications and equally senior PHP web developers with knowledge of feature differences between PHP5 and PHP4, along with socket programming talent. Even some of the top talent search firms like Artisan often need more knowledgeable candidates for their clients.
Freelance developers with strong PHP skills along with database, source control, unit testing, and JavaScript ability should be able to take advantage of this heightened demand. Even those employers with limited knowledge of PHP understand its significance and importance in their web-based operations. But then, employers need not be PHP experts—they do need to realize the criticality of retaining superior PHP web developers to enhance their web pages and permit complex servers to talk to each other.
While there are increasing full-time positions, freelance developers with expertise and experience will encounter a noticeably higher volume of—and better compensated—contract opportunities, too. Even in the ever-changing world of high tech, “Supply and Demand 101″ rules. Many employers seem to believe that both the supply and demand for top freelance developers were down during the recession, many are also ready to ramp up demand.
If the perceived insufficient supply of experienced and talented freelance developers continues, the prospects of securing excellent assignments will grow further. As PHP continues its march to the pinnacle of becoming the most popular scripting language used on the web, its most experienced and up-to-date freelancers will become equally more popular with employers.
As freelance web design jobs increase, the importance of web developers, to create a winning interface between designer and server, becomes more critical. The U.S. Bureau of Labor Statistics states that web developer opportunities should grow much faster than the average for other specialties through 2018.
As the recovery from the recession strengthens in 2011, the demand for freelance developers should continue to increase. Even entry-level opportunities should be available for those PHP web developers wishing to build a marketable portfolio. While the assignments may be modest, like a superstar professional athlete, the three keys to greatness are repetition, repetition and repetition. Newer freelance developers will benefit from the expansion of opportunities. Younger professionals should consistently check the job boards for projects appropriate for building their portfolios.
Along with increasing freelance web developer jobs, many hiring managers indicate they will also be looking for talented developers for full-time positions. This might prove to be another positive for freelance developers as those preferring full-time positions may soften the competition a bit among freelancers. However, clients still seek the best, so freelance and PHP web developers should keep their expertise up-to-date and relevant to take advantage of the most lucrative opportunities.
Don’t Quote Me On That
8/18/2010 9:30 AM By Jeff BLet’s examine one of the best practices for writing PHP: what quotes to use. This may seem like a strange thing to consider, but just come along, gentle reader, and all will be made clear. Let’s take this example PHP:
<?php echo "http://www.artisantalent.com/"; ?>
This can be rendered identically like so:
<?php echo 'http://www.artisantalent.com/'; ?>
So what’s the big deal? Let’s look at a more complex example. Here it is with double quotes:
<?php echo "<a href=\"http://www.artisantalent.com/\" title=\"Artisan Talent\">"; ?>
Wait… what just happened? Well, we needed to use double quotes for the HTML we were echoing, and because of that, we needed to escape the double quotes that don’t actually end the string by using a backslash. “Well, why not use single quotes for the HTML?” you might ask, and that would be because it’s considered best practice to use double quotes for HTML. Not only that, but if you’ve already gotten in the habit of using double quotes for your HTML, having to relearn that behavior or adjust all of your existing HTML is just a pain.
Now let’s look at that PHP code snippet using single quotes for the string:
<?php echo '<a href="http://www.artisantalent.com/" title="Artisan Talent">'; ?>
How much nicer this is! Not only is that easier to write, but it actually processes faster in some cases, meaning your PHP doesn’t work as hard. And that’s a Good Thing.
One caveat: if you want to use the special formatting characters (\n for new line, \t for tab, etc.), you’ll need to encase those in double quotes, as they’ll be parsed literally within single quotes (since single quotes ignore the backslash escaping character). So you’d want to do this:
<?php echo "\t\t".'<a href="http://www.artisantalent.com/" title="Artisan Talent">This link would be indented by two tabs' ?>
And there you have it, best practice with single quotes.
Discovering more with phpinfo
8/18/2010 9:30 AM By Jeff BThis one’s a quickie way to determine whether or not PHP is installed on your host, and if so, what version it is and what settings are enabled. You’ll want to create a new file; name it whatever you like, but test.php is probably a good name. Copy this one line to it:
<?php phpinfo(); ?>
Save it and upload it to the server you’d like to test. Then go ahead and visit test.php on your server, and you should see something similar to this:

This generated page will go on for quite a bit, showing you lots of information in a series of tables. You can discover some very useful information about the PHP setup on your host. First, note the version. You want to be running at least version 5.0, and if not, you should ask your host to either upgrade your machine or move you to a more up-to-date box. PHP 5.0 has been out since 2004, so there is no excuse for your host not at least being that up-to-date, and preferably, they should be running 5.3.2, the current stable release.
Additionally, if you continue looking on, you’ll discover the “Configuration” table, which shows us way too much info, but some useful things to note are:
- Is
display_errorsenabled? - What is
memory_limitset to? - What is
post_max_sizeset to? - What is
upload_max_filesizeset to? - Is
safe_modeenabled?
The first, display_errors, does exactly that: when enabled, PHP errors are rendered in the browser and shown to you. This is good for you as a developer, but once the item in question is finished and developed, this should be disabled if possible, as it can provide outsiders with far more information than they should have.
The memory_limit is a size, usually in MB (indicated with an “M”), for how much memory PHP can consume while running. The bigger this is, the bigger your scripts can be before they choke. Most servers default this to 8 or 16 MB, and increasing it can often solve a host of issues with larger scripts and file uploading. Which brings me to the next two configuration items.
The post_max_size and upload_max_filesize items determine how large of a file you can upload using PHP. This is especially important when using a CMS, like WordPress or ExpressionEngine, as the default limit is 2MB, which can be far too small if you’re uploading movies, PDFs, or large images to your site using your CMS.
The last one, safe_mode, is a bit tricky to explain, as it does a lot of different things, but simply put, it limits PHP’s powers in an effort to combat abuse and intrusion attempts. This limiting, however, can cause many headaches with PHP’s own normal abilities, and generally, life is easier all around if it can be left off.
You can continue on down the page, seeing all the different modules your server’s PHP has loaded (and their configuration), but the last set of interesting data will be the “PHP Variables” table. This is a set of global variables (that is, variables that are available throughout any PHP you write on this server). Examine these to learn some more about what PHP can determine, and remember that these may come in handy later.
The time, please?
8/16/2010 9:30 AM By Jeff BTime is one of the most difficult things to work with in PHP. It comes in so many different formats, in many different orders, and it’s so particular. Thankfully, there are a number of built-in functions in PHP for dealing with time. Some of the most important ones are:
The time() function merely returns the current time measured in seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). While at first this seems rather useless, it actually becomes one of the best ways to deal with comparisons of time, as now we have an integer, and all of our comparisons become simple mathematical relationships and arithmetic equations. This allows for some excellent simple time/date pieces:
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
That example will spit out something like this:
Now: 2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06
The date() function returns a string formatted according to given string using either a given integer timestamp or the current time. The timestamp it expects should be in Unix format (e.g. what the time() function returns). An example would be:
<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('America/New_York'); // Set to this writer's current timezone
$today = date("F j, Y, g:i a"); // June 28, 2010, 4:39 pm
echo $today;
?>
All of the formatting options for the string are available on the PHP manual page.
The next function mentioned, strtotime(), can convert many English textual date/time pairs into a Unix timestamp. This is most useful for comparisons of times and dates against each other. So you could do something like this:
<?php
$tomorrow = strtotime('+1 day');
$today = time();
if ($tomorrow != $today) {
echo 'Tomorrow never comes.';
}
else {
echo 'Tomorrow is finally here!';
}
?>
The idate() function is a bit confusing if you just read the PHP manual description. It functions similarly to date(), but instead of returning an English formatted date/time string, it only accepts a single format string parameter and returns an integer for that particular item. For example:
<?php
$timestamp = strtotime('1st January 2004'); //1072915200
// this prints the year in four digit format.
echo idate('Y', $timestamp);
?>
This is useful for breaking out pieces of a timestamp and comparing only those pieces. It could be used to group things that happened in the same timeframe together (month, year, etc.)
Finally, here we have a custom function from the GoSquared folks over at their blog Liquidicity:
<?php
/**
* Converts seconds into days:hours:minutes:seconds components
*
* @param int $time - number of seconds
* @return string
*/
function time_quanta($time){
$d = intval(($time / 86400));
$h = intval(($time / 3600) % 24);
$m = intval(($time / 60) % 60);
$s = intval($time % 60);
if(!max($d,$h,$m,$s)) return false;
$st = '';
if($d>0) $st .= ($d < 10?'0'.$d:$d).':';
if($h>0) $st .= ($h < 10?'0'.$h:$h).':';
$st .= ($m < 10?'0'.$m:$m).':';
$st .= ($s < 10?'0'.$s:$s);
return $st;
}
?>
It does just like it says, omitting days and hours if they’re not applicable. Potentially useful, perhaps as a way to represent how long ago something was published in a more human-readable format, or to otherwise compare times in a human-readable fashion.
There are a lot more date functions, but this is the handful that have proven useful recently to this writer. If you’d like to see the whole list, it can be found in the Date/Time Functions article of the PHP manual.
You want an extension on that?
8/16/2010 9:00 AM By Jeff BHere’s a tasty little tidbit. Suppose you’ve got a series of PHP documents for your site, like index.php, about.php, and others. But you really want to have those pretty links like http://www.example.com/about/, etc. Fear not, some delightful mod_rewrite rules are here to save the day. So if we add this into your .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]
You can visit http://www.example.com/about and you’ll actually be served http://www.example.com/about.php. Now, that’s all well and good, but why don’t we really take advantage of PHP, and instead of having separate documents for each page, serve everything from index.php and use a query variable to determine what the visitor actually sees? Put this in the .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
And now, if you head to http://www.example.com/about, you’ll be served http://www.example.com/index.php?q=about. So how can we take advantage of this? How about something like this:
require_once('library.php');
switch ($_GET['q']) {
case 'about':
echo header('about page');
break;
default:
echo header('home page')
break;
}
include($_GET['q'] . '.php');
require('footer.php');
So while we still have the truly separate items broken down into separate files, we’ve consolidated as much common functionality as possible into the index.php file and the library.php file.
And why should we bother? Because other than image files (jpg, png, etc.), HTML files, and formats people actually deal with, extensions like php, cgi, asp, and other server-processed languages have little to no value to your visitors. So you give them shorter, easier-to-understand URLs, and if you ever decide to switch languages in the future, you don’t have to worry about your URLs.
Picture Perfect
8/13/2010 9:30 AM By Jeff BThis next one is really useful if you’ve got a whole pile of images sitting in a folder (or folders) and you want to easily generate a gallery for them. Let’s take an example of pictures you’ve taken on a trip and organized into date-based folders. The structure looks like this:
- 2010
- 04
- 01
- 02
- 03
- 04
So we’ve got the main folder, which is a year, then the month, then the days, with the images stored in each day folder. Now we write a page to house these images, like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pictures From My Trips</title>
</head>
<body>
<section id="april-pics">
<ul id="photos-list">
<!-- PHP goes here -->
</ul>
</section>
</body>
</html>
And finally, insert this PHP:
<?php
// the directory, where your images are stored
$imgdir = '/images/2010/04/01';
// list of filetypes you want to show
$allowed_types = array('png','jpg','jpeg','gif');
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
{
$a_img[] = $imgfile;
sort($a_img);
reset ($a_img);
}
}
// total image number
$totimg = count($a_img);
for($x=0; $x < $totimg; $x++)
{
$size = getimagesize($imgdir.'/'.$a_img[$x]);
// Make changes to the images' size to show thumbnails.
$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);
echo "\t\t\t".'<li><a rel="lightbox" href="'.$imgdir.'/'.$a_img[$x].'"<img src="'.$imgdir.'/'.$a_img[$x].'" width="'.$halfwidth.'" height="'.$halfheight.'" /></a></li>'."\r"; // Tabs & carriage return added to improve final rendered readability.
}
?>
So what’s going on with that? Well, we’ve set a variable, $imgdir, then we parse that directory for each image that corresponds to an array of filetypes (based on extension). Next, we count the total number of images and use a for() statement to do something to each image until we run out of images; ($x=0, then we tell it to go while $x < $totimg, incrementing $x by one each time.)
Finally, it echoes a few tabs to line up the echoed code with the rest of the HTML, inserts a <li>, then creates a link to the image itself for a lightbox effect, and finally inserts the image itself using an <img> tag. From there, we can use some CSS to style and lay out the list into a gallery of sorts; perhaps the usual grid, or maybe we could use some JavaScript to create some sort of carousel, slider, or other fancy effect.
Whatever you decide to do, this is a great, simple way to generate a gallery automatically based on a folder of images.
PHP Variables in your CSS
8/13/2010 9:00 AM By Jeff BNow, while there are solutions to supercharge CSS (SASS, LESS), you can use just plain old PHP to spice up your CSS powers, and there’s no need to learn any more syntax or install anything additional to preprocess your styles.
Of course, you can’t just start tossing PHP into your CSS willy-nilly; we need to do some preparation first. Depending on your server configuration, one of these methods will work for you.
- Change the
.cssextension to.php, and then at the top of your CSS file, set the content-type back to CSS with this:<?php header("Content-type: text/css; charset: UTF-8"); ?> - Include this in your
.htaccessfile (changing the “style” bit to whatever your stylesheet is named):<FilesMatch "^.*?style.*?$"> SetHandler php5-script </FilesMatch>
The first method seems to work fine on a static page, but WordPress seems to take issue with that, so using the second one (as-is, since WordPress requires a theme’s stylesheet to be named style.css) will do the trick.
Now we can take advantage of CSS variables, and even conditional statements, to fill in our styles. So let’s set up some variables:
<?php
$imageURL = 'http://images.domain.com/';
$link_color = '#eee';
$alt_link_color = '#000';
?>
And of course, lets use said variables:
#logo {
background: url("<?php echo $imageURL; ?>/header/logo.png") no-repeat;
}
a {
color: <?php echo $link_color; ?>;
}
…
#main-nav li a {
color: <?php echo $alt_link_color; ?>;
}
And of course, conditionals. If we were using WordPress, for example, we could do something like this:
<?php
if (is_page('sunrise')) $sun_position = 'sunrise.png';
else $sun_position = 'sunset.png';
?>
#background {
background: url("<?php echo $imageURL; ?>/header/<?php $sun_position; ?>") no-repeat;
}
Using PHP to generate random numbers, or utilizing some of the date/time functions to change backgrounds to reflect the time of day, the possibilities are quite powerful! So go forth, and enjoy PHP-ifying your CSS.
Batten Down the Hatches
8/11/2010 9:30 AM By Jeff BWe’re going to take this opportunity to discuss some security items with regards to PHP. It should be noted that, since PHP executes on the server side, it can be used maliciously to take control of your server and repurpose it for various unpleasant activities.
One of the most common efforts to do this is through what’s called a SQL injection. This is when you are utilizing a SQL-based database (MySQL, etc.), and a SQL query is directly injected into your server through a form field, a URL query, or some other mechanism that asks the server to process information. Thankfully, there are a number of ways to prevent this. One of the simplest is this handy little function, culled from the wilds of the internet:
<?php
/*
Function: sql_sanitize( $sCode )
Description: "Sanitize" a string of SQL code to prevent SQL injection.
Parameters: $sCode
The SQL code which you wish to sanitize.
Example: mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
Requirements: PHP version 4 or greater
Notes:
Author: engel <engel@engel.uk.to>
*/
function sql_sanitize( $sCode ) {
if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
$sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
} else { // If PHP version < 4.3.0
$sCode = addslashes( $sCode ); // Precede sensitive characters with a backslash \
}
return $sCode; // Return the sanitized code
}
?>
As it says, when you run a query, you’ll want to run the sql_sanitize() function on any value being input into the database, such as a $_POST["variable"] from a form.
One of the other functions that’s wide open by default, and should be disabled for any production server, is error reporting. When you’re writing a site or application using PHP, you’ll definitely want the error reporting to be on so you can see the problem as it happens and where it happens. But once you’ve deployed, you don’t want your visitors seeing anything like that.
The solution is to disable display_errors in the php.ini configuration file, and then enable log_errors, which will write any PHP errors to your server’s error log. In this way, you can still check the logs for any problems that might arise after you’ve deployed to production, but you don’t run the risk of exposing any runtime code to your visitors, who may turn out to be malicious in their intent.
Hopefully, none of this has scared you away from using PHP to develop your sites; it’s a solid, robust programming language still under active development, and as such, is as safe as you make it. Sadly, there will always be people seeking to take advantage.
Image resizing magic
8/11/2010 9:00 AM By Jeff BThis last one is a tip about a very useful image manipulation script, TimThumb. Go ahead and grab the source code; save it to a new document called something intelligent, like timthumb.php, and put that somewhere on your site (e.g. /scripts/). You’ll also want to ensure that the folder containing timthumb.php is writeable by the server (set it to 777 if necessary), so TimThumb can create its cache folder.
Now, normally, we’d insert an image inline like so:
<img src="/images/image.jpg" alt="My picture" width="800" height="600" />
With TimThumb, however, we can do this:
<img src="/scripts/timthumb.php?src=/images/image.jpg&h=150&w=150&zc=1" alt="My picture" width="150" height="150" />
But what does that do for us? Well, TimThumb dynamically resizes images, so we supply it with a query consisting of:
- Source (
src), which is an absolute path to the image file (meaning it starts with “/”) - Height (
h=), which is the number of pixels for the height - Width (
w=), which is the number of pixels for the width - Zoom/Crop (
zc=), which is a boolean setting which determines if the image will be resized or if it will be zoomed/cropped to achieve the size you want. This setting is most useful when you are generating thumbnails that are all an identical size, but you have source images that are various sizes and shapes.
So now, if we take our image gallery code from one of the previous posts, we can do this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pictures From My Trips</title>
</head>
<body>
<section id="april-pics">
<ul id="photos-list">
<?php
// the directory, where your images are stored
$imgdir = '/images/2010/04/01';
// list of filetypes you want to show
$allowed_types = array('png','jpg','jpeg','gif');
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types))
{
$a_img[] = $imgfile;
sort($a_img);
reset ($a_img);
}
}
// total image number
$totimg = count($a_img);
for($x=0; $x < $totimg; $x++)
{
echo "\t\t\t".'<li><a rel="lightbox" href="'.$imgdir.'/'.$a_img[$x].'"<img src="/scripts/timthumb.php?src='.$imgdir.'/'.$a_img[$x].'&w=250&h=250&zc=1" width="250" height="250" /></a></li>'."\r"; // Tabs & carriage return added to improve final rendered readability.
}
?>
</ul>
</section>
</body>
</html>
Now you may say, “But I can do that by just specifying the size in the img tag; why would I waste server resources like this?” And the answer is because TimThumb caches these resized images. Once at least one person asks for one of them, they become static files in TimThumb’s cache folder, and as such, consume even fewer resources than resizing an image client-side with the img tag.
We can, however, improve on TimThumb’s caching and skip TimThumb entirely when an image is cached. Before performing this step, please make sure TimThumb is working well as-is; we don’t want to hack something that’s not 100% to start with.
With that in mind, take a look at line 528 (in the current version). You’ll see this:
$cachename = $_SERVER['QUERY_STRING'] . VERSION . $lastModified;
$cache_file = md5($cachename) . '.png';
If we change how the cachename is generated, we can craft some filenames that can be more easily used in some RegEx .htaccess rules. So how about this little tidbit:
$filename = preg_replace("@http://[^/]+/(.*)\.$ext$@", "$1", get_request( 'src', 'timthumb' ));
$cachename = $filename . '-' .
get_request( 'w', 100 ) . '-' .
get_request( 'h', 100 ) . '-' .
get_request( 'zc', 1 ) . '-' .
get_request( '9', 80 );
$cache_file = $cachename . '.png';
So what’s happening here? We’re calculating the file name (from the URL) and stripping out the extension (since all of the images end up being PNGs), then adding in a dash, the width, dash, height, dash, the value of zc, and the quality value, ending with the png extension.
Now let’s craft some mod_rewrite rules to skip TimThumb whenever we can. Open up your .htaccess, and place this bit in before any of your other rewrite rules:
RewriteCond %{SCRIPT_FILENAME} timthumb\.php
RewriteCond %{QUERY_STRING} src=http:\/\/[^\/]+\/(.*)\.(png|jpe?g)&w=([0-9]+)&h=([0-9]+)&zc=([0-9]+)
RewriteCond YOUR_HOME_DIRECTORY/%1-%3-%4-%5-80.%2 -f
RewriteRule .* /%1-%3-%4-%5-80.%2 [L]
So what the heck does that do? Well, the first line keeps an eye out for any requests for TimThumb. Then the second rule figures out some GET parameters for the image file name and its extension, width, and height. If you’ve got anything else going on with your image URLs, here’s where to add them in. If you’ve never dealt with RegEx, I recommend some Googling on it, and perhaps asking a question over at StackOverflow, a great programming resource.
Then we have a line you need to modify. The YOUR_HOME_DIRECTORY bit needs to be adjusted to reflect your actual site root. If you don’t know what it is, put this:
<?php echo $_SERVER['DOCUMENT_ROOT'] ?>
Into a file at the site root and view it. Copy the path it presents you with, and replace YOUR_HOME_DIRECTORY with it. The variables (%1, %2, etc.) are being culled from the second RewriteCond. The last rule is the actual rewrite itself (which is internal, not a redirect, so the URL never changes). You may need to adjust this rule to reflect the path to your images, but a little experimentation should yield whether or not your images can be found.
If you have dedicated hosting, this is only going to result in a little bit of savings, but if you’re on shared hosting, like Media Temple’s (gs), or GoDaddy, or Dreamhost, or any of the myriad other hosts, this will dramatically improve your site’s response if you want to use TimThumb.








Subscribe by RSS