howtos » php
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);
-
}
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()
-
}
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;
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.
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);
Sending a plain-text e-mail through PHP is a simple process
The $to parameter can look like:
example@mysite.com example@mysite.com, user@mysite.com Example Sr <example@mysite.com>, Example Jr <user@mysite.com>
Common headers to use in your messages:
-
$headers = "From: yourname@yoursite.com\r\n
-
Reply-To: replyhere@yoursite.com\r\n
-
Cc: watcher@yoursite.com\r\n
-
Bcc: spy@yoursite.com\r\n
-
X-Mailer: YourApplicationNameHere\r\n"
PHP 5's DOM Functions (or extension) allows you to create and manipulate XML documents. In fact, it can also be used to create and manipulate any documents adhering to the DOM3 specifications such as HTML and XHTML documents.
Creation of a DOM document is a fairly simple affair
- Instantiate DOMDocument - also specify which version of XML the document is in and how it is encoded
- Create elements through the DOMDocument object
- Set your elements' properties (e.g. values, attributes, child nodes)
- Append the elements to your parent DOMDocument
- Output as fully-formed XML using
DOMDocument::saveXML()
The following example shows you how to create an XML document (using UTF-8 encoding) using PHP 5's DOM functions.
-
//First create an XML document
-
//The following statement sets XML version 1.0, encoding utf-8
-
$dom = new DOMDocument('1.0', 'utf-8');
-
-
//Step 1: create the root node
-
//Now create the root node and declare the XML namespace
-
$entry_node = $dom->createElementNS('http://www.w3.org/2005/Atom', 'entry');
-
//If you need to add additional namespace declarations, do it now
-
$entry_node->setAttribute('xmlns:gd','http://schemas.google.com/g/2005');
-
-
//Step 2: create all child nodes
-
$category_node = $dom->createElement('category');
-
$category_node->setAttribute('scheme', 'http://schemas.google.com/g/2005#kind');
-
$category_node->setAttribute('term', 'http://schemas.google.com/g/2005#event');
-
-
$title_node = $dom->createElement('title', $title);
-
$title_node->setAttribute('type', 'text');
-
-
$content_node = $dom->createElement('content', $content);
-
$content_node->setAttribute('type', 'text');
-
-
//In some cases the child node may itself be a parent with its own child nodes
-
//Create the parent node
-
$author_node = $dom->createElement('author');
-
-
//Create the child nodes
-
$author_name_node = $dom->createElement('name', $author_name);
-
$author_email_node = $dom->createElement('email', $author_email);
-
-
//Add the child nodes to the parent
-
$author_node->appendChild($author_name_node);
-
$author_node->appendChild($author_email_node);
-
-
$transparency_node = $dom->createElement('gd:transparency');
-
$transparency_node->setAttribute('value', 'http://schemas.google.com/g/2005#event.opaque');
-
-
$eventstatus_node = $dom->createElement('gd:eventStatus');
-
$eventstatus_node->setAttribute('value', 'http://schemas.google.com/g/2005#event.confirmed');
-
-
$where_node = $dom->createElement('gd:where');
-
$where_node->setAttribute('valueString', $where);
-
-
$when_node = $dom->createElement('gd:when');
-
$when_node->setAttribute('startTime', $startTime . '+10:00');
-
$when_node->setAttribute('endTime', $endTime . '+10:00');
-
-
//Another child node which is also a parent
-
$reminder_node = $dom->createElement('gd:reminder');
-
$reminder_node->setAttribute('minutes', $minutes);
-
-
$when_node->appendChild($reminder_node);
-
-
//Step 3: Add child nodes to the parent node
-
$entry_node->appendChild($category_node);
-
$entry_node->appendChild($title_node);
-
$entry_node->appendChild($content_node);
-
$entry_node->appendChild($author_node);
-
$entry_node->appendChild($transparency_node);
-
$entry_node->appendChild($eventstatus_node);
-
$entry_node->appendChild($where_node);
-
$entry_node->appendChild($when_node);
-
-
-
//Append the root node to the document
-
$dom->appendChild($entry_node);
-
-
//Return the fully-formed XML representation of the DOMDocument
-
return $dom->saveXML();
Here's how to include another template file within a template file:
- md5 sanitizes the ID and limits it to 32 characters.
- uniqid generates a random ID based on your server's time, etc.
- rand() is prefixed onto the ID - thus enhancing the ID's uniqueness.
- true tells uniqid() to make use of "more entropy" - again enhancing the ID's uniqueness.
Your development environment might be configured to not display errors and log them instead. While this makes good sense in the production environment, while developing you want to be able to see every error and warning in order to pick up potential troublespots.
You can override php.ini's error display settings via .htaccess or within your PHP script.
Here's a way to turn on error display from within your PHP script.