Inerd Hussein - tagged with php http://www.ooopx.net/feed en-us http://blogs.law.harvard.edu/tech/rss Sweetcron husseinad@gmail.com 3 Ways to Speed up Your Site with PHP http://www.ooopx.net/items/view/3226/3-ways-to-speed-up-your-site-with-php

These days, with broadband connections the norm, we don’t need to worry as much about internet speeds or the filesize of our pages. However, that’s not to say that we still shouldn’t do so. If you wish to reduce the load times on your server, decrease the number of HTTP requests, and go that extra bit for your visitors, there are a few techniques that you can use. This tutorial covers a number of PHP tricks, including caching and compression.

  1. CSS Amalgamation with PHP As web developers, we often split up our CSS between several separate files to keep a logical separation and to make modifications easier. However, this increases the number of requests to the server, resulting in a slower page load. Using some PHP we can have the best of both worlds; keeping multiple files on our end, and using one request to retrieve all of them.

Preparation Before we can optimize CSS files, we will need some CSS to work with! So let’s make three files and put some CSS in them.

// main.css // Just some sample CSS

body { width: 800px; margin: 0 auto; color: grey; }

#wrapper { margin-top: 30px; background: url(../images/cats.png); }

// typography.css // Just some sample CSS

body { font-family: Arial, san-serif; font-weight: bold; }

strong { font-size: 120%; }

// forms.css // Just some sample CSS

form { position: relative; top: 400px; z-index: 99; }

input { height: 50px; width: 400px; }

The PHP We need to get the contents of these files and append them to each other in a specified order. So our script has to receive the names of the CSS files via URL parameters, open all the files and put them together. An explanation of the code follows.

<?php //Lets define some useful variables // --- NOTE: PATHS NEED TRAILING SLASH --- $cssPath = './css/';

if (isset($_GET['q'])) { $files = $_GET['q']; // Got the array of files!

//Lets just make sure that the files don't contain any nasty characters. foreach ($files as $key => $file) { $files[$key] = str_replace(array('/', '\', '.'), '', $file); }

$cssData = ''; foreach ($files as $file) { $cssFileName = $cssPath . $file . '.css'; $fileHandle = fopen($cssFileName, 'r'); $cssData .= "\n" . fread($fileHandle, filesize($cssFileName)); fclose($fileHandle); } }

// Tell the browser that we have a CSS file and send the data. header("Content-type: text/css"); if (isset($cssData)) { echo $cssData; echo "\n\n// Generated: " . date("r"); } else { echo "// Files not avalable or no files specified."; } ?>

Breaking it Down It looks quite complicated, but stick with me, it’s really pretty simple.

<?php //Lets define some usefull variables // --- NOTE: PATHS NEED TRAILING SLASH --- $cssPath = './css/';

if (isset($_GET['q'])) { $files = $_GET['q']; // Got the array of files!

//Lets just make sure that the files don't contain any nasty charactors. foreach ($files as $key => $file) { $files[$key] = str_replace(array('/', '\', '.'), '', $file); }

This chunk of code sets the path for the CSS folder and checks that we have been sent some files to work with. The CSS path needs to have trailing slashes otherwise we will find ourselves with bucket-loads of errors. If we wanted, we could check automatically for a slash and add it if required. However, for the sake of simplicity I omitted that behavior. Next we check each filename and remove any full stops and/or slashes. This prevents people from navigating the filesystem by passing filenames such as ‘../../secret/file’.

$cssData = ''; foreach ($files as $file) { $cssFileName = $cssPath . $file . '.css'; $fileHandle = fopen($cssFileName, 'r'); $cssData .= "\n" . fread($fileHandle, filesize($cssFileName)); fclose($fileHandle); } }

Now we have to build our CSS data from the individual files. To do this, we loop through the files array with foreach, open each file and append the contents onto our data. The “\n” simply adds a new line character to keep things nice and tidy. The filesize() function is used to find the length of the file so that we can tell fread() how much we want (the entire file).

// Tell the browser that we have a CSS file and send the data. header("Content-type: text/css"); if (isset($cssData)) { echo $cssData; echo "\n\n// Generated: " . date("r"); } else { echo "// Files not avalable or no files specified."; } ?>

The last bit of the script is to send the CSS data to the browser. This means we have to tell PHP that we are sending CSS data, and that it should inform the browser. We do this with the header function, setting the content type to ‘text/css’. Then we send the CSS to the client. We first check if there is any CSS data to send. If there isn’t, then this means that no names of CSS files were sent. If this is the case we simply reply with a CSS comment saying so. If, however, we do have some data to send, then we send that and add a message detailing when it was generated. If you wanted to, for example, add some copyright information to all your CSS in one go, then this would be an ideal place. Putting it to the Test Okay, now it’s time to test the script; we need to first build a directory structure and then place our script and CSS files. Have a look at the image below and try to replicate that structure. If you want something different, don’t forget to change the paths to reflect those changes.

Once everything is in the right place, we can test our script. The directory structure will have to be placed in the ‘htdocs’ or ‘www’ folder of a webserver with PHP (pretty much any webserver these days). Navigate to the index.php file. You should be greeted by a single comment: ‘Files not available or no files specified’. This means that we have not given any files for it to pull together. However, the good news is that this is a valid CSS comment and won’t cause any problems. Let’s give something a little trickier a go; type in ‘index.php?q[]=main’, you should get the CSS from you main.css file and a notice at the bottom. If we want to pull multiple files together (as this was really the entire point of the script) we can send this request: ‘index.php?q[]=main&q[]=forms’. As you can see we can repeat ‘q[]=’ as many times as we want because it is adding each value to an array. You could potentially add 50 CSS files together if you wanted using this script.

Concluding Using this method can be very useful, and can provide benefits such as being able to have a default style sheet for every page and and an extra CSS file for pages with forms. It’s also easy to implement if you’re already using some sort of CSS processing with PHP. If you want, you can even rename index.php to index.css as long as you set up .htaccess to treat CSS files as PHP. You might notice that I’m treating different orders of CSS files as different. This is because you may wish to have one stylesheet override another and therefore the order of the files is important. If this isn’t a problem for you, you may wish to perform a sorting function on the files array before processing. Just a word of caution; if you place the index.php file in any folder other than the one that contains the CSS then you have to write your relative background image paths as if index.php was your stylesheet. This is because that’s what the browser thinks it is. Alternatively, you could add some code to rewrite these URLs, however, that is beyond the scope of this tutorial. 2. Stripping Whitespace from your HTML and CSS Many of us use large amounts of whitespace when writing code. The good news is that whitespace in PHP doesn’t actually get sent to the browser. However, it does in HTML. Browsers tend to only display one space no matter how many tabs you use in your code. This means that there is some wasted bandwidth. However, with some simple PHP we can remove this bandwidth leeching whitespace. Preparation Once again, we will need some raw data to work with; so copy the following example HTML and CSS code. Save the following into a .htm and a .css file in a folder within your server’s webroot directory.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Hey a Page!</title> <link rel="stylesheet" href="./css.css" type="text/css"> </head> <body id="homepage"> <div id="wrapper"> <div id="header"> <h1>Kittens for sale!</h1> <div> There are lots of spaces here! But we need to get rid of them! </div> </div> <div id="mainbody"> Lorem Ipsum dol... </div> </div> </body> </html>

body { min-height: 800px; background: black; font-size: 18px; }

wrapper {

width: 960px; margin: 20px auto; padding: 15px; }

header h1 {

text-indent: -99999em; background: url(../images/header.png); display: block; width: 100%; height: 48px; }

mainbody {

font-weight: bold; }

The PHP One of the advantages of this method is that the same script will work with both HTML and CSS. Our script has to accept a filename as part of the request. Once the file has been loaded, it has to strip all whitespace down to just one space character. This is because we don’t want to remove all the spaces between words! Once again, ther’s a bunch of PHP here, but I will go through it carefully with you.

<?php $fileDirectory = ''; $file = $_GET['q']; $nameExplode = explode('.', $file); $ext = $nameExplode[1]; $fileName = $fileDirectory . $file; if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') { //Check for evil people... die('Hackers...!'); } else { //Lets get down to business $handle = fopen($fileName, 'r'); $fileData = fread($handle, filesize($fileName)); //Now for some regex wizzardry! $newData = preg_replace('/\s+/', ' ', $fileData); fclose($handle); //Time to output the data. if ($ext == 'css') { header("Content-type: text/css"); } echo $newData; } ?>

Having a Closer Look This one isn’t so tricky, but we will still break it up and make sure we understand what is going on. We are getting the filename via a parameter passed with the GET request and checking to make sure that it is an allowed filetype. Then we proceed to fetch the data and process it to remove excess whitespace. This method is relatively primitive and won’t remove all unnecessary whitespace, but it will deal with most of it in only a few lines of code!

<?php $fileDirectory = ''; $file = $_GET['q']; $nameExplode = explode('.', $file); $ext = $nameExplode[1]; $fileName = $fileDirectory . $file;

This snippet just sets some variables. Once again, we are passing our data through ‘q’ as it is nice and short. This also gives us a place to define our directory for files and extract the file extension. The explode() function rips the filename up whenever it sees a ‘.’ and puts the bits into an array.

if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') { //Check for evil people... die('Hackers...!'); } else {

Here we’re checking to make sure that the file is either CSS or HTML. If it was something else we might find ourselves giving hackers a hole into our site like showing them settings.php! So after giving the hackers the flick we can move on to processing our data!

//Lets get down to business $handle = fopen($fileName, 'r'); $fileData = fread($handle, filesize($fileName)); //Now for some regex wizzardry! $newData = preg_replace('/\s+/', ' ', $fileData); fclose($handle); //Time to output the data. if ($ext == 'css') { header("Content-type: text/css"); } echo $newData; } ?>

Now for the main attraction; all we are really doing here is opening the file and reading it - like we did in the first script - and then ripping out as much whitespace as possible. This is achieved through a relatively simple regular expression that searches through the file for any spaces, tabs or newlines and then replaces them with a single space. Lastly we send back the data, setting the required headers if we are dealing with CSS. But Does it Work? If you go into your browser and navigate to ‘index.php?q=css.css’ we should see one line of CSS across the page. This shows that everything is fine! We can also see the same effect on the source code for the html example. In fact in that small example, we reduced a 314 character CSS file down to 277 characters and a 528 character html file down to 448 characters. Not bad for 15 lines of code.

Conclusion So that’s a good example of how we can do quite a lot with very little work. If you have a look at the source of pages like Google you will find that they have almost no whitespace because, when you receive millions of requests, a few extra kilobytes per request really adds up. Unfortunately, most of us aren’t that lucky! 3. Caching in your PHP Scripts In this part, I will show you how to ‘retrofit’ caching into your scripts using the above script as an example. The aim is to speed things up by not having to regenerate the data every time someone requests a file. Generating the content every request is just a waste, especially on static data such as our CSS. To add caching we need to add three things to our script. Firstly, we have to collect the data input to the script and generate a filename unique to that set of inputs. Secondly, we have to look for a cache file and see if it is sufficiently recent. Lastly, we have to either use the cached copy or generate new content and cache it for next time.

Breaking the Flow This part of the process really depends on the individual script, however I will show where I am going to break the flow of this script for the caching.

<?php $fileDirectory = ''; $file = $_GET['q']; $nameExplode = explode('.', $file); $ext = $nameExplode[1]; $fileName = $fileDirectory . $file;

//-- WE HAVE ENOUGH DATA TO GENERATE A CACHE FILE NAME HERE --

if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') { //Check for evil people... die('Hackers...!'); } else {

//-- WE CAN INTERCEPT AND CHECH FOR THE CACHED VERSION HERE --

//Lets get down to business $handle = fopen($fileName, 'r'); $fileData = fread($handle, filesize($fileName)); //Now for some regex wizardry! $newData = preg_replace('/\s+/', ' ', $fileData); fclose($handle); //Time to output the data.

//-- NOW WE CAN STORE THE NEW DATA IF REQUIRED AND OUTPUT THE DATA --

if ($ext == 'css') { header("Content-type: text/css"); } echo $newData; } ?>

Putting it into Action We will now actually write the code for caching into this script. I will first show the script completed and then go through each piece.

<?php $fileDirectory = ''; $file = $_GET['q']; $nameExplode = explode('.', $file); $ext = $nameExplode[1]; $fileName = $fileDirectory . $file; $cacheName = './cache/' . $nameExplode[0] . $nameExplode[1] . '.tmp'; if ($ext != 'css' AND $ext != 'htm' AND $ext != 'html') { //Check for evil people... print_r($ext); die('Hackers...!'); } else { if (file_exists($cacheName) AND filemtime($cacheName) > (time() - 86400)) { $cacheHandle = fopen($cacheName, 'r'); $newData = fread($cacheHandle, filesize($cacheName)); fclose($cacheHandle); $isCached = TRUE; } else { //Lets get down to business $handle = fopen($fileName, 'r'); $fileData = fread($handle, filesize($fileName)); //Now for some regex wizardry! $newData = preg_replace('/\s+/', ' ', $fileData); fclose($handle); //Lets cache! $cacheHandle = fopen($cacheName, 'w+'); fwrite($cacheHandle, $newData); fclose($cacheHandle); $isCached = FALSE; } //Time to output the data. if ($ext == 'css') { header("Content-type: text/css"); if ($isCached) { echo "// Retrieved from cache file. \n"; } } else { if ($isCached) { echo '<!-- Retrieved from cache file. -->'; } } echo $newData;

} ?>

The Explanation This one’s a bit trickier and a little more likely to leave you scratching you head. But don’t worry, not much has changed and we will go through each section. An extra feature we have included is the refreshing of the cache every 24 hours. This is handy so if you change anything, you can either wait 24 hours or simply empty the cache directory. If you want a different refresh interval just calculate it in seconds.

$cacheName = './cache/' . $nameExplode[0] . $nameExplode[1] . '.tmp';

This bit of code just gets the file’s name and extension, glues them together and adds the cache directory and the appropriate ‘.tmp’ extension.

if (file_exists($cacheName) AND filemtime($cacheName) > (time() - 86400)) { $cacheHandle = fopen($cacheName, 'r'); $newData = fread($cacheHandle, filesize($cacheName)); fclose($cacheHandle); $isCached = TRUE; } else {

Here we’re checking if we have a cache file saved and if the cache file was created within 24 hours. If both these conditions are met then we open the file and extract its contents to substitute for the scripts output. We also set $isCached to true so we can output some messages at the end.

//Lets cache! $cacheHandle = fopen($cacheName, 'w+'); fwrite($cacheHandle, $newData); fclose($cacheHandle); $isCache = FALSE; }

Now we are caching the output of the script for us to use in later requests. We simply open a file in write mode, dump our data into it and then close it. Strictly you don’t have to close files in PHP but it’s considered a good practise so I have done it here.

//Time to output the data. if ($ext == 'css') { header("Content-type: text/css"); if ($isCached) { echo "// Retrieved from cache file. \n"; } } else { if ($isCached) { echo '<!-- Retrieved from cache file. -->'; } }

This is another part of the script that was modified a little so that we can offer some feedback through the browser. If the file was retrieved from the cache we can add a message to the script’s output. Notice that the message for CSS scripts has ‘\n’ at the end. This is because the characters ‘//’ comment our entire line and ‘\n’ pushes everything else onto another line. If you want to disable the messages all you have to do is comment out the line ‘$isCached = TRUE;’. Giving it a Whirl If we use our script again, we will notice no change until we refresh a second time when we will see a message saying that the file was retrieved from cache. Sweet success! This caching setup can also be applied to the first script with little modification, however, that is left as an exercise for the reader.

Concluding Being able to quickly add simple but effective caching to any script that you are working on is an extremely useful skill. It just adds that extra bit to the script, reducing the load on your server and speeding up the site for users. Now that’s win-win! Summing it Up In this tutorial I have shown you a few handy but simple ways to speed up your site with a dash of PHP. I really hope that you find them useful and that you can apply them to a project in the future. How do you improve your site’s performance?

Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Wed, 22 Jul 2009 08:40:00 -0600 http://www.ooopx.net/items/view/3226/3-ways-to-speed-up-your-site-with-php
Organize Your Next PHP Project the Right Way http://www.ooopx.net/items/view/3219/organize-your-next-php-project-the-right-way

When starting out with PHP, it can be daunting figuring out how best to organize a project. If you’ve ever been confused with where to put your images, external libraries, or keeping your logic separate from your layout, then check out these tips; they’ll get you heading in the right direction.

Tutorial Details

Program: PHP/Projects Version: 1 Difficulty: Easy Estimated Completion Time: 20 minutes

Directory Structure

I’d say the number one thing in getting your project up and running quickly is having a solid directory structure you can reuse for multiple projects. If you are using a framework, usually it will provide a structure to use, but in this scenario we’re working on a simple site or app.

Breakdown

You are probably very familiar with the public_html structure. This is the Document Root in which all your public files are accessed (/public_html/page.php is accessed at example.com/page.php).

img — All your image files. I decided to split content images from layout images. css — All your css files. js — All your javascript files.

The resources directory should hold all 3rd party libraries, custom libraries, configs and any other code that acts as a resource in your project.

config.php — Main configuration file. Should store site wide settings. library — Central location for all custom and third party libraries. templates — Reusable components that make up your layout.

The Config File

As designers and developers our main goal is to do as little work as possible. One way to reach this goal is with config files. To get a better idea of what the configuration file should have check out this example.

<?php

/* The important thing to realize is that the config file should be included in every page of your project, or at least any page you want access to these settings. This allows you to confidently use these settings throughout a project because if something changes such as your database credentials, or a path to a specific resource, you'll only need to update it here. */

$config = array( "db" => array( "db1" => array( "dbname" => "database1", "username" => "dbUser", "password" => "pa$$", "host" => "localhost" ), "db2" => array( "dbname" => "database2", "username" => "dbUser", "password" => "pa$$", "host" => "localhost" ) ), "urls" => array( "baseUrl" => "http://example.com" ), "paths" => array( "resources" => "/path/to/resources", "images" => array( "content" => $_SERVER["DOCUMENT_ROOT"] . "/images/content", "layout" => $_SERVER["DOCUMENT_ROOT"] . "/images/layout" ) ) );

/* I will usually place the following in a bootstrap file or some type of environment setup file (code that is run at the start of every page request), but they work just as well in your config file if it's in php (some alternatives to php are xml or ini files). */

/* Creating constants for heavily used paths makes things a lot easier. ex. require_once(LIBRARY_PATH . "Paginator.php") */ defined("LIBRARY_PATH") or define("LIBRARY_PATH", realpath(dirname(FILE) . '/library'));

defined("TEMPLATES_PATH") or define("TEMPLATES_PATH", realpath(dirname(FILE) . '/templates'));

/* Error reporting. */ ini_set("error_reporting", "true"); error_reporting(E_ALL|E_STRCT);

?>

This is a basic drop-in config file. A multi-dimensional array serves as a flexible structure for accessing various config items such as database credentials.

db — Store database credentials or other data pertaining to your databases.

paths — Commonly used paths to various resources for your site.

log files upload directories resources

urls — Storing urls can be really handy when referencing remote resources throughout your site. emails — Store debugging or admin emails to use when handling errors or in contact forms.

Using constants for commonly used paths makes include statements (require or include) a breeze, and if the path ever changes you’ll only need to update it in one place. Using Different Config Files For Multiple Environments

By using different config files for multiple environments you can have relevant settings depending on the current environment. Meaning, if you use different database credentials or different paths for each environment, by setting up the respective config files you ensure that your code will work without hassle when updating your live site. This also allows you to have different error reporting settings based on the current environment. Never ever display errors on your live site! Displaying errors on the live site could expose sensitive data to users (such as passwords).

The Layout

Reusable templates are another big time saver. There are some great libraries for templating (such as Smarty), and I always encourage using such a library rather than reinventing the wheel. These libraries offer a lot of functionality (like helper methods for formatting currency and obfuscating email addresses). Since this is a simple site however we don’t want to take the time to setup the library and will be using the most basic of basic templates. We achieve this by including common sections or modules in to our site pages; this way if we want to change something in the header, like adding a link to the global navigation, it is propagated throughout the site.

header.php <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Simple Site</title> </head>

<body> <div id="header"> <h1>Simple Site</h1> <ul class="nav global"> <li><a href="#">Home</a></li> <li><a href="#">Articles</a></li> <li><a href="#">Portfolio</a></li> </ul>

</div> rightPanel.php <div id="siteControls"> <ul class="categories"> <li>PHP</li> <li>HTML</li> <li>CSS</li> </ul> <div class="ads"> <!-- ads code --> </div>

</div> footer.php <div id="footer"> Footer content... </div> </body> </html> index.php

Let’s say that we put all of our layout components (header, footer, rightPanel) in our resources directory under templates.

<?php // load up your config file require_once("/path/to/resources/config.php");

require_once(TEMPLATES_PATH . "/header.php"); ?> <div id="container"> <div id="content"> <!-- content --> </div> <?php require_once(TEMPLATES_PATH . "/rightPanel.php"); ?> </div> <?php require_once(TEMPLATES_PATH . "/footer.php"); ?> Taking It Further

While this basic template system gets you off to a great start, you can take it a lot further. For instance, you can create a class or functions that include all the template files and accept a content file as an argument to render within the layout. This way you don’t need to keep including the template files in every page of your site, but rather abstract that logic out meaning even less work down the road. I’ll show you a quick example.

/resources/library/templateFunctions.php <?php require_once(realpath(dirname(FILE) . "/../config.php"));

function renderLayoutWithContentFile($contentFile, $variables = array()) { $contentFileFullPath = TEMPLATES_PATH . "/" . $contentFile;

// making sure passed in variables are in scope of the template // each key in the $variables array will become a variable if (count($variables) > 0) { foreach ($variables as $key => $value) { if (strlen($key) > 0) { ${$key} = $value; } } }

require_once(TEMPLATES_PATH . "/header.php");

echo "<div id=\"container\">\n" . "\t<div id=\"content\">\n";

if (file_exists($contentFileFullPath)) { require_once($contentFileFullPath); } else { /* If the file isn't found the error can be handled in lots of ways. In this case we will just include an error template. */ require_once(TEMPLATES_PATH . "/error.php"); }

// close content div echo "\t</div>\n";

require_once(TEMPLATES_PATH . "/rightPanel.php");

// close container div echo "</div>\n";

require_once(TEMPLATES_PATH . "/footer.php"); } ?> index.php

This is assuming you have a file called home.php in your templates directory that acts as a content template.

<?php

require_once(realpath(dirname(FILE) . "/../resources/config.php"));

require_once(LIBRARY_PATH . "/templateFunctions.php");

/* Now you can handle all your php logic outside of the template file which makes for very clean code! */

$setInIndexDotPhp = "Hey! I was set in the index.php file.";

// Must pass in variables (as an array) to use in template $variables = array( 'setInIndexDotPhp' => $setInIndexDotPhp );

renderLayoutWithContentFile("home.php", $variables);

?>

home.php <!-- Homepage content --> <h2>Home Page</h2>

<?php

/* Any variables passed in through the variables parameter in our renderLayoutWithContentPage() function are available in here. */

echo $setInIndexDotPhp;

?>

Benefits of This Method Include:

Greater separation of logic and view (php and html). Separating concerns like this makes for cleaner code, and the job of the designer or developer becomes easier as they are mostly working with their respective code.

Encapsulating the template logic into a function allows you to make changes to how the template renders without updating it on each page of your site.

Symlinks

On Unix based systems (os x, linux) there is a neat little feature called symlinks (Symbolic Links). Symlinks are references to actual directories or files on the filesystem. This is really great for when you have a shared resource, such as a library used between multiple projects. Here are a few concrete things you can do with symlinks:

Have two versions of your resource directory. When updating your live server you can upload your latest files into an arbitrary directory. Simply point the symlink to this new directory instantly updating your code base. If something goes wrong you can instantly rollback to the previous (working) directory.

Shared resources are easily managed with symlinks. Say you have a custom library you’ve been working on, any updates to the library you make in one project will be immediately available in another.

Using Symlinks Symlinks vs Hardlinks

Symlinks, or softlinks, act as references to full paths on the filesystem. You can use symlinks in multiple locations and the filesystem treats them as if they were the actual file or directory they reference. Hardlinks on the other hand are pointers to a file on the disk (think shortcuts in windows); they take you to the actual location of the file.

There are a few things you should consider when using symlinks. Your server configuration must be set up to follow symlinks. For Apache this is done in the httpd.conf file. Find the Directory block and make sure that Options FollowSymLinks is there. If not add it and then restart Apache.

<Directory /> Options FollowSymLinks AllowOverride None </Directory> Creating Symlinks in OS X

There are 2 ways to create symlinks in OS X:

Via the command line, navigate (cd, change directory) to the directory in which you want the symlink to be created, then use the following command: $: ln -s /path/to/actual/dir targetDir So if our custom library lives in ~/Sites/libraries/myCustomLibrary we’d cd to where we want to use that library cd ~/Sites/mySite/resources/library and enter: $: ln -s ~/Sites/libraries/myCustomLibrary myCustomLibrary Note that this method should work in all Unix based operating systems.

The alternative is through the finder. By holding alt + cmd while clicking and dragging a file, a Symlink (or alias in os x) that points to the file is created.

Creating Symlinks in Windows

To accomplish this in windows you’ll need to use the mklink command in the command prompt:

C:\mklink /D C:\libraries\myCustomLibrary C:\Users\derek\Sites\mySite\resources\library\myCustomLibrary

Summary

These tips are meant for beginners or those creating simple sites or applications. Ideally for larger applications or sites, you’ll want to consider something more advanced like the MVC architecture and Object Oriented programming. I encourage you to look into these once you’ve gotten your feet wet and feel that you’ve outgrown most of the steps above. I decided not to cover source control as it’s a pretty large subject on its own, but these tips should help you in organizing your files for easier source control if desired (hint: store stuff like layout images in your resource directory and symlink it into your /public_html/img dir). Definitely look in to using source control, like subversion or git for all of your projects.

Hope you find these tips helpful when starting your next PHP Project. Thanks!

Resources

Smarty Templating Engine Multitier Architecture MVC Object Oriented Programming Subversion For Designers (version control) Symlinks Hardlinks

Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Mon, 20 Jul 2009 09:52:00 -0600 http://www.ooopx.net/items/view/3219/organize-your-next-php-project-the-right-way
15 Wonderfully Creative Uses for PHP http://www.ooopx.net/items/view/2934/15-wonderfully-creative-uses-for-php

If you are familiar with the basics of PHP, then you’re probably wondering how you can use it to make your website more appealing. The possibilities are endless, and you can write your own PHP scripts or implement widely available scripts from around the web. Let’s get started with 15 creative uses for PHP for your website!

  1. E-Commerce E-commerce is one of the major uses for PHP. From a small business level to an enterprise level, businesses are always looking to create additional streams of revenue online. If you know how to integrate existing e-commerce solutions or build your own from scratch, this gives you a distinct advantage with your clients. Advanced Coders If you want to build your own shopping cart application, you can either code the entire application from scratch or implement a PHP framework. If you are an intermediate to advanced PHP coder, I personally recommend using a framework such as CodeIgniter or CakePHP. CakePHP has a bakery section with readily available source code for e-commerce applications. For instance, you can integrate Paypal with your site using ready-made scripts. CodeIgniter has a user guide and a few tutorials to get you up and running quickly. Both of these frameworks have extensive documentation on how to create web applications from the ground up; which one you use is really a matter of personal preference. Beginners If you are new to PHP, or you just know some basic PHP programming, I would suggest using an existing e-commerce solution. Some of the available options are:

Magento Zen Cart Shopify

While I understand that each of these solutions has its own quirks, it might be easier to spend a few days with the documentation or a tutorial than to learn PHP from the ground up. It really depends on how much time you are willing to invest in tackling e-commerce.

  1. Project Management Tools For both freelancers and web development firms alike, project management is an important aspect of your business. Your clients need a resource to be able to check the progress of the work and provide feedback. Ideally, with a good project management system in place, your clients will be thoroughly pleased with the end result. There are several excellent web-based project management tools on the market today. If you can afford to use a subscription service, I would highly recommend Basecamp. Although Basecamp was written in Ruby on Rails, it is an excellent advertisement for effective, streamlined project management solutions. For those of us who do not necessarily need a subscription-based product, you can build your own! Building your own project management tool from the ground up will require a bit of in-depth PHP and some Javascript knowledge. The most important aspects of the application are security, time-tracking, collaborative to-do lists, file sharing, a message board, and a live preview of the website - which could simply be a link to an index.html page. Of course, you can add to this list or remove features as you like. The takeaway point here is that you can learn a lot about PHP by creating this application and your customers will be happy to see their project take shape. Showing you how to get started on your own project management tool is beyond the scope of this article, but I hope I have given you a good basis to start generating ideas!

  2. Graphical User Interface For those of you who are up to the challenge, you can extend your PHP installation to create desktop applications. This one is a challenge because it requires some extensive knowledge of PHP and it might also be easier to create desktop applications in other programming languages. If PHP is your favorite programming language, then you can use some of these PHP extensions to get you started creating GUI applications.

PHP GTK - This extension is a popular open source that implements the GIMP toolkit ZZEE PHP GUI - A paid solution that allows you to turn your PHP scripts into Windows applications

The main advantage of creating your own PHP GUI’s is that you will learn a great deal about the language itself!

  1. Building an Online Community Whether your website is about business, entertainment, or products and services, internet users need to feel connected to the product or message. For example, if you develop web applications, a forum where your customers can discuss issues might be a good idea. As a user, if I have a question and I need support right away, a hotline or an e-mail form is often insufficient. With an online community, your visitors can help solve each other’s product-related issues, and even answer technical questions. You still have to provide some level of after-sales support, but a community can effectively decrease your workload and provide useful feedback.

You can build your own PHP-driven online community, or choose from widely available scripts that you can implement into your website. Again, if you plan to build your own forum from scratch, I do recommend the use of a PHP Framework. CodeIgniter, for example, has classes and helpers to take care of the most routine tasks you can think of. Beyond that, you can use several different forum building tools. Some popular ones include:

php BB vBulletin Pun BB

  1. Developing Facebook Applications You can integrate Facebook with your website using PHP. If you have developed Facebook applications using another language or you would like to get started with PHP, the Facebook developer’s wiki can help you to get started. The developer’s wiki explains the Facebook PHP client library and provides detailed instructions on how to install and use the files included in the library. This is certainly worth a look if you are interested in programming for the Facebook platform. For Facebook users interested in the back-end of the platform, this would be a natural step.

  2. Generating PDF Files The PDF format is Adobe’s proprietary file type for document exchange. Using a library called PDFLib, you can generate PDF files with PHP. This library is already included with PHP5; to access it, you need to uncomment the appropriate lines in your PHP configuration file. An example of why creating PDF files might come in useful is, if you were building an online invoicing application and you wanted to output an HTML-generated invoice in PDF format. You can then send the invoice via e-mail or print a copy of it to your client.

  3. Parsing XML Files PHP allows you to parse XML files. Parsing XML is an important feature of PHP 5 because not all browsers can output the contents of an XML file; so you can create a parser in PHP to facilitate this process. Using XML is important for RSS feeds, and also for data storage and rendering data on different devices - for example, cell phones use an implementation of XML called WML (Wireless Markup Language). Working with XML files in PHP is similar to handling the opening, closing, and reading of a file. The steps involved are creating an XML parser, setting functions to handle your opening and closing XML tags, opening the file for reading, reading the file incrementally and then closing it.

  4. Mailing Lists You can write your own script to send e-mail newsletters to your client, or use a ready-made script. PHP mailing lists are an excellent way to keep your clients informed about your services and products, holidays, vacations, and general announcements. Anything your clients need to know can be included in your automated newsletter. The PHP online documentation explains PHP mailing functions in more detail. There are also scripts you can download and install on your website:

PHP list

  1. Image Processing and Generation Using the GD library with PHP, you can do more than just output HTML to the browser! You can output images in different file types including jpeg, png, and gif. This feature of PHP is useful because it allows you to create thumbnail pictures, add watermarks, resize and crop images, and even create a photo gallery!

  2. Create Graphs and Charts Do you need visual representations of numbers on your site? PHP can create graphs and charts too! Using Image_Graph, you can create up to fourteen different types of charts including pie charts, bar graphs, impulse, dot/scatter, step, candlestick, box & whisker, radar. This is incredibly useful for e-commerce websites or websites where you need to present graphical data in a concise manner. the Image_Graph website has more detail on how you can get started!

  3. Content Management Systems One of the most popular uses of PHP is creating or using Content Management System. A good CMS allows your clients to update their website and add content without any in-depth knowledge of HTML and CSS. A good Content Management System should be user friendly, extensible, produce clean URL’s, and be search engine friendly among other things. There are several online resources you can use to assist you with coding your own CMS from scratch, or you can use one of the widely available free or commercial solutions listed below:

Drupal Wordpress Joomla

  1. Create a PHP Photo Gallery By simply using PHP’s file handling functions, you can create your own photo gallery! you begin by placing your photos in a single directory, you then use PHP’s exif function to get header information about the photo and output a thumbnail version of it. The process is as straightforward as it sounds and its also a great way to present your photos!

  2. Create Dynamic Website Templates Using PHP, you can make it easier to add pages and elements to your websites dynamically. You begin by creating the HTML page and splitting it into the header, main content, and footer sections. Add the .php extension to your subsequent pages and use server-side Includes for the header and footer for each new page. You can also have dynamic sidebars and top navigation sections. As a matter of fact, the more “templated” your site is, the easier it is to update the content.

  3. Create Wordpress Plugins If you have done any work with Wordpress, you will know that it is a highly flexible blogging system that you can use to do just about anything from e-commerce to content management. With that being said, if you know some PHP and you delve into the Wordpress Codex, you have everything you need to begin plugin development. If you need novel ideas for creating plugins, they even have a section where users post their plugin ideas. Watch a screencast that teaches how to build your first WordPress plugin.

  4. Creating Flash The use of Flash in websites is a contentious issue to say the least! But there is nothing wrong with having Flash elements in certain places on your website; PHP can help with this! To these files you would use the Ming library to create Flash files in .swf format. With this library, you can generate movies, text, and even animations in Flash!

You’ve just learned fifteen creative uses of PHP which you can use to improve your website or just have fun with - enjoy them all! Any I missed?

Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Mon, 04 May 2009 03:30:00 -0600 http://www.ooopx.net/items/view/2934/15-wonderfully-creative-uses-for-php
5 Quality Sites to Increase Your Knowledge of PHP http://www.ooopx.net/items/view/2943/5-quality-sites-to-increase-your-knowledge-of-php

Recently, a friend of mine asked me if I knew of any good tutorials or websites for people that are beginners to intermediate skill level with php. There are many websites, one could say too many, that have sub par tutorials and tips on php. If you are looking for some quality sites to visit and really increase your knowledge of the language then this post is for you! Join us as we take a look at 5 quality sites to increase your knowledge of php, all of them have been Drew Approvedtm, so you know it's good.

  1. Ennui Design

Ennui design is the website of Jason Lengstorf, a fellow php and MySQL nerd. Jason frequently has quality articles and real world example and implementations on the topic of php. 1. Zend Developer Zone 101

This was perhaps the one series of articles/website that really got me into php enough to be proficient. The tone is anything but boring and the material taught is extremely useful for anyone. Don't let the '101' fool you, I still reference this series of articles from time to time and always find it helpful. 2. Roshan Bhattarai's Blog

I don't personally know Roshan, but I have been through every single php article on the site (yes, I do have a life also) and every one of them I learned a little something knew. His blog isn't only php related, it also features excellent Javascript and MySQL tips as well. 3. PHP Freaks Community and Forum

I am semi-new to the php freaks community, but I love it considering I am myself a php freak. A great way to learn any web or programming language is to lurk around the popular forums and check out the threads. You will learn a lot more thank you think just by looking at the problems others are having or participating yourself. 4. Query 7

I would consider Query7 an intermediate php website and a damn good one at that. A huge plus is that they frequently cover the use of CodeIgniter and API's such as the Google language API. Bonus! Brenelz Web Blog

For a quick bonus I have included Brenelz, who is a good friend of Dev-Tips and myself. Brenelz constantly has experts in the field of php and other languages guest posting on his blog with their tips, as well as great tips from the man himself. After all, Brenelz was the one who first showed me how to use a transparent png-8 without needing any hacks for IE6. And there you have it, five sites plus a bonus site to increase your knowldege of php. And in case you were wondering, here at Dev-Tips, we always start counting from zero

]]>
Wed, 29 Apr 2009 18:40:00 -0600 http://www.ooopx.net/items/view/2943/5-quality-sites-to-increase-your-knowledge-of-php
Diving into PHP: Day 14 http://www.ooopx.net/items/view/2834/diving-into-php-day-14

It’s been a while, but we’re back with Day 14 of our “Diving into PHP” series. Today, we’ll begin researching OOP techniques. We’ll start with a basic overview of classes and functions, and will then move into some more real-world and complicated examples in future tutorials.

Day 12: Files

Subscribe to the Theme Forest RSS Feed.

]]>
Tue, 21 Apr 2009 11:19:00 -0600 http://www.ooopx.net/items/view/2834/diving-into-php-day-14
Add Power to Your PHP With Multi-Tiered Applications http://www.ooopx.net/items/view/2799/add-power-to-your-php-with-multi-tiered-applications

As PHP applications become more and more complex, it can be easy to end up with a tangled mess of code that makes maintenance nearly impossible. Applying the concept of tiered applications can help to alleviate some of the difficulty in maintaining complex applications.

What Do You Mean by Tiered Applications?

Tiered programming is the practice of keeping different components, ideas, or languages separate from each other. In front-end development, tiered markup would be using external stylesheets and JavaScript.

By linking to a CSS file rather than embedding styles in your HTML markup, it becomes easier to change the formatting of your websites because now all styling information is conveniently stored in one place, separated from the markup of the document. And multiple HTML pages can pull in the exact same CSS file, your whole site can be updated style-wise by simply changing one line of CSS.

In back-end development, the same rules apply, but we’re dealing with different components. In broad terms, we’re looking at three tiers: the Database (storing and retrieving data), Business (processing and handling of data), and Presentation (how data is displayed) tiers.

Why Should I Care?

It might not be immediately obvious, but separating your applications into a tiered structure will have a huge impact on your code’s ability to change in the future. For example, if you have a blogging system set up, and it becomes necessary to create an RSS feed for the blog, a properly tiered application would allow you to simply set up an RSS template, then call the database and business functions that you’ve already written.

On the opposite end, if your client suddenly decided that PostgreSQL was a better choice for their organization than MySQL, you would only have to rewrite your database functions, all without touching the business or presentation logic of the application.

In terms of reusability, you could have multiple database functionalities (supporting MySQL, PostgreSQL, and Oracle, for example), that could be easily dropped into new rollouts of your application using just a few lines of code in one place, rather than editing several lines of your code across multiple functions.

The Wrong Way

To start, let’s take a fairly simple task—pulling the title and body text of an entry out of a database, creating a shortened version of the entry, and placing the data into HTML markup—and go about it in entirely the wrong way. In the following code, we’ll write one function to perform all of our tasks:

function displayEntry() { $entryDisp = NULL;

// Get the information from the database $sql = "SELECT title, entry FROM entries WHERE page='blog'"; $r = mysql_query($sql) or die(mysql_error()); while($entry = mysql_fetch_assoc($r)) { $title = $entry['title']; $text = $entry['entry'];

// Create the text preview $textArray = explode(' ',$text); $preview = NULL; for($i=0; $i<24; $i++) { $preview .= $textArray[$i] . ' '; } $preview .= $textArray[24] . '...';

// Format the entries $entryDisp .= <<<ENTRY_DISPLAY

<h2> $title </h2> <p> $preview </p> ENTRY_DISPLAY; }

return $entryDisp; }

This code outputs HTML markup along these lines:

<h2> Entry One </h2> <p> This is the shortened description of entry number one. It displays the first 25 words of the entry and then trails off with an ellipsis... </p> <h2> Entry Two </h2> <p> This is the shortened description of entry number two. It displays the first 25 words of the entry and then trails off with an ellipsis... </p>

Though this might appear logical, it’s actually really undesirable. Let’s go over what makes this code a less-than-optimal approach.

The Problem with This Approach

Poor Legibility—This code is diluted. Its purpose, though documented in the comments (sort of), is tough to discern. If you wrote this, then came back to it in six months, it wouldn’t be instantly clear what was going on, which means a few seconds/minutes wasted trying to interpret your own code.

Too Narrow in Focus—This function is crippled by its specificity: the database query only works for one type of entry; the text preview creation is hard-coded into the function; the formatting is specific to the type of entry being displayed. In order to create a slightly different implementation of this functionality, we’d be forced to create a second function that looked almost exactly the same, even if all we needed to change was the number of words in the text preview.

Lack of Scalability—This is pretty closely related to the idea of being too narrow in focus; if we want to add more functionality (such as a link or an image), our function will get larger and more difficult to manage. And what if we want to add conditions that affect how an entry is displayed? It’s easy to see how programming like this allows for code to quickly become sprawling and unmanageable.

The Big Problem: Lumping Database, Business, and Display Logic

This is the sweeping issue that is causing all of the aforementioned problems.

By combining all three of our logic types, we end up with a narrow, messy, hard-to-manage, nearly-impossible-to-reuse tangle of code.

Imagine an application where each type of display (RSS feed, entry preview, full entry display, etc.) was built with a function like the one above, with the database access, business logic, and presentation logic all written together. Now imagine that there are nine pages on the site, all of which have their own entry display and preview functions.

Even if we assume the application is really simple and that there are only two functions per site page, we’re still looking at almost twenty functions that will need to be updated if changes become necessary.

Improving the Code

To improve the code above, we’ll spread our different types of logic across several functions. If done properly, we should end up with a set of highly reusable, easily understood functions that stack to perform a variety of tasks.

To get started, we’ll plan out the necessary functionality to get a better idea of how it should be constructed:

Retrieve the entry and title columns for a given page from the “entries” table in the database Shorten the body of the entry to a 25-word preview and append an ellipsis Insert the data into HTML tags to display on the user’s browser

As you can see, our plan clearly identifies a database, business, and presentational tier. We can now write functions to fulfill each of these steps with relative ease.

Step 1—The Database Tier

To get information from the database, we’re going to write a very simple function. To encourage good coding practice, I’m going to use the mysqli extension, but I’m not going to focus on how it works. If you’re not using it already, I’d encourage you to explore mysqli or a similar extension (i.e. PDO) to secure your MySQL queries against injection attacks.

So let’s jump right into the code:

function getDataFromDB($page) { /* * Connect to a MySQL server */ $mysqli = new mysqli('localhost', 'user', 'password', 'world'); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; }

/* * Create a prepared statement for pulling all entries from a page / if ($stmt = $mysqli->prepare('SELECT title, entry FROM entries WHERE page=?')) { / * Create a multi-dimensional array to store * the information from each entry */ $entries = array();

/* * Bind the passed parameter to the query, retrieve the data, and place * it into the array $entries for later use */ $stmt->bind_param("s", $page); $stmt->execute(); $stmt->bind_result($title, $entry); while($stmt->fetch()) { $entries[] = array( 'title' => $title, 'entry' => $entry ); }

 /*
  * Destroy the result set and free the memory used for it
  */
 $stmt-&gt;close();

}

/* * Close the connection */ $mysqli->close();

/* * Return the array */ return $entries; }

If you break down what this function is doing, we are literally just requesting two columns (title and entry) from our table (entries), then storing each entry in a multi-dimensional associative array, which is the return value of the function. We pass one parameter, $page, so that we can determine which page we’re grabbing information for. In doing so, we’ve now created a function that will work for every page of our site (provided they all have a ‘title’ and ‘entry’ field).

Notice that our function does nothing to handle the data; it simply acts as a courier, grabbing the information we request and passing it on to whatever comes next. This is important, because if it did anything more, we’d be in the realm of business logic.

Why is it important to separate the business logic from the database logic?

The short answer is that it allows for database abstraction, which essentially means that the data could be migrated from MySQL into another database format, such as PostgreSQL or Oracle, all without changing the data-handling functions (business tier), since the output would still simply be a multi-dimensional associative array containing entries with a title and entry column, no matter what kind of database we’re using.

Step 2—The Business Tier

With the data loaded into our array, we can start processing the information to suit our purposes. In this example, we’re trying to create an entry preview. In the first example, the length of the preview was hard-coded into the function, which we decided is a bad practice. In this function, we’ll pass two parameters to our code: the text to process, and the number of words we want to display as our preview.

Let’s start by looking at the function:

function createTextPreview($text, $length=25) { /* * Break the text apart at the spaces and create the preview variable */ $words = explode(' ', $text); $preview = NULL;

/* * Run a loop to add words to the preview variable / if($length < count($words)) { for($i=0; $i<$length; $i++) { $preview .= $words[$i] . ' '; // Add the space back in between words } $preview .= $words[$length] . '...'; // Ellipsis to indicate preview } else { / * If the entry isn't as long as the specified preview length, simply * return the whole entry. */ $preview = $text; }

/* * Return the preview */ return $preview; }

In the function above, we simply check that the number of words in the supplied entry is greater than the number of words we want to show in our preview, then add words to the newly-created $preview variable one at a time until we hit our target length, at which point we append an ellipsis and return $preview.

Just like in our database tier, we’re keeping the code within the bounds of the business tier. All we’re doing is creating a text preview; there is no interaction with the database, and no presentational elements such as HTML markup.

Step 3—The Presentation Tier

Finally, we need to display the data we’ve retrieved and processed. For our purposes, we’ll be displaying it with extremely simple HTML markup:

<?php $entries = getDataFromDB(); // Load entries into an array foreach($entries as $entry) { /* * Place the title and shortened entry text into two appropriately * named variables to further simplify formatting. Also note that * we're using the optional $length parameter to create a 30-word * text preview with createTextPreview() */ $title = $entry['title']; $preview = createTextPreview($entry['entry'], 30); ?>

<h2> <?php echo $title; ?> </h2> <p> <?php echo $preview; ?> </p>

<?php } // End foreach loop ?>

The idea behind this code is simple: first, load the entries using our database function, then loop through the entries, shortening the entry text using our preview function and then placing the title and entry preview into presentational markup.

Now, in order to change the layout of the entry previews, only two lines of HTML need to be adjusted. This is a far cry less confusing than the original function that handled all three tiers.

Closing Thoughts on Tiered Programming

I’d like to point out that the above example is very basic, and is meant only to demonstrate the concept of tiered programming. The idea is that by keeping the different types of programming logic separated, you can vastly increase the readability and maintainability of your code.

NOTE: There’s a great article on TheDailyWTF.com discussing the use and misuse of tiered software design, and wonderful commentary on the article that presents differing opinions. Multi-tiered applications are extremely useful, but also easy to misunderstand and over-complicate, so remember to thoroughly plan your software before building to avoid causing more problems than you’re solving.

Do you have any thoughts on tiered applications? What steps are you taking to maximize ease of maintenance and future changes in the code you write? Let us know in the comments!

Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Tue, 14 Apr 2009 21:14:00 -0600 http://www.ooopx.net/items/view/2799/add-power-to-your-php-with-multi-tiered-applications
Make an iPhone App Using the Envato API http://www.ooopx.net/items/view/2801/make-an-iphone-app-using-the-envato-api

With the release of the new Envato Marketplace API, third-party developers now have access to a wealth of information to create all kinds of useful applications. This tutorial will teach you how to make your very own iPhone app using data from the new API. Even if you don’t have an iPhone, you can still learn the basics about using PHP and JSON.

Before We Begin The app we will be creating is based off of my iPhone app, Envato Marketplace Mobile. While we won’t be recreating the entire app, this tutorial will give you a general idea on how it was created. This tutorial is aimed at PHP and JSON beginners and serves as a basis for creating more advanced PHP applications. Using the API

Before we can start retrieving data using the API, we must learn how to go about accessing it. The API is split up into 5 parts:

Version : determines what version of the API to use. Username : the user whose data you wish to access. API-key : similar to a password and is unique to each user and grants access to their data. set and format : determine what data to access and what format to provide it in.

For more information on the API, click here. Step 1 - Accessing Our Data Now that we know what is required to access the API, we are ready to put it into practice. Since we want others to use our awesome app, we need to get a username and API key on the fly; so we are going to retrieve some PHP variables from the browser.

if(isset($_GET['user']) && $_GET['user'] != "") { $userName = $_GET['user']; if(isset($_GET['key']) && $_GET['key'] != "") { $apiKey = $_GET['key']; } else { echo 'Api key not set!'; exit; } } else { echo 'Username not set!'; exit; }

The above code checks to see if the variables user and key have been set - and exits if they haven’t. It also checks to make sure that the global variable isn’t empty. Retrieving Our Data Now that we have our required information, we can go ahead and use it to retrieve our data. To do this we will simply create a url using the format outlined in the introduction.

// Creates a string that will be used to access the API $json_url = "http://marketplace.envato.com/api/edge/".$userName."/".$apiKey."/vitals+recent-sales.json";

Notice that we are using the “edge” version and are using our previous variables for the username and api-key. Finally, we are going to retrieve the vitals and recent sales data sets in the JSON format. Now that we have created our url to access the API, we must read its contents so that they may be passed to the json_decode function - which requires an actual json data set, not just a url. So, let’s go ahead and use the file_get_contents() function to read the contents of the url.

// Get the contents of the $json_url string $json_contents = file_get_contents($json_url);

// A little error checking if(!$json_contents) { echo "Error: The JSON file could not be read. Please check your username and api key."; exit; }

We are finally ready to convert the JSON data to an array so that we can use it in our application. To accomplish this task we will use the json_decode() function which will take the data from our $json_contents variable and output it to an array.

// Output our data to an array $json_data = json_decode($json_contents, true);

We are using two parameters in this function, the first is the string we wish to decode, and the second tells the function to output the data as an array. That’s it! We are now ready to show our data to the user. Step 2 - Displaying Our Results We’ve retrieved our data and now it’s time to show it to the user. For the sake of simplicity we will be adding our frontend HTML code into the same file as our PHP code. So go ahead and add the standard HTML document code below your PHP code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>My Nettuts iPhone App - <?php echo $userName; ?></title>

<link rel="stylesheet" href="style.css" type="text/css" /> </head>

<body> <div id="header">My Nettuts iPhone App</div> </body> </html>

Notice that in the <title> tag, I added a simple PHP “echo” statement that will display the user’s name in the browser’s title bar. Getting the Username and Balance Let’s go ahead and add a simple div that displays the username retrieved from the API. We could do this using the $userName variable like we used in the page title, however, using JSON is more exciting.

<div id="username"><?php echo $json_data['vitals']['username']; ?></div>

What the above code does is retrieve the username from the vitals array, which is an array within our $json_data array that was created earlier. Makes sense? Here is the structure of the array used in the API example: Array ( [vitals] => Array ( [username] => ryan [balance] => 32.75 ) ) Next, we want to show the user his balance. This is done the same way as we displayed the username. This time, however, we will simply change from “username” to “balance”. The rest is simply for layout and styling.

<div id="content"> <div class="line"><img src="bank_plus.png" alt="Balance" class="icon" />Balance: $<?php echo $json_data['vitals']['balance']; ?></div> <h3>Recent Sales:</h3>

Listing Recent Sales The last thing on our agenda is to display the most recent sales for a user. This is a little more complicated than the previous examples, however, if you’ve ever worked with arrays you should be able to handle it.

<?php // List Recent Sales $count = 1; $salesArray = $json_data['recent-sales']; foreach($salesArray as $value) { if($count <= 10) { echo "<div class='line'><img src='plus.png' alt='Sale' class='icon' />Sold ".$value['item']." for <strong>$".$value['amount']."</strong></div>"; $count = $count + 1; } else { break; } } ?> </div><!--End Content-->

There’s a lot to digest here so lets start with the foreach statement. First we create a $salesArray from the recent-sales array within $json_data. This isn’t necessary, but I think it looks cleaner. The foreach statement creates a $value for each row in the $salesArray array and allows us to pull information from each row. So, basically you use $value to get data from the row as the foreach statement loops through it. Next up is the code which is executed each time the foreach statement goes through a row. Instead of showing all of the recent sales I only want to list ten, which is why, if the number of rows checked exceeds ten, it will break the loop. To change the number of rows the statement loops through, just change ten to the number you want. Actually displaying the rows is quite simple, as it requires just echoing out each row inside a div with a small icon. We use the $value to access the sale information from the array. We pull “item”, which is the item title and “amount” which is the amount the author made on the sale. Finally “$count + 1″ just increases the count of rows the statement has looped through. You should now be all set! Try loading the file on a testing server and see if it works! If you don’t have a Envato Marketplace account, you can use the example login:

user: ryan key: 26k6otse2s586e4hcbzjy3quq830t3o4

Step 3 - Designing the Frontend Adding CSS

Well, our new app works great, but it looks bad - which means it’s time to break out some CSS. I assume you know enough to understand the following code as I won’t be going into it except for a few things. #browser is used by the iPhone/Touch to make sure that if the page it is too small that it will fill the screen. body.lanscape #browser does the same, however, is for when the browser is in landscape mode.

body { background: #efefef; margin: 0px; padding: 0px; font-family: Helvetica; -webkit-touch-callout: none; -webkit-text-size-adjust: none; width: 100%; color: #2a2a2a; }

browser {

/* ensure we always fill the whole screen */ min-height: 416px; }

body.landscape #browser { min-height: 268px; }

h3 { margin-bottom: 5px; }

p { margin: 0 0 5px 0; }

/* Layout */

header {

padding: 10px 5px 5px; height: 30px; color: #fff; font-size: 22px; background: url(header_bg.jpg) repeat-x; }

username {

font-size: 18px; font-weight: bold; text-transform: uppercase; padding: 5px; /* WebKit supports text-shadow... so why not make it look pretty */ text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5); color: #fff; background: #498929; border-top: 1px solid #85c952; border-bottom: 1px solid #34661c; }

content {

padding: 5px; padding-top: 10px; }

.icon { vertical-align: text-top; margin-right: 5px; } .line { padding-bottom: 5px; border-bottom: 1px solid #cccccc; margin-bottom: 5px;}

iPhone Time It’s time to make your great app finally iPhone compatible. This is actually really easy and involves only one line of code.

<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">

Just add the above code right below the <title> tag and it should be the right size for your iPhone or iPod Touch. That code scales the page to the correct size for viewing on the iPhone. The last thing you may need to do is add a homepage icon so your app looks cool when someone adds your iPhone application as a webclip. To do this we add another small line of code that is similar to a favicon.

<link rel="apple-touch-icon" href="apple-touch-icon.png"/>

Well… we’re all done! You can see the finished product below.

Conclusion You’ve made it to the end. I hope this was a good introduction for those who are still in the beginning stages of using PHP and JSON. You’re now ready to make your own killer app using the API and JSON in general. Now remember, this tutorial is for beginners and those who need a jump-start for using the API.

Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Tue, 14 Apr 2009 09:04:00 -0600 http://www.ooopx.net/items/view/2801/make-an-iphone-app-using-the-envato-api
9 Extremely Useful and Free PHP Libraries http://www.ooopx.net/items/view/2737/9-extremely-useful-and-free-php-libraries

A lot of functionality is shared among applications - like sending emails or preventing spam. In the spirit of reusing the wheel instead of reinventing it, here are nine free web libraries that you can use in your next program which will dramatically increase your efficiency.

  1. ReCAPTCHA The reCAPTCHA library allows you to integrate an advanced CAPTCHA system on your website, which helps keep spam bots from posting on your website. The visual CAPTCHA also includes a helpful audio feature. In addition to the reCAPTCHA service, the library also includes an API for the “Mailhide” service which hides emails from spammers. The API is free and easy to implement on your site and also gives back to the community as it translates scanned books.

Download ReCAPTCHA | Get an API Key | Documentation 2. Akismet Akismet was covered in a previous NETTUTS article. Akismet is a free service that can be used on most small sites - or used on larger sites for a small fee. The library works by comparing comments to a database of existing spam comments provided by other users. The library can then decide to flag the comment for moderation or allow it through. Everyday the library grows and the service improves.

Implement Akismet 3. Services_JSON JSON is a handy format for transmitting human readable data. Not everyone has made the move to PHP5 which has included JSON support since version 5.2.0. This small library enables you to implement JSON functionality into your own applications if you are not using a recent version of PHP.

View Services_JSON 4. Smarty Smarty is a template engine which was formally a sub-project of the PHP project. Smarty provides many powerful features such as loops, variables, and a great caching system. The library has many years under its belt and is nearing its version three release.

Download Smarty | View Documentation 5. pChart In addition to displaying text data in your application, it can also be useful to show data in a more visual format. This can be done with a slew of options like pie charts and bar graphs. pChart is a script that allows you to create charts and graphs from SQL queries or manually provided details. The script is baked by GD to create the images. There is also a main focus on the aesthetics; so it creates some beautiful work.

Download pChart | View Documentation | View Demos 6. SimplePie SimplePie is another article that been covered on NETTUTS a few times. SimplePie allows you to easily pull in syndicated content (like RSS feeds). It’s also been integrated with a lot of different platforms and language sets; it should be able to deal almost any feed in a variety of ways.

Download SimplePie | View Documentation | Extending SimplePie to Parse Unique RSS Feeds 7. XML-RPC PHP Library Applications sometimes use functionality to “ping” other sites when an action has occurred (known as trackbacks). This is done by using a protocol called XML-RPC. The XML-RPC PHP library also allows you to integrate the functionality into your website.

Download XML-RPC PHP | View Documentation 8. Amazon S3 Amazon provides a nice service to work in the cloud, called “S3″. Nettuts+ even uses it to store the images seen in each article. There is a nice Amazon S3 library that doesn’t require any third party tools and allows for large file uploads.

Download Amazon S3 PHP Class 9. PHPMailer Most applications send out an email in some form, but usually rely on the basic php mail() function. PHPMailer is an existing powerful class that allows you to send different types of emails - from basic text to rich formatted emails. These emails can also include attachments or custom headers.

Download PHPMailer | View Documentation

Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Tue, 07 Apr 2009 07:44:00 -0600 http://www.ooopx.net/items/view/2737/9-extremely-useful-and-free-php-libraries
PHP variable variables http://www.ooopx.net/items/view/2740/php-variable-variables

Over the coming weeks I’m going to be writing some posts on object orientated programming in PHP5, but to get us started there are a few techniques that we need to know, so today I’m going to be looking at variable variables. Naming conventions are really important when it comes to variable names in programming and one way we can get around this is by using the value of the variable string as the variable name. to explain this better i’ve put together the following code.

$a = 'Ashley'; $b = 'Papermashup'; $c = 'John'; $d = 'Mark'; $e = 'Luke';

$values = array('a', 'c', 'd'); foreach($values as $seat){ echo $$seat .'<br />'; }

Lets start by looking at the end of the code and more specifically the echo statement. Notice how there are two $ signs, this is because we are saying take the value of $seat and use it as the variable name and we do that by using $$. The rest of the code is pretty self explanatory, a simple array which we loop through to return the values of a, c and d. Variable variables are a good way of trimming down unnecessary code.

]]>
Tue, 07 Apr 2009 02:16:00 -0600 http://www.ooopx.net/items/view/2740/php-variable-variables
Generate RSS Feed with PHP. http://www.ooopx.net/items/view/2686/generate-rss-feed-with-php

This post explains how to create RSS feed for web projects with PHP. It's simple code just you have to include the basic RSS stucture in while loop.

Basic structure of RSS feed.

]]>
Mon, 30 Mar 2009 00:51:00 -0600 http://www.ooopx.net/items/view/2686/generate-rss-feed-with-php
Regex for Dummies: Day 2 http://www.ooopx.net/items/view/2678/regex-for-dummies-day-2

Today, we’ll review the answers to yesterday’s quiz. We’ll then move on to examining PHP and Javascript’s methods for comparing regular expressions against strings.

Day 2: Matching

Be sure to click on the “Full Screen Toggle”. Quiz 1: What’s the difference between PHP’s preg_match() and JavaScript’s “someVariable.match()”? What is returned from each method? 2: True or False: You should wrap quotations around your regular expressions when working with JavasScript. 3: Homework: What is the difference between “greedy” and “lazy” matching?

Subscribe to the ThemeForest RSS Feed for more daily web development screencasts and articles.

]]>
Thu, 26 Mar 2009 13:29:00 -0600 http://www.ooopx.net/items/view/2678/regex-for-dummies-day-2
Regular Expressions for Dummies: 2 http://www.ooopx.net/items/view/2679/regular-expressions-for-dummies-2

We'll review PHP and Javascript's way of matching regular expressions against strings.

]]>
Thu, 26 Mar 2009 13:28:00 -0600 http://www.ooopx.net/items/view/2679/regular-expressions-for-dummies-2
Regular Expressions for Dummies http://www.ooopx.net/items/view/2680/regular-expressions-for-dummies

In the first entry of this new series, we'll review the abilities of each symbol.

]]>
Wed, 25 Mar 2009 12:34:00 -0600 http://www.ooopx.net/items/view/2680/regular-expressions-for-dummies
10 Advanced PHP Tips Revisited http://www.ooopx.net/items/view/2615/10-advanced-php-tips-revisited

Here, on the Smashing Editorial team, we always try to meet the expectations of our readers. We do our best to avoid misunderstandings, and we try to spread knowedge and present only the best design practices and development techniques. However, sometimes we do make mistakes. And when we do, we apologize and do our best to correct what we’ve done. In November 2008 we published the article 10 Advanced PHP Tips To Improve Your Programming. Apparently, according to negative comments to the post, it contained some errors and some statements that are just wrong. We sincerely apologize for our mistake, and we are truly sorry for any inconvenience we caused by it. However, this simple apology is not good enough. To solve the problem, we asked Chris Shiflett and Sean Coates, two PHP gurus, to take a closer look at the article, explain its errors and make it perfectly clear what is actually right and wrong in the theory and practice. This article is a professional response to our article published a couple of months ago. 10 Useful PHP Tips Revisited by Chris Shiflett and Sean Coates This article is a rebuttal to 10 Advanced PHP Tips To Improve Your Programming — henceforth referred to as the previous article — published last November here on Smashing Magazine. The introduction sounds intriguing: Listed below are 10 excellent techniques that PHP developers should learn and use every time they program. Unfortunately, the intrigue devolves into disappointment. We disagree with many of the tips, and even when we don’t, the accompanying explanation is weak or misleading. In this article, we go through each and every tip from the previous article and provide our own commentary and evidence, either to validate and clarify the tip, or to refute it. Our hope is that you don’t just accept our opinion, but rather learn enough to form your own. 1. Use an SQL Injection Cheat Sheet This particular tip is just a link to a useful resource with no discussion on how to use it. Studying various permutations of one specific attack can be useful, but your time is better spent learning how to safeguard against it. Additionally, there is much more to Web app security than SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous. We can provide some much-needed context, but because we don’t want to focus too much on one attack, we’ll first take a step back. Every developer should be familiar with good security practices, and apps should be designed with these practices in mind. A fundamental rule is to never trust data you receive from somewhere else. Another rule is to escape data before you send it somewhere else. Combined, these rules can be simplified to make up a basic tenet of security: filter input, escape output (FIEO). The root cause of SQL injection is a failure to escape output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP apps that construct queries as follows: <?php

$query = "SELECT * FROM users WHERE name = '{$_GET['name']}'";

?> In this case, the value of $_GET['name'] is provided by another source, the user, but it is neither filtered nor escaped. Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted. Assuming we’re using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called “defense in depth” and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity: <?php

// Initialize arrays for filtered and escaped data, respectively. $clean = array(); $sql = array();

// Filter the name. (For simplicity, we require alphabetic names.) if (ctype_alpha($_GET['name'])) { $clean['name'] = $_GET['name']; } else { // The name is invalid. Do something here. }

// Escape the name. $sql['name'] = mysql_real_escape_string($clean['name']);

// Construct the query. $query = "SELECT * FROM users WHERE name = '{$sql['name']}'";

?> Although the use of naming conventions can help you keep up with what has and hasn’t been filtered, as well as what has and hasn’t been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not. Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps: <?php

// Provide the query format. $query = $db->prepare('SELECT * FROM users WHERE name = :name');

// Provide the query data and execute the query. $query->execute(array('name' => $clean['name']));

?> The PDO manual page provides more information and examples. Prepared statements offer the strongest protection against SQL injection. 2. Know the Difference Between Comparison Operators This is a good tip, but it is missing a practical example that demonstrates when a non-strict comparison can cause problems. If you use strpos() to determine whether a substring exists within a string (it returns FALSE if the substring is not found), the results can be misleading: <?php

$authors = 'Chris & Sean';

if (strpos($authors, 'Chris')) { echo 'Chris is an author.'; } else { echo 'Chris is not an author.'; }

?> Because the substring Chris occurs at the very beginning of Chris & Sean, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like Chris is not an author, but he is! This can be corrected with a strict comparison: <?php

if (strpos($authors, 'Chris') !== FALSE) { echo 'Chris is an author.'; } else { echo 'Chris is not an author.'; }

?> 3. Shortcut the else This tip accidentally stumbles upon a useful practice, which is to always initialize variables before you use them. Consider a conditional statement that determines whether a user is an administrator based on the username: <?php

if (auth($username) == 'admin') { $admin = TRUE; } else { $admin = FALSE; }

?> This seems safe enough, because it’s easy to comprehend at a glance. Imagine a slightly more elaborate example that sets variables for name and email as well, for convenience: <?php

if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } else { /* Get the name and email from the database. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; $admin = FALSE; }

?> Because $admin is still always explicitly set to either TRUE or FALSE, all is well, but if a developer later adds an elseif, there’s an opportunity to forget: <?php

if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } elseif (auth($username) == 'mod') { $name = 'Moderator'; $email = 'mod@example.org'; $moderator = TRUE; } else { /* Get the name and email. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; $admin = FALSE; $moderator = FALSE; }

?> If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition. By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether: <?php

$admin = FALSE; $moderator = FALSE;

if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } elseif (auth($username) == 'mod') { $name = 'Moderator'; $email = 'mod@example.org'; $moderator = TRUE; } else { /* Get the name and email. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; }

?> Regardless of what the rest of the code does, it’s now clear that $admin is FALSE unless it is explicitly set to something else, and the same is true for $moderator. This also hints at another good security practice, which is to fail safely. The worst that can happen as a result of not modifying $admin or $moderator in any of the conditions is that someone who is an administrator or moderator is not treated as one. If you want to shortcut something, and you’re feeling a little disappointed that our example includes an else, we have a bonus tip that might interest you. We’re not certain it can be considered a shortcut, but we hope it’s helpful nonetheless. Consider a function that determines whether a user is authorized to view a particular page: <?php

function authorized($username, $page) { if (!isBlacklisted($username)) { if (isAdmin($username)) { return TRUE; } elseif (isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } else { return FALSE; } }

?> This example is actually pretty simple, because there are only three rules to consider: administrators are always allowed access; those who are blacklisted are never allowed access; and isAllowed() determines whether anyone else has access. (A special case exists when an administrator is blacklisted, but that is an unlikely possibility, so we’re ignoring it here.) We use functions for the rules to keep the code simple and to focus on the logical structure. There are numerous ways this example can be improved. If you want to reduce the number of lines, a compound conditional can help: <?php

function authorized($username, $page) { if (!isBlacklisted($username)) { if (isAdmin($username) || isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } else { return FALSE; } }

?> In fact, you can reduce the entire function to a single compound conditional: <?php

function authorized($username, $page) { if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) { return TRUE; } else { return FALSE; } }

?> Finally, this can be reduced to a single return: <?php

function authorized($username, $page) { return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)); }

?> If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive. This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply: <?php

function authorized($username, $page) {

if (isBlacklisted($username)) {
    return FALSE;
}

if (isAdmin($username)) {
    return TRUE;
}

return isAllowed($username, $page);

}

?> This uses more lines of code, but it’s very simple and unimpressive (we’re proudest of our code when it’s the least impressive). More importantly, this approach reduces the amount of context you must keep up with. For example, as soon as you’ve determined whether the user is blacklisted, you can safely forget about it. This is particularly helpful when your logic is more complicated. 4. Drop Those Brackets Based on the content of this tip, we believe the author means “braces,” not brackets. “Curly brackets” may mean braces to some, but “brackets” universally means “square brackets.” This tip should be unconditionally ignored. Without braces, readability and maintainability are damaged. Consider a simple example: <?php

if (date('d M') == '21 May') $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud');

?> If you’re good enough, smart enough, secure enough, notorious enough, or pitied enough, you might want to party on the 21st of May: <?php

if (date('d M') == '21 May') $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); party(TRUE);

?> Without braces, this simple addition causes you to party every day. Perhaps you have the stamina for it, so the mistake is a welcome one. Hopefully, the silly example doesn’t detract from the point, which is that the excessive partying is an unintended side effect. In order to promote the practice of dropping braces, the previous article uses short examples such as the following: <?php

if ($gollum == 'halfling') $height --; else $height ++;

?> Because each condition is constrained to a single line, such mistakes might be less likely, but this leads to another problem: inconsistencies are jarring and require more time to read and comprehend. Consistency is such a valued quality that developers often abide by a coding standard even if they dislike the coding standard itself. We recommend always using braces: <?php

if (date('d M') == '21 May') { $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); party(TRUE); }

?>

You’re welcome to party every day, but make sure it’s deliberate, and please be sure to invite us! 5. Favor str_replace() Over ereg_replace() and preg_replace() We hate to sound disparaging, but this tip demonstrates the sort of misunderstanding that leads to the same misuse it’s trying to prevent. It’s an obvious truth that string functions are faster at string matching than regular expression functions, but the author’s attempt to draw a corollary from this fails miserably: If you’re using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace(). Because str_replace() does not support pattern matching, this statement makes no sense. The choice between string functions and regular expression functions comes down to which is fit for purpose, not which is faster. If you need to match a pattern, use a regular expression function. If you need to match a string, use a string function. 6. Use Ternary Operators The benefit of the ternary operator is debatable (there’s only one, by the way). Here is a line of code from an audit we performed recently: <?php

$host = strlen($host) > 0 ? $host : htmlentities($host);

?> Oops! The author actually means to escape $host if the string length is greater than zero, but instead accidentally does the opposite. Easy mistake to make? Maybe. Easy to miss during a code audit? Certainly. Concision doesn’t necessarily make the code any better. The ternary operator may be fine for one-liners, prototypes, and templates, but we strongly believe that an ordinary conditional statement is almost always better. PHP is descriptive and verbose. We think code should be, too. 7. Memcached Disk access is slow. Network access is slow. Databases typically use both. Memory is fast. Using a local cache avoids the overhead of network and disk access. Combine these truths and you get memcached, a “distributed memory object caching system” originally developed for the Perl-based blogging platform LiveJournal. If your application isn’t distributed across multiple servers, you probably don’t need memcached. Simpler caching approaches — serializing data and storing it in a temporary file, for example — can eliminate a lot of redundant work on each request. In fact, this is the sort of low-hanging fruit we consider when helping our clients tune their apps. One of the easiest and most universal ways to cache data in memory is to use the shared memory helpers in APC, a caching system originally developed by our colleague George Schlossnagle. Consider the following example: <?php

$feed = apc_fetch('news');

if ($feed === FALSE) { $feed = file_get_contents('http://example.org/news.xml'); // Store this data in shared memory for five minutes. apc_store('news', $feed, 300); }

// Do something with $feed.

?> With this type of caching, you don’t have to wait on a remote server to send the feed data for every request. Some latency is incurred — up to five minutes in this example — but this can be adjusted to as close to real time as your app requires. 8. Use a Framework All decisions have consequences. We appreciate frameworks — in fact, the main developers behind CakePHP and Solar work with us at OmniTI — but using one doesn’t magically make what you’re doing better. In December, our colleague Paul Jones wrote an article for PHP Advent called The Framework as Franchise, in which he compares frameworks to business franchises. He refers to a suggestion by Michael Gerber from his book “The E-Myth Revisited”: Gerber notes that to run a successful business, the entrepreneur needs to act as if he is going to sell his business as a franchise prototype. It is the only way the business owner can make the business operate without him being personally involved in every decision. This is good advice. Whether you’re using a framework or defining your own standards and conventions, it’s important to consider the value from the perspective of future developers. Although we would love to give you a universal truth, extending this idea to suggest that a framework is always appropriate isn’t something we’re willing to do. If you ask us whether you should use a framework, the best answer we could give is, “It depends.” 9. Use the Suppression Operator Correctly Always try to avoid using the error suppression operator. In the previous article, the author states: The @ operator is rather slow and can be costly if you need to write code with performance in mind. Error suppression is slow. This is because PHP dynamically changes error_reporting to 0 before executing the suppressed statement, then immediately changes it back. This is expensive. Worse, using the error suppression operator makes it difficult to track down the root cause of a problem. The previous article uses the following example to support the practice of assigning a variable by reference when it is unknown if $albus is set: <?php

$albert =& $albus;

?> Although this works — for now — relying on strange, undocumented behavior without a very good understanding of why it works is a good way to introduce bugs. Because $albert is assigned to $albus by reference, future modifications to $albus will also modify $albert. A much better solution is to use isset(), with braces: <?php

if (!isset($albus)) { $albert = NULL; }

?> Assigning $albert to NULL is the same as assigning it to a nonexistent reference, but being explicit greatly improves the clarity of the code and avoids the referential relationship between the two variables. If you inherit code that uses the error suppression operator excessively, we’ve got a bonus tip for you. There is a new PECL extension called Scream that disables error suppression. 10. Use isset() Instead of strlen() This is actually a neat trick, although the previous article completely fails to explain it. Here is the missing example: <?php

if (isset($username[5])) { // The username is at least six characters long. }

?> When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $username[5] is the sixth character in $username.) The reason this is slightly faster than strlen() is complicated. The simple explanation is that strlen() is a function, and isset() is a language construct. Generally speaking, calling a function is more expensive than using a language construct. About the Authors Hi, we’re Chris Shiflett and Sean Coates. We work together at OmniTI (“the most important web company you’ve never heard of”), blog about PHP and other stuff at shiflett.org and seancoates.com, curate PHP Advent, and do the Twitter thing as @shiflett and @coates. (al)

© Smashing Editorial for Smashing Magazine, 2009. | Permalink | 11 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine

Post tags: coding, php, programming, tips, web-development

]]>
Tue, 24 Mar 2009 10:24:00 -0600 http://www.ooopx.net/items/view/2615/10-advanced-php-tips-revisited
Display your Feedburner stats http://www.ooopx.net/items/view/2558/display-your-feedburner-stats

I’ve been away for the last week. My wife and I bought a flat in North London and finally moved in on March 16th. So I’m currently without the internet and won’t have it until the end of March which is frustrating when I want to update my blog but simply can’t so please excuse my infrequent posts over the next few weeks. Here’s a quick piece of code to simply display your feedburner stats on your blog. I’m yet to post my stats publicly on my blog but have seen numerous blogs with the standard feedburner badge which I think is quite ugly. So here’s how to just get the stats using PHP and CURL. You can then style it how you like.

$ch = curl_init(); //set the feed url and options plus a timeout value $timeout=5; curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=AshleyFord-Papermashupcom'); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $result = curl_exec($ch); // get just the subscriber number using the regex function $subscribers = get_match('/circulation="(.*)"/isU',$result);

echo 'Papermashup.com has <strong>'.$subscribers.'</strong> subscribers';

//close connection curl_close($ch);

function get_match($regex,$result) { preg_match($regex,$result,$matches); return $matches[1]; }

]]>
Fri, 20 Mar 2009 09:13:00 -0600 http://www.ooopx.net/items/view/2558/display-your-feedburner-stats
Diving into PHP: Day 13 http://www.ooopx.net/items/view/2479/diving-into-php-day-13

Hey everyone. Just a note that Day 13 of this series was posted on the nettuts+ blog. I’m hoping to attract more subscribers, so that we can ultimately put even more effort into bringing you great tutorials. Feel free to ask questions on either site. Watch it now!

]]>
Thu, 12 Mar 2009 11:45:00 -0600 http://www.ooopx.net/items/view/2479/diving-into-php-day-13
Diving into PHP: 13 http://www.ooopx.net/items/view/2524/diving-into-php-13

At the request of one of our readers, we'll take a look at how to upload files with PHP.

]]>
Wed, 11 Mar 2009 13:46:00 -0600 http://www.ooopx.net/items/view/2524/diving-into-php-13
Creating a File Hosting Site with CodeIgniter http://www.ooopx.net/items/view/2457/creating-a-file-hosting-site-with-codeigniter

I have seen a few introductory tutorials for Codeigniter, and was hoping to show you something a little more advanced. This tutorial will show you how to build a powerful web application for hosting images, using the flexibility of Codeigniter. This tutorial should teach you about the MVC coding philosophy, integral to producing serviceable applications.

Step 1: Setup Before we go anywhere near the code, we need to do some setup. Fire up your favorite database editor (I’ll be using SQLBuddy) and create a new database called ‘uploadr’. Inside this, create two tables: ‘users’ and ‘files’. Set up users to have a primary-key, auto-numbered ‘id’ column, along with two varchar columns: ‘password’ and ‘username’. The files table needs another ‘id’ column (again primary-key and auto-numbered), as well as an integer ‘owner’ column, and a varchar ‘name’ column.

Since this tutorial is focussed on learning Codeigniter programming and about MVC, we are going to forgo all of the styling stuff (like CSS, photoshop). To this end, I’ve created a custom Codeigniter install for you, with all the files created, and the views (mostly) HTML-d and CSS-d. The two things you’ll need to change are the config and database settings. I even included a “Beta” stamp, so it’d feel even more like a web-startup!

Step 2: Registration Now onto the first bit of meat! Open up the ‘login.php’ controller and create a function called ‘register’. This is going to control the entire registration process. First, we need to check whether any POST requests have been sent to the server. In this case, these will signify someone trying to register. We can do this by checking whether $_POST['username'] is set. If it is, then we know someone has tried to register, and can enter it into the DB.

function register() { if(isset($_POST['username'])){

// User has tried registering, insert them into database.

$username = $_POST['username']; $password = $_POST['password'];

$this->users->register($username, $password);

redirect('login');

} else{ //User has not tried registering, bring up registration information. $this->load->view('register'); } }

If the user has yet to try registering, it detects this and automatically sends them to the ‘register’ view that I’ve coded for you. You’ll notice the line: $this->users->register($username,$password); This is calling the function ‘register’ in the model ‘users’. At the moment this will not work, since we haven’t loaded the model. We do this in the same way as loading views, but since we are going to be using this model extensively throughout this class, we will load it in the constructor function (the function with the same name as the class), so that it is always loaded and available:

function Login() { parent::Controller(); $this->load->model('users'); }

You’re probably interested in what the registration function actually contains. Well, it simply uses a couple of Codeigniter’s active record functions, which allow for DB manipulation. The big advantage of using Codeigniter’s built in active record functions (besides the fact that they’re nice and simple) is that they’re database agnostic: you can easily switch in and out different database types (for example mySQL, SQLite) in the DB config file without affecting the application. In the case of our registration, we’re adding an entry to the users table. Create this function in the ‘users.php’ model:

function register($username, $password) { $new_user = array ( 'username'=>$username, 'password'=>$password );

$this-&gt;db-&gt;insert(&#39;users&#39;, $new_user);

return true; }

The only thing worth noticing in the registration view are the site_url() and base_url() functions. These respectively give your site’s URL with and without the index.php/ suffix. The greatest advantage to them is that you can change your site’s URL structure without having to go through all the links: it just takes one change in your config file. Once this is all setup, we can try registering an account. The function in our controller should redirect us to the login page again after our account is created. Step 3: Login Now that we have a few users set up, we need a way of actually letting them into the site. For this, we are going to use Codeigniter’s sessions class. Although this actually uses cookies, it works in a very similar way to normal PHP sessions, just with more options (I recommend you check the userguide). To start with, we need to create the function that the login button currently points to, ‘go’. This function will need to collect the information that the form has submitted, and then check it against the DB using a model. If all is correct, it’ll start a session, and redirect the user to their files. If they mistyped their information, they’ll be redirected to the login page.

function go() {

$username = $_POST['username']; $password = $_POST['password'];

//Returns userid if successful, false if unsuccessful $results = $this->users->login($username,$password);

if ($results==false) redirect('login'); else { $this->session->set_userdata(array('userid'=>$results)); redirect('profile'); }

}

Parts of this function should look very familiar to you from the register function: it collects $username and $password, before submitting them to a model (this time ‘login’). After this however, the differences begin to occur. It then checks to see if the login has failed; if it has, then the user is redirected back to the login page. However, if the login is successful then the script creates a session, setting ‘userid’ to the users id. All that we need now for the login script to work is the model. Add this function to the ‘users’ model we used earlier:

function login($username, $password) {

$query = $this->db->get_where('users', array('username'=>$username, 'password'=>$password));

if ($query->num_rows()==0) return false; else{ $result = $query->result(); $first_row = $result[0]; $userid = $first_row->id;

return $userid; }

}

A quick rundown: first, it queries the database looking for any users with exactly the same username and password. If it doesn’t find any, then the number of rows will be 0, and the function returns false. If somebody was found, then it uses another of Codeigniter’s active record functions to load it as an object. This objects comes as an array of DB rows, each containing an object with that rows information. Since we want the first and only row, we take it out of $result, and then return the id from it. We will need to check whether the user is logged in whilst on the profile page. To do this, we simply insert two lines of code into the constructor of the profile controller. This will check that the session contains a userid. If it doesn’t, then redirect to the login page. If it does, then all is fine, and it gets turned into a public variable. Whilst we’re changing the constructor, we will load the two models that we will need for the profile page:

function Profile() { parent::Controller();

$this->load->model('users'); $this->load->model('files');

$this->userid = $this->session->userdata('userid'); if (!isset($this->userid) or $this->userid=='') redirect('login'); }

The final thing we need to do is make it possible to logout. This is achieved by simply setting the userid to nothing, deleting it. All it requires is one simple function:

function logout() { $this->session->set_userdata(array('userid'=>'')); redirect('login'); }

Step 4: Viewing and Uploading Files Right then, we’ve just logged in for the first time. What are we greeted with?

Not bad, not bad, although that ’sample file’ isn’t being generated from our database, it’s static. We’ll rectify that soon, but first we need to change the permissions of the ‘file’ folder so that Codeigniter can read and write on it. I changed it to 777 Permissions:

Now that that’s out of the way, let’s get back to some coding! We need to load all the users files out of the database, and to do that we’re going to need… … a model! This time however, we’re going to create it in the ‘files.php’ model, so we keep our user table and file table separate. Insert this function:

function get($userid) { $query = $this->db->get_where('files', array('owner'=>$userid)); return $query->result(); }

This again draws from earlier sections of this tutorial, so you should be able to understand it. Basically, it gets all the rows where the owner = the user’s id, and returns them in a nice array of objects. Let’s create something in the ‘profiles’ controller to interface with it, and to pass the info onto the view. Amend the index function with this:

function index() { $data['files'] = $this->files->get($this->userid); $this->load->view('profile', $data); }

Again, a very simple function. It takes the results passed to it from the files model, and packages them to the view. Codeigniter passes data to the view usually through an array (in this case data). It will then automatically explode the array into lots of variables, so when we go to the view, it will be able to access the database results through $file, rather than $data['file']. Let’s put this lovely database result into the view! Stick this into ‘profile.php’, replacing the code that the HTML comment tells you to.

<?php foreach($files as $file): ?>

<div class="section"> <span><?=$file->name?></span> <div style="float: right;"> <span><a href="<?=base_url()?>files/<?=$file->name?>">View</a></span> <span><a href="<?=site_url("profile/delete/".$file->id)?>">Delete</a></span> </div> </div>

<?php endforeach; ?>

The foreach loop loads each row of the array in turn, and makes it accessible via the $file object. We then, using the sample “section” as a template, fill in all the links and the name with information for the new $file object. We will how the delete function works later, and how the view link works after we’ve uploaded something. If you open this in your browser now, you won’t see anything. This is because we haven’t got any files uploaded! Well, we need to rectify that, so we’ll need to make an uploading form. Let’s do the controller first; open ‘profile.php’ and add this function:

function upload() { if(isset($_FILES['file'])){ $file = read_file($_FILES['file']['tmp_name']); $name = basename($_FILES['file']['name']);

write_file('files/'.$name, $file);

$this->files->add($name); redirect('profile'); }

else $this->load->view('upload'); }

This function adds quite a few new things: especially Codeigniter’s file handling. It starts off fairly simply, checking to see whether a form has been submitted by looking for a file. If the file doesn’t exist, it simply shows the upload view (which we’ll be updating next). If the file does exist, then it extracts reads the temporary file that the server has generated. The directory of the temporary file can be found at $_FILES['your_file']['tmp_name'], and the file can be read from this directory by Codeigniter’s read_file. This loads all of the files information into the $file variable. The next line gets the file’s name from the global $_FILES in a similar way to getting the temporary directory. Armed with these two pieces of information, codeigniter writes the file to the files folder in the same directory as it’s index file. Lastly, the file needs to be added to the database. Again, we’re going this with a model, this time the ‘add’ function in ‘files’. We’ll see how that works in a minutes, but we now need to create the uploading form in the view. Add this where the ‘upload.php’s HTML comment tells you to:

<form enctype="multipart/form-data" action="<?=site_url('profile/upload')?>" method="post">

<div id="boxtop"></div><div id="boxmid">

<div class="section"> <span>File:</span> <input type="file" name="file" /> </div>

</div><div id="boxbot"></div>

<div class="text" style="float: left;"><p>Before uploading, check out</p><p>the <a href=#>Terms of Service</a>.</p></div> <div class="text" style="float: right;">

<input type="submit" value="Upload" name="upload" class="submit" /> </div> <br style="clear:both; height: 0px;" />

</form>

Replace the current HTML with this. The important thing to note here is that when we’re uploading files, we use an input type=file, which allows us to pick a file to upload. Also, we have to specify an enctype in our form tag, so that the server knows that it’s recieving a file and to save it. Not too interesting to us back-end coders, but still crucial! Let’s have a quick look at what we’ve created:

Now we move onto the final bit of the file uploading script, the model. This adds the file to the database, with it’s name and owner, so the server knows which files belong to whom. Let’s take a look; add this to your ‘files’ model:

function add($file) { $this->db->insert('files', array('owner'=>$this->session->userdata('userid'),'name'=>$file )); }

Again leveraging Codeigniter’s active record functionality, we add a row to the database with the name of the file and the owner. We get the owner by finding the users id from the session data that we saved earlier when logging on. All in all, a very simple function. Let’s trying uploading a nice photo, eh?

Et, Voila!

Looking into the ‘files’ folder, we see that the file that we uploaded has appeared there, as if by magic (Codeigniter magic!), and we see why the view link works, since it simply points directly to the file in the directory. With this done, all that remains for this tutorial is deleting files. Step 5: Deleting Files Ok, the last bit. This shouldn’t take so long, since you’ll be able to utilize the ideas that you learnt earlier to understand this. First we’ll add this code to our ‘profiles’ controller:

function delete($id) { //This deletes the file from the database, before returning the name of the file. $name = $this->files->delete($id); unlink('files/'.$name); redirect('profile'); }

And this code to our ‘files’ model:

function delete($fileid) { $query = $this->db->get_where('files',array('id'=>$fileid)); $result = $query->result(); $query = $this->db->delete('files', array('id'=>$fileid)); return $result[0]->name; }

The first controller should be very easy to understand. It calls the delete function from the files model (which we defined at the same time), which generates the name of the file. It then uses a basic PHP function to delete the file with that name in the files directory. Finally, it sends back to the users profile (which is now minus one file). The model is slightly more complex. It needs to return the name of the file as well as deleting it, so first it queries the database to get the files details. It loads this into the $result variable, and then goes on to delete the file. It then returns the ‘name’ column of the first row of the array (the only row that the query returned), which is then used in the above controller. Let’s try to delete a function:

And click delete…

Hooray! It worked. I guess we’re all done then! Final Thoughts Delete Files Of course, this code should not be run on a server without some serious improvements. Here are a few major problems with it:

The passwords are all unencrypted. This means that if anyone should break into your database, they will be able to steal all of your users data with minimal effort. As I’m sure you’ll all agree: not good. This could easily be solved by adding some simple hashing to the passwords.

The files are not private. A user may want to ensure that the files they upload are only visible by them, and not by someone who just guesses a bunch of urls. This would probably require another controller for serving the files (which checks for session data).

The script does not check that files exist before writing files. This could cause conflicts with your files, or it could result in file data being overwritten. Whichever: not good. This could be solved with a simple DB check to ensure that the file has not been taken, and could be minimized by giving users their own directories within the files folder.

No errors are being generated. This doesn’t exactly help the user find out what they’re doing wrong, and although this isn’t (too) much of a problem on such a small site with such limited actions, it still could be improved.

All in all, you’ve created quite a powerful little web application, especially due to the small amount of code that you had to write. Due to Codeigniter’s nature, it’s quite easily extended, both to resolve the above problems, and to add new features, like renaming files. I also hope that this tutorial taught you a bit about using MVC concepts, and the power that they bring: by simply adjusted the models on our application, we can swap our the DB for text files, XML or anything, and by changing the views, we can completely re-theme without breaking functionality. Amazing!

Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

]]>
Wed, 11 Mar 2009 03:30:00 -0600 http://www.ooopx.net/items/view/2457/creating-a-file-hosting-site-with-codeigniter
Diving into PHP: Day 12 http://www.ooopx.net/items/view/2458/diving-into-php-day-12

We’ll take a short break from working with MySQL in order to analyze how to work with the file system. Today, you’ll learn how to use the “file” function, as well as “fopen”, “fgets”, and “fputs”.

Day 12: Files

Be sure to click on the “Full Screen Toggle”.

Subscribe to the Theme Forest RSS Feed.

]]>
Tue, 10 Mar 2009 09:22:00 -0600 http://www.ooopx.net/items/view/2458/diving-into-php-day-12
Add Gravatars to your wordpress theme http://www.ooopx.net/items/view/2425/add-gravatars-to-your-wordpress-theme

A few days ago I was looking around the internet for a solution on how to add Gravatar avatars to my Wordpress comments section, and I found out that its easier than I originally thought! I thought there might be quite a bit of code to implement but found out that it requires just one line of PHP. So here are the steps to adding user Gravatars to your comments. Step One The first thing to do i log into your blog and under ‘Settings’ click ‘Discussion’ scroll down to ‘Avatars’ and make sure that you have avatars turned on as shown below.

Once the you have chosen your setup as above you are ready to add the code into your comments template. Step Two Now under ‘Appearance’ select ‘Editor.’ In the right hand column you should see all the files that refer to your current theme. Select ‘Comments comments.php’ the template code for the comments section of your blog will now load in the main window where you can make changes and edit the code. Dependent upon how your theme is structured you should be able to roughly work out where the comments are pulled in as in the image below. I have highlighted where i have added the line of code to pull in users avatars, each comment is placed in a list item. The Gravatar code is then added straight after the opening list item tag. Add this single line of code.

<?php if(function_exists('get_avatar')) { echo get_avatar($comment, '40'); } ?>

And that’s it! Want to see a demo? then leave a comment below and you’ll see the avatars. You will need to style the position of the avatars, size etc which is controlled by the class .avatar

]]>
Mon, 09 Mar 2009 02:02:00 -0600 http://www.ooopx.net/items/view/2425/add-gravatars-to-your-wordpress-theme