Archive for category php

PHP code snippet – Reorder items in a table

This snippet of code reorders items in a table based on the number of steps you want to move an item from its current position. It moves the item of interest to its new position and shifts all other items to their new shifted positions.

PHP:
  1. function moveItem ($n_steps) {
  2. if ($n_steps == 0) {
  3. return;
  4. }
  5.  
  6. $cur_pos = $this->pos;
  7. $new_pos = $cur_pos + $n_steps;
  8.  
  9. if ($n_steps <0) {
  10. $min_pos = $cur_pos + $n_steps;
  11. $max_pos = $cur_pos - 1;
  12. $shift_sign = '+';
  13. } elseif ($n_steps> 0) {
  14. $min_pos = $cur_pos + 1;
  15. $max_pos = $cur_pos + $n_steps;
  16. $shift_sign = '-';
  17. } else {
  18. return;
  19. }
  20.  
  21. $id = $this->id;
  22.  
  23. //Reorder existing items that will be existed by moving this item
  24. $sql = "UPDATE  positions
  25. SET  order_num = order_num $shift_sign 1
  26. WHERE   id = $id
  27. AND position>= $min_pos
  28. AND position <= $max_pos";
  29.  
  30. $this->db->query($sql);
  31.  
  32. //Now set new position for this item
  33. $sql = "UPDATE postions SET position = $new_pos WHERE id = $id";
  34. $this->db->query($sql);
  35. }

No Comments

Akismet and PHP for your site

A few sites I administer have recently had the misfortune of having spambots visit their enquiry and contact pages. These pages usually have a contact form, where an enquirer can leave their name, e-mail, and request or comment. When they submit the form, a copy of the message is e-mailed to the site owner. The spambots try and submit messages that usually contain gibberish but also multiple URLs to spam sites. Something had to be done to prevent site owners from receiving hundreds of spam messages a day.

I considered a few methods for preventing the bots from visiting the enquiry page. These included firewall configuration, user-agent detection, rudimentary parsing of the messages, captcha systems, and so forth. These methods were either too cumbersome to implement, could be circumvented, or spoiled the user experience for a genuine user. The latter was a critical concern.

Enter Akismet

The Akismet API is an open API used to assess the spam score of comments left or enquiries made on a site. It is in widespread use as a plugin for WordPress blogs. Its effectiveness has become a must-have plugin for WordPress installations. The Akismet API however can be applied to any site or application capable of making HTTP requests.

First you need an API key. You can obtain one by registering for a WordPress.com user account (you do not need to have an active WordPress blog). Your API key will be e-mailed to you once you have activated your account.

Akismet and PHP5

Download the PHP5 Akismet Library.
Extract the contents of the downloaded package and place them in a location that your application can access when required.

Here's how to use the Akismet API in your PHP5 code.

PHP:
  1. require_once('Akismet.class.php');
  2.  
  3. $API_key = 'xxxxxxxxxxxx';
  4. $source_url = 'http://www.mysite.com/contact.php';
  5.  
  6. $akismet = new Akismet($source_url, $API_key);
  7. $akismet->setCommentAuthor($enquirer_name);
  8. $akismet->setCommentAuthorEmail($enquirer_email);
  9. $akismet->setCommentContent($enquiry);
  10.  
  11. if ($akismet->isCommentSpam()){
  12.     //Enquiry is spammy - log it for later review by site owner
  13.     //If false positive, be sure to submit to Akismet so that it can learn from
  14.     //  its mistake.  Use Akismet::submitHam()
  15. } else {
  16.     //Enquiry is not spammy - e-mail it to the site owner
  17.     //If false, be sure to submit to Akismet so that it can train itself better.
  18.     //  Use Akismet::submitSpam()
  19. }
  20.  
  21. //Below are other Akismet methods that you could call
  22. $akismet->setCommentAuthorURL($enquirer_url);
  23. $akismet->setCommentType($enquiry_type);    //{'blank', 'comment', 'trackback', 'pingback', or custom}
  24. $akismet->setPermalink($url);   //A permanent URL referencing the resource for which a comment is being left for

Akismet and PHP4

Download the PHP4 Akismet library. Extract the contents of the downloaded package and place them in a location that your application can access when required.

Here's how to use the Akismet API in your PHP4 code.

PHP:
  1. require_once('Akismet.class.php');
  2.  
  3. $API_key = 'xxxxxxxxxxxx';
  4. $source_url = 'http://www.mysite.com/contact.php';
  5.  
  6. $comment = array('author'     => $enquirer_name,
  7.                  'email'        => $enquirer_email,
  8.                  'website'   => $enquirer_uri,
  9.                  'body'         => $enquiry,
  10.                  'permalink'    => $this_page_uri,
  11.                  'user_ip'   => $referrer_ip,     // optional, defaults to $_SERVER['REMOTE_ADDR']
  12.                  'user_agent'   => $client_ua,        // optional, defaults to $_SERVER['HTTP_USER_AGENT']
  13.                 );
  14.                
  15. $akismet = new Akismet($source_url, $API_key, $comment);
  16.  
  17. // test for errors before submitting to Akismet
  18. if($akismet->errorsExist()) {
  19.     if($akismet->isError('AKISMET_INVALID_KEY')) {
  20.         //...
  21.     } elseif($akismet->isError('AKISMET_RESPONSE_FAILED')) {
  22.         //...
  23.     } elseif($akismet->isError('AKISMET_SERVER_NOT_FOUND')) {
  24.         //...
  25.     }
  26. } elseif ($akismet->isSpam()) {
  27.     //Enquiry is spammy - log it for later review by site owner
  28.     //If false positive, be sure to submit to Akismet so that it can learn from
  29.     //  its mistake.  Use Akismet::submitHam()
  30. } else {
  31.     //Enquiry is not spammy - e-mail it to the site owner
  32.     //If false, be sure to submit to Akismet so that it can train itself better.
  33.     //  Use Akismet::submitSpam()
  34. }

No Comments

Timezones and UTC in PHP

If you are dealing with multiple users in different timezones or simply want to display times in a timezone other than your server's settings, it is best to store timestamps as their UTC (~ GMT) equivalents. When you read those timestamps later, you can convert them to local time.

Local time to UTC time

PHP:
  1. date_default_timezone_set('Australia/Sydney');
  2. $time = gmmktime($hr, $min, $sec, $mon, $day, $yr);
  3. $date = gmdate('d/m/Y H:i', time());

date_default_timezone_set sets the default timezone for all date & time operations.
gmmktime is analogous to mktime except it takes in local time values and creates the corresponding UTC timestamp.
gmdate similarly takes in local time values and creates the corresponding UTC date & time.

UTC time to Local time

PHP:
  1. $ts_utc = read_timestamp_from_db()//Some custom function in your script
  2. date_default_timezone_set('Australia/Sydney');
  3. $offset = date('Z');    //Timezone offset from UTC in number of seconds (can be +ve or -ve)
  4. $ts_local = $ts_utc + $offset;

No Comments

Prevent caching of page on client’s end – PHP and HTML solutions

To prevent the caching of a web page on your client's end, use the following snippet of PHP to ensure that the appropriate HTTP headers are sent.

PHP:
  1. header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  2. header("Expires: Tue, 03 Jul 1979 00:00:00 GMT");   // Date in the past

The first header tells the client that the page must not be cached.
The second header is a backup, and tells the client that the page expired a long time ago in the past, and it should fetch a more recent version.

The same effect can be achieved by placing corresponding meta tags in your HTML document

HTML:
  1. <meta http-equiv="Expires" content="Tue, 03 Jul 1979 00:00:00 GMT" />
  2. <meta http-equiv="Pragma" content="no-cache" />

Where possible, place your cache control directives in the HTTP header, because some clients and proxies rely on your server's HTTP response to determine caching.

No Comments

PHP/CURL

cURL is used to interact with remote URLs without needing a user to initiate the process (e.g. by clicking on a form submit button). cURL is useful for submitting HTTP POST/PUT/DELETE requests when dealing with web services. PHP has inbuilt cURL support since PHP 4.0.2 using cURL's libcurl library. Find out more about PHP/CURL -- using libcurl with PHP here.

A fullset of cURL options and what they mean can be found in
PHP's manual entry for curl_setopt().

PHP:
  1. //Contains encoded string to pass along for basic authentication purposes
  2. $auth_token = base64_encode($username . '-' . $password);
  3.  
  4. //Target URL - the URL you want to submit a form to
  5. $target_url = 'http://www.remotesite.com/post_target.php';
  6.  
  7. //Create  a new cURL handle
  8. //Passing the target URL to curl_init allows you to bypass the call curl_setopt($ch, CURLOPT_URL, $target_url);
  9. $ch = curl_init($target_url);
  10.  
  11. //Tell the handler that the info is to be sent using an HTTP POST request
  12. curl_setopt($ch, CURLOPT_POST, true);
  13.  
  14. //Set other relevant headers.  Place each header as an array element
  15. //An alternative to building the Authorization header is to use curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
  16. $headers = array('Authorization: Basic ' . $auth_token,
  17.                  'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3');
  18. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  19.  
  20. //Pass the POST fields - be sure to urlencode your value strings (hint: http_build_query() will do this for you; PHP5)
  21. //Below we assume values have already been posted to this script and kept in $_POST.  We have validated the submission and
  22. // are now posting the same values to a remote URL
  23. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
  24.  
  25. //When we execute the handle, we want curl_exec() to return to a string rather than directly outputting it
  26. curl_setopt($ch, CURLOPT_RETURNTRANSER, true);
  27.  
  28. //Don't use a cached connection - explicitly create a new one
  29. curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
  30.  
  31. //Fail if cannot connect to the target server within 5 seconds
  32. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  33.  
  34. //If the target server returns a redirect request using the "Location:" header directive, then follow it.
  35. //To prevent recursive redirects, only do a max of 5 follows
  36. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  37. curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  38.  
  39. //Let's now execute the handler
  40. //Because CURLOPT_RETURNTRANSFER is true, we need to capture the return value of curl_exec()
  41. $response_data = curl_exec($ch);
  42.  
  43. //Was there an error?
  44. //curl_errno() returns the error code
  45. //curl_error() returns a clear text message for the last cURL operation
  46. if (curl_errno($ch)> 0){
  47.     die('There was a cURL error: ' . curl_error($ch));
  48. } else {
  49.     //Close the handler and release resources
  50.     curl_close($ch);
  51. }
  52.  
  53.  
  54. //Now do something with your data
  55. return myProcessingFunction($data);

No Comments