Discover & Rate New Music Check out ChartVote. Promote the music you like.

PHP Framework Round Up

Software frameworks have become very popular in the last few years, mainly due to the explosive popularity of Ruby on Rails, making frameworks the new hip thing to use for development and a great buzzword to throw around like its candy.

Personally, I don’t use frameworks for my projects. I find them too constricting and I feel that I lose control over my development process, but thats just me. Some people swear and live by frameworks. Maybe one day I will find one that suits me.

Model-View-Controller (MVC) Architecture

MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

  • The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your your database.
  • The View is the information that is being presented to a user.
  • The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

mvc.png

PHP Frameworks

  • CakePHP is a PHP framework that works on the MVC architecture and offers caching, application scaffolding, validation of model data and even a presentation API. One of the most popular PHP frameworks.
    cakephp.png
  • CodeIgniter is a PHP framework that also uses the MVC platform, has classes for data access, e-mail, FTP, and XML-RPC. Also, CodeIgniter has an exciting community and thorough documentation to get you started.
    codeigniter.gif
  • The Zend Framework is the self-proclaimed “leading open-source PHP framework.” Services included in the API include Ajax (JSON), search, syndication, web services, and a fully object oriented PHP class library.
    zend.gif
  • Symfony - A feature packed framework, but has a reputation for being server-intensive.
  • Prado - A component framework for PHP5 that has similar event based web apps similar to ASP.NET.
  • BareBones - a one-file, no-configuration, MVC framework for PHP5.

Source @ SmashingMagazine.com

Create a “back” button with PHP

Deziner Folio posted this PHP snippet for creating a simple back link that will take you to the previous page you were on.

Code:

PHP:
  1. <?php session_start(); ?> <!– Starting a session before the DOCTYPE –>
  2.  
  3. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
  4. “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
  5.  
  6. <a href=”<?php echo $_SESSION[’back’]; ?>“>back</a> <!–The anchor tag that links to the previous page –>
  7.  
  8. <?php $_SESSION[’back’] = $_SERVER[’REQUEST_URI’]; ?> <!– Assigning the current URL to a session variable –>

Please note that first we assign the previous session variable to the anchor tag and only then re-assign the current URL to the session variable which will be read when you move on to the next page.

This being a simple PHP snippet can be used in almost every CMS (PHP based) and sure is a good addon to the accessibility of your site.

You can view the original article here

Recover Truncated PHP Serialized Arrays

Shaun Inman has posted a great function that will salvage all the data that it can in a serialized array that has been truncated. PHP's unserialize() function will fail if it encounters a malformed string. This is where repairSerializedArray() function comes in to save the day.

PHP’s native serialization text format is the simplest way to store an arbitrary array in a database without losing the types of its many values or their structure within the array. However, you might occasionally run into problems when the serialized string is longer than the database column that houses it. The resulting truncated string cannot be unserialized by PHP. The majority of the data might still be intact but PHP doesn’t know what to do with it; so I wrote a function, two actually, that does. (While PHP’s serialize() and unserialize() functions also work with objects this recovery function does not.)

Because the recursive function operates on and whittles down the actual serialized string while it attempts its recovery, a second function duplicates and prepares the string leaving the original unchanged.

Code Example

PHP:
  1. // the native unserialize() function returns false on failure
  2. $data = @unserialize($serialized); // @ silences the default PHP failure notice
  3. if ($data === false) // could not unserialize
  4. {   
  5.     $data = repairSerializedArray($serialized); // salvage what we can
  6. }

You can read the full post and download the code here

Random Images with PHP

Devlounge has posted an article for displaying random images with PHP.

Every now and then you want to randomize images, usually headers of sorts. This is pretty simple, with just 9 lines of PHP code you can rotate randomly between two images.

PHP:
  1. <?php
  2.     $images = array(
  3.         0 => 'image1.gif',
  4.         1 => 'image2.gif',
  5.     );
  6.     $image = $images[ rand(0,(count($images)-1)) ];
  7.     $output = "<img src=\"/mysite/randomimages/".$image."\" alt=\"\" border=\"0\" />";
  8.     print($output);
  9. ?>

This will rotate between image1.gif and image2.gif, which are located in /mysite/randomimages/ on your server.

Check out the full post here

Limit File Download Speed with PHP

This PHP code will limit the download rate for a file being downloaded by a client. This is useful if you are streaming MP3s from your site and you are trying to distribute your bandwidth as evenly as possible.

For example: If you are streaming MP3s with a bitrate of 96kb then you would at the minimum only need to send 12KB/s of data to the client. Now to be safe I would send around 16KB/s to allow some buffering just in case some packets get held up somewhere.

Code

PHP:
  1. <?php
  2.  
  3. $file = "/path/to/file/test.mp3"; // path to file
  4. $speed = 16; // 16 kb/s download rate limit
  5.  
  6. header("Cache-control: private");
  7. header("Content-Type: application/octet-stream");
  8. header("Content-Length: ".filesize($file));
  9. header("Content-Disposition: filename=$file" . "%20");
  10.  
  11.  
  12. $fd = fopen($file, "r");
  13. while(!feof($fd)) {
  14.     echo fread($fd, round($speed*1024));
  15.     flush();
  16.     sleep(1);
  17. }
  18.  
  19. fclose ($fd);
  20.  
  21. ?>

Random Password Generator with PHP

This function will generate a random password based off of a character list that you specify. This is very useful for a user registration form.

Example: Instead of asking a user for their desired password on a sign up form, generate a random one for them and email it to them. This poses less of a security risk by emailing them a random password and less fields for them to to fill out when signing up.

PHP:
  1. function randomPassword($length = 7) {
  2.   // empty password
  3.   $password = "";
  4.   // define possible characters
  5.   $possible = "23456789abcdefghjkmnpqrstuvwxyz";
  6.   // add random characters until $length is reached
  7.   $i = 0;
  8.   while ($i <$length) { 
  9.     // pick a random character from the possible ones
  10.     $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
  11.     // don't allow duplicate characters
  12.     if (strpos($password, $char) === false) {
  13.       $password .= $char;
  14.       $i++;
  15.     }
  16.   }
  17.   return $password;
  18. }

List all files in a directory with PHP

This code snippet displays a hyper linked list of all the files contained in a specified folder. I find myself always coming back to this very useful piece of code. I can't count how many times I've used this.

PHP:
  1. <?
  2.     // Define the full path to the folder whose contents you want to list
  3.     $path = "/home/user/public/foldername/";
  4.     // Open the directory
  5.     $dir_handle = @opendir($path) or die("Error opening $path");
  6.     // Loop through the files
  7.     while ($file = readdir($dir_handle)) {
  8.       if($file == "." || $file == ".." || $file == "index.php" ) { continue; }
  9.    
  10.       echo "<a href=\"$file\">$file</a><br />";
  11.     }
  12.     // Close
  13.     closedir($dir_handle);
  14. ?>

MySQL Update on Duplicate entries for Inserts

Particletree has a great article on a MySQL query that updates a record in a database when trying to insert data that has a record with a duplicate key. Check out the code below.

Old Way

PHP:
  1. $sql = 'SELECT TransId FROM Sales WHERE TransId = 123';
  2. $rs = $db->query($sql);
  3. if(mysql_num_rows($rs) == 1) {
  4.     // do an SQL UPDATE
  5. }
  6. else {
  7.     // do an SQL INSERT
  8. }

New Way

SQL:
  1. INSERT INTO Sales(TransId, STATUS, Amount)
  2. VALUES(123, 'Pending', 20)
  3. ON DUPLICATE KEY UPDATE STATUS = 'Paid'

Also keep in mind that a current bug in MySQL makes this method not replication safe. I believe this has been fixed.

7 reasons I switched back to PHP after 2 years on Rails

Derek Sivers, the founder, president, and sole programmer behind CD Baby, wrote a great article about why he switched back to PHP from Rails. I have nothing against Ruby or Rails, but I never found the reason why everyone was so hyped about it. Check out the article below.

“Is there anything Rails can do, that PHP CAN’T do?”

The answer is no.

I threw away 2 years of Rails code, and opened a new empty Subversion respository.

Article:
7 reasons I switched back to PHP after 2 years on Rails

Convert Multiple Spaces To a Single Space

Nifty line of PHP code that will take multiple sequential spaces and convert into a single space. This is great for cleaning and sanitizing data before storing it.

PHP:
  1. $date= preg_replace('/\s+/', ' ', $date);

RSS Feed



Recommended Sites