Archive for category php
PHP code snippet – Reorder items in a table
Posted by vinoaj in db, development, howto, php on July 9, 2007
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.
-
function moveItem ($n_steps) {
-
if ($n_steps == 0) {
-
return;
-
}
-
-
$cur_pos = $this->pos;
-
$new_pos = $cur_pos + $n_steps;
-
-
if ($n_steps <0) {
-
$min_pos = $cur_pos + $n_steps;
-
$max_pos = $cur_pos - 1;
-
$shift_sign = '+';
-
} elseif ($n_steps> 0) {
-
$min_pos = $cur_pos + 1;
-
$max_pos = $cur_pos + $n_steps;
-
$shift_sign = '-';
-
} else {
-
return;
-
}
-
-
$id = $this->id;
-
-
//Reorder existing items that will be existed by moving this item
-
$sql = "UPDATE positions
-
SET order_num = order_num $shift_sign 1
-
WHERE id = $id
-
AND position>= $min_pos
-
AND position <= $max_pos";
-
-
$this->db->query($sql);
-
-
//Now set new position for this item
-
$sql = "UPDATE postions SET position = $new_pos WHERE id = $id";
-
$this->db->query($sql);
-
}
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.
-
require_once('Akismet.class.php');
-
-
$API_key = 'xxxxxxxxxxxx';
-
$source_url = 'http://www.mysite.com/contact.php';
-
-
$akismet = new Akismet($source_url, $API_key);
-
$akismet->setCommentAuthor($enquirer_name);
-
$akismet->setCommentAuthorEmail($enquirer_email);
-
$akismet->setCommentContent($enquiry);
-
-
if ($akismet->isCommentSpam()){
-
//Enquiry is spammy - log it for later review by site owner
-
//If false positive, be sure to submit to Akismet so that it can learn from
-
// its mistake. Use Akismet::submitHam()
-
} else {
-
//Enquiry is not spammy - e-mail it to the site owner
-
//If false, be sure to submit to Akismet so that it can train itself better.
-
// Use Akismet::submitSpam()
-
}
-
-
//Below are other Akismet methods that you could call
-
$akismet->setCommentAuthorURL($enquirer_url);
-
$akismet->setCommentType($enquiry_type); //{'blank', 'comment', 'trackback', 'pingback', or custom}
-
$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.
-
require_once('Akismet.class.php');
-
-
$API_key = 'xxxxxxxxxxxx';
-
$source_url = 'http://www.mysite.com/contact.php';
-
-
'email' => $enquirer_email,
-
'website' => $enquirer_uri,
-
'body' => $enquiry,
-
'permalink' => $this_page_uri,
-
'user_ip' => $referrer_ip, // optional, defaults to $_SERVER['REMOTE_ADDR']
-
'user_agent' => $client_ua, // optional, defaults to $_SERVER['HTTP_USER_AGENT']
-
);
-
-
$akismet = new Akismet($source_url, $API_key, $comment);
-
-
// test for errors before submitting to Akismet
-
if($akismet->errorsExist()) {
-
if($akismet->isError('AKISMET_INVALID_KEY')) {
-
//...
-
} elseif($akismet->isError('AKISMET_RESPONSE_FAILED')) {
-
//...
-
} elseif($akismet->isError('AKISMET_SERVER_NOT_FOUND')) {
-
//...
-
}
-
} elseif ($akismet->isSpam()) {
-
//Enquiry is spammy - log it for later review by site owner
-
//If false positive, be sure to submit to Akismet so that it can learn from
-
// its mistake. Use Akismet::submitHam()
-
} else {
-
//Enquiry is not spammy - e-mail it to the site owner
-
//If false, be sure to submit to Akismet so that it can train itself better.
-
// Use Akismet::submitSpam()
-
}
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
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
-
$ts_utc = read_timestamp_from_db(); //Some custom function in your script
-
date_default_timezone_set('Australia/Sydney');
-
$ts_local = $ts_utc + $offset;
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.
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
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.
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().
-
//Contains encoded string to pass along for basic authentication purposes
-
-
//Target URL - the URL you want to submit a form to
-
$target_url = 'http://www.remotesite.com/post_target.php';
-
-
//Create a new cURL handle
-
//Passing the target URL to curl_init allows you to bypass the call curl_setopt($ch, CURLOPT_URL, $target_url);
-
$ch = curl_init($target_url);
-
-
//Tell the handler that the info is to be sent using an HTTP POST request
-
curl_setopt($ch, CURLOPT_POST, true);
-
-
//Set other relevant headers. Place each header as an array element
-
//An alternative to building the Authorization header is to use curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
-
'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');
-
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
-
//Pass the POST fields - be sure to urlencode your value strings (hint: http_build_query() will do this for you; PHP5)
-
//Below we assume values have already been posted to this script and kept in $_POST. We have validated the submission and
-
// are now posting the same values to a remote URL
-
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
-
-
//When we execute the handle, we want curl_exec() to return to a string rather than directly outputting it
-
curl_setopt($ch, CURLOPT_RETURNTRANSER, true);
-
-
//Don't use a cached connection - explicitly create a new one
-
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
-
-
//Fail if cannot connect to the target server within 5 seconds
-
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
-
-
//If the target server returns a redirect request using the "Location:" header directive, then follow it.
-
//To prevent recursive redirects, only do a max of 5 follows
-
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
-
-
//Let's now execute the handler
-
//Because CURLOPT_RETURNTRANSFER is true, we need to capture the return value of curl_exec()
-
$response_data = curl_exec($ch);
-
-
//Was there an error?
-
//curl_errno() returns the error code
-
//curl_error() returns a clear text message for the last cURL operation
-
if (curl_errno($ch)> 0){
-
} else {
-
//Close the handler and release resources
-
curl_close($ch);
-
}
-
-
-
//Now do something with your data
-
return myProcessingFunction($data);