Howto: Create and Stream a CSV with PHP
I find myself constantly creating csv files for users to download. Whether it’s a method for users to export their data to excel, a way for users to backup their hosted data, or just a simple way to send them report information, csv files are extremely useful. Normally I just create an actual file and link to it for the user to download. The files are usually cleaned up after a certain amount of time or after a certain number of newer files exist.
Recently however, I had a client that really wanted to be able to export data in csv format without ever creating a file on the webserver. Their concern was rooted in security, but the reality of the matter was that they were trying to obey the letter of the law with regards to company policies. Whether it was truly necessary or not is for another discussion. Instead, the technique is actually very useful so I thought I’d share.
The key to this is that the fopen function supports php input/output streams as wrappers.
WordPress 2.5 Shortcodes
First I touched on the topic in my first impressions of WordPress 2.5. Then I whined a little about the tickets relating to them, and eventually I released my Google Maps Plugin that uses them. In the end, WordPress’s new shortcodes are really nice.
What are they?
First of all, a shortcode called “mycode” can look like any of these:
[mycode] [mycode foo="bar" id="123" color="red" something="data"] [mycode]Some Content[/mycode] [mycode]<p><a href="http://example.com/">HTML Content</a></p>[/mycode] [mycode]Content [another-shotcode] more content[/mycode] [mycode foo="bar" id="123"]Some Content[/mycode]
As you can see, shortcodes allow a user to put a code into a post or page, and a plugin can then easily handle those codes. They can be nested, contain content (including HTML), attributes, etc. Sounds great, but how can you leverage shortcodes for your benefit?
How can I use them?
You want to leverage the new, powerful shortcode system in WordPress 2.5, but where do you start?
Read more
Wordpress Should Update get_sidebar to Work With Multiple Sidebars
I submitted an enhancement to wordpress yesterday, to allow get_sidebar to work with multiple sidebars. It’s an extremely simple fix, and you end up with a function that looks like this:
function get_sidebar($name=null) {
do_action( 'get_sidebar' );
if ( isset($name) && file_exists( TEMPLATEPATH . "/sidebar-{$name}.php") )
load_template( TEMPLATEPATH . "/sidebar-{$name}.php");
elseif ( file_exists( TEMPLATEPATH . '/sidebar.php') )
load_template( TEMPLATEPATH . '/sidebar.php');
else
load_template( ABSPATH . 'wp-content/themes/default/sidebar.php');
}By adding two lines and one optional parameter to the get_sidebar() function, you would be able to pass it a sidebar name. For example, get_sidebar(‘left’) would load the template TEMPLATEPATH . ’sidebar-left.php’ allowing you to have multiple sidebar files as part of your template.
Read more
PHP function to Redirect a user with a message
One of the common things that you need to do in PHP is redirect a user, and display a message on whatever page you are sending them to. There are a lot of reasons for this, but the most common is to avoid a user refresh from resubmitting a form. Instead, process the form data, and redirect the user (even if you redirect them to the same page). Here is a function I use for this very purpose. It requires that you are using sessions. It stores the message in the session, and passes a has in the URL. This way, you can use any length message you want, and display it only once.
Read more
Replace every other occurrence with str_replace
Well, someone put some code onto the str_replace PHP manual page to replace every other occurrence of a string with another string. However, it didn’t work, and was simply spam to get a link onto the PHP manual page (shame on them). So I made a function that DID work, for the poor lost souls who would be trying over and over to make that one work. I figured that since I made it, I might as well post it, maybe someone needs something like this.
/**
* Replaces every other occurrence of search in haystack with replace
*
* @param $needle mixed
* @param $replace mixed
* @param $haystack mixed
* @param $count int[optional]
* @param $replace_first bool[optional] - Default true
* @return mixed
*/
function str_replace_every_other($needle, $replace, $haystack, &$count=null, $replace_first=true) {
$count = 0;
$offset = strpos($haystack, $needle);
//If we don't replace the first, go ahead and skip it
if (!$replace_first) {
$offset += strlen($needle);
$offset = strpos($haystack, $needle, $offset);
}
while ($offset !== false) {
$haystack = substr_replace($haystack, $replace, $offset, strlen($needle));
$count++;
$offset += strlen($replace);
$offset = strpos($haystack, $needle, $offset);
if ($offset !== false) {
$offset += strlen($needle);
$offset = strpos($haystack, $needle, $offset);
}
}
return $haystack;
}
//Use it like this:
$str = "one two one two one two";
echo str_replace_every_other('one', 'two', $str, $count).'\r\n';
//two two one two two two
echo str_replace_every_other('one', 'two', $str, $count, false).'\r\n';
//one two two two one two
I added the last option ($replace_first) to let you replace the odd occurrences (true, default) or the evens (false).
PHP Pagination with mysqli
I’m asked pretty regularly for help with pagination in PHP. I have a nice mysqli pagination class that I use. Once it’s implemented, it is used like this:
/**
* $db is your mysqli connection
* $query is your query
* 'mailPage' is the $_GET variable to use for the pages. It defaults to 'page' but using different values lets you have separate
* paginated data on that same web page. Setting multiple paginated items on the same webpage to the same "page" variable
* will mean that when one goes to page two, all of them go to page 2.
*/
// Require the class
require_once('paginate.class.php');
// Lets not use your normal SELECT * FROM table query...just to show it still works
$query = <<<
SELECT
`mail`.`id`,
`mail2`.`read`,
`mail2`.`seen`,
`mail`.`from`,
`mail`.`sent`,
`mail`.`subject`,
`mail`.`body`,
`users`.`full_name` as from_name
FROM `mail`
JOIN `users`
ON (`mail`.`from` = `users`.`id`)
JOIN `mail2`
ON (`mail`.`id` = `mail2`.`mess_id`)
WHERE
`mail2`.`uid`=1 &&
`mail2`.`folder`=1
ORDER BY
`mail`.`sent` DESC
EOQ;
// Create our paginate object, and pass it the database, query, and page var
$paginate = new Paginate($db, $query, 'mailPage');
// Run the query
$r = $paginate->get_results();
// Loop through our results
while ($message = $r->fetch_object()) {
// Create your page of information
}
// Show the page links
echo $paginate->show_pages();


