23 Feb, 2010
Reading a CSV in PHP is much easier than I anticipated with the advent of the fgetcsv() function for PHP 4. The function basically reads a file line by line and performs and explode on the delimiter, returning the array. Here’s some sample code:
$length = 0;
if ( ($handle = @fopen($file, "r")) !== FALSE )
{
while (($row = fgetcsv($handle, $length, "\t")) !== FALSE)
{
var_dump($row); //dumps an array corresponding
}
}
The length parameter is option as of PHP 5.0.4. Using a limited line length makes execution slightly faster, so if it is realistic to limit line length (even if limiting it at a great value) it could improve script execution time significantly.
The function also allows for setting the enclosure and escape characters.
14 Jan, 2010
I needed to offer a client the ability to send Email using PHPmailer and Gmail. The below is what I came up with, which worked flawlessly:
require("PHPMailer_v5.1/class.phpmailer.php");
$mail = new PHPMailer();
$body = "Message Body";
$mail->Mailer = "smtp";
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 465;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username@gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SetFrom('from@address.com', 'First Last');
$mail->Subject = "PHPMailer Test Subject via smtp, basic with authentication";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress('email@address.com', 'First Last');
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
The part that threw me for a loop was right here:
$mail->Host = "ssl://smtp.gmail.com";
I was using simply smtp.gmail.com. I knew from setting up mail clients that you needed to use SSL, but it didn’t occur to me to tell PHPmailer to do the same. When it came to me, simply looking up how to instruct PHPmailer to use SSL did the trick.
11 Jan, 2010
Just created a wordpress funciton in_tree($a, $b) which checks to see if page ID $a is in the tree of page ID $b. That is, it checks to see if $a is a child of $b or $a is $b.
/**
* Checks to see if a $in_tree_id is in the tree of
* $in_tree_root post (is a child of or is the post
* ID provided)
*/
function in_tree($in_tree_id, $in_tree_root)
{
if($in_tree_id == $in_tree_root)
return true;
if(!get_post($in_tree_id)->post_parent)
return false;
return in_tree(get_post($in_tree_id)->post_parent, $in_tree_root);
}
30 Dec, 2009
I wanted to use the PHPExcel package on my Debian system running 5.2.0, however PHPExcel 1.7.1 requires the sys_get_temp_dir() function which doesn’t exist prior to PHP 5.2.1. Of course aside from updating PHP, we would need to replicate the functionality of sys_get_temp_dir(). This gem in the php.net comments on the function provides a workaround.
if ( !function_exists('sys_get_temp_dir'))
{
function sys_get_temp_dir()
{
if( $temp=getenv('TMP') ) return $temp;
if( $temp=getenv('TEMP') ) return $temp;
if( $temp=getenv('TMPDIR') ) return $temp;
$temp=tempnam(__FILE__,'');
if (file_exists($temp))
{
unlink($temp);
return dirname($temp);
}
return null;
}
}
22 Dec, 2009
In combination with my previous post on adding multiple sidebars to a Wordpress theme, I had the need to display one of them only when looking at the blog part of wordpress. This is pretty straightforward, but basically we just need to check if we are not on a page and display the sidebar.
//If we are viewing posts, not a page, print the posts sidebar
if(!is_page())
{
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Posts Sidebar') ):
endif;
}
21 Dec, 2009
I recently needed a little more control over the sidebar on a theme and had never added a sidebar to a theme before. I wanted certain widgets to show up only on posts and the rest to show up on posts and pages. The below is how to add the sidebar:
In the functions.php page, we need to modify the code which looks like this:
if ( function_exists('register_sidebar') )
register_sidebar();
To make it look like this:
if ( function_exists('register_sidebar') )
{
register_sidebar(array('name'=>'Top Sidebar',));
register_sidebar(array('name'=>'Posts Sidebar',));
register_sidebar(array('name'=>'Bottom Sidebar',));
}
Now, when calling a sidebar, we just need to call it by name as in the following:
//Top Sidebar
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Top Sidebar') ):
endif;
//Posts Sidebar
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Posts Sidebar') ):
endif;
//Bottom Sidebar
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Bottom Sidebar') ):
endif;
Obviously we have freedom to name our sidebars as we please. Look for more info on making a sidebar only show up on posts in an upcoming post.
18 Dec, 2009
I recently ran across a silly Wordpress situation where I needed to pass an array in the querystring. Here’s what I came up with:
$array = array('a' => 1, 'b' => 2, 'c' => 3);
$array = rawurlencode(serialize($array));
echo '<a href="./getarray.php?a=' . $array . '">Pass array</a>';
Then on the receiving getarray.php:
$array = unserialize(stripslashes($_GET['error_array']));
18 Dec, 2009
It was recently asked in a newsgroup how to make the Wordpress author function like the wordpress category page. The format of the category page is category-x.php. Replace the x with the category ID you would like a custom page for (e.g. category-14.php) and when browsing category x the custom page category-x.php is processed instead of category.php.
In my research, I didn’t see a previously implemented way to do this with author.php, so I came up with these modifications to the author.php page:
global $wp_query;
$curauth = $wp_query->get_queried_object();
if(file_exists('author-'.$curauth->ID.'.php'))
{
include('author-'.$curauth->ID.'.php');
}
else
{
//Default author page
}
The idea here is to have author.php check to see if author-x.php exists. If it does, include that file. If not, process the default author.php in the else condition.
8 Dec, 2009
I am interested in building a google voice / highrise mashup that tags people by how long overall I’ve talked to them. I ran across this bit of PHP code by Aaronpk that attempts to use the main voice functionality as an API. And it works really well.
The below is adapted from that code to get all calls and get the duration of the calls. Of course, duration is approximate, but that’s as good as it is going to get for me.
$login = 'username';
$pass = 'password';
$cookieFile = '/tmp/gvCookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
// fetch the login page
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ServiceLogin?passive=true&service=grandcentral');
$html = curl_exec($ch);
if(preg_match('/name="GALX"\s*value="([^"]+)"/', $html, $match))
$GALX = $match[1];
else
throw new Exception('Could not parse for GALX token');
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/accounts/ServiceLoginAuth?service=grandcentral');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'Email' => $login,
'Passwd' => $pass,
'continue' => 'https://www.google.com/voice/account/signin',
'service' => 'grandcentral',
'GALX' => $GALX
));
// Process login
$html = curl_exec($ch);
if( preg_match('/name="_rnr_se".*?value="(.*?)"/', $html, $match) )
{
$rnr_se = $match[1];
}
else
{
exit("Could not log in to Google Voice with username: " . $login);
}
// Get results for all recent calls, paginated of course
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/voice/inbox/recent/all/');
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$xml = curl_exec($ch);
$dom = new DOMDocument();
// load the "wrapper" xml (contains two elements, json and html)
$dom->loadXML($xml);
$json = $dom->documentElement->getElementsByTagName("json")->item(0)->nodeValue;
$json = json_decode($json);
// now make a dom parser which can parse the contents of the HTML tag
$html = $dom->documentElement->getElementsByTagName("html")->item(0)->nodeValue;
// replace all "&" with "&" so it can be parsed
$html = str_replace("&", "&", $html);
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$calls = array();
// Call duration isn't included, so foreach $json->messages, getting gc-message-call-details for each element
foreach( $json->messages as $mid=>$convo )
{
//find this conversation by message id
$elements = $xpath->query("//div[@id='$mid']");
if(!is_null($elements))
{
$element = $elements->item(0);
//find the gc-message-call-details contents
$XMsg = $xpath->query("//span[@class='gc-message-call-details']", $element);
//add details to the convo
$convo->details = $XMsg->item(0)->nodeValue;
}
//add $convo to results
$calls[] = $convo;
}
foreach($calls as $mid => $convo)
{
echo "Call $mid lasted $convo->details\n";
}
7 Dec, 2009
Thanks to the help of Daniel Watrous, an improved version of our $_Get Getter Wordpress plugin is now available. It is now able to pull multiple variables from the query string.
You can get the new version here.