Archive for the ‘PHP programming’ Category

Dirty hack: force primary category for wordpress post permalink

The permalink from Wordpress CODEX

I’m not especially proud of this hack. However, I was getting crazy by how the category used for a post permalink is choosen. And I could not figure out a clean way to control which is the primary permalink (I hope it’s not part of Wordpress 3.0…).

You may need to set the primary category for permalink in two situations:

  • First, you want some consistency among your posts, having them in the same primary category.
  • Second, it’s never fun when, by adding an additional category to an existing post, it changes the post permalink!

Read the rest of this entry »

Search files using PHP with a mask pattern

This morning, I cam to a very, very basic need: detect whether a file matching a specific pattern (like ‘*.txt’) is available.

However, I could not find any ready to use PHP function, although PHP5 provides some interesting functions, like scandir().

After completing writting such a function, I decided to share it. So here is it.

Bare in mind it requires PHP5 (or later), as it relies on scandir() and on fnmatch(). Finally, this function while return the filtered directory content, regardless of the content being a file, a link or a directory.

Additional feature: by default, if you call the function more than once in your script in order to scan the same directory, it will read the directory only once: next times, it will use a cached content. To disable caching, set the third parameter to 1.

function searchdir( $path='.', $mask='*', $nocache=0 ){
 static $dir = array();
 if ( !isset($dir[$path]) || $nocache) {
 $dir[$path] = scandir($path);
 foreach ($dir[$path] as $i=>$entry) {
 if ($entry!='.' && $entry!='..' && fnmatch($mask, $entry) ) {
 $sdir[] = $entry;
 if ($nocache)
 return ($sdir);

Did you find this small function useful? Do you have any improvment suggestion?


You are currently browsing the archives for the PHP programming category.