Archive

Posts Tagged ‘files’

Reading And Writing To Compressed gzip Files

April 23rd, 2009 No comments

Reading and writing to compressed gzip files can be done in much the same way as reading and writing normal files. The main difference is the use of some special functions that compress and uncompress the data. Rather then use fopen() to open a file, you open a compressed file with gzopen(). This is the case for many of the file access functions, although you should be aware that they don’t all work exactly the same as each other. Here are some examples of the compression functions in use.

To read from a compressed file use the following script.

// read from file
$inputfile = 'text.gz';
 
$filecontents = '';
 
$ifh = gzopen($inputfile, 'r');
 
while ( $line = gzgets($ifh, 1024) ) {
    $filecontents .= $line;
}
echo $filecontents;
gzclose($ifh);

To write to a compressed file use the following script.

// writing to a complessed file
$inputfile = 'text.gz';
 
$string = 'lalalala';
$filecontents = '';
 
$ifh = gzopen($inputfile, 'r');
 
while ( $line = gzgets($ifh, 1024) ) {
    $filecontents .= $line;
}
gzclose($ifh);
 
$ifh = gzopen($inputfile, 'w');
if ( !gzwrite($ifh, $filecontents.$string) ) {
    // write failed
}
 
gzclose($ifh);
 

To compress a normal file use the following script.

// compress
$inputfile = 'text.txt';
$outputfile = 'text.gz';
 
// open files
$ifh = fopen($inputfile, 'rb');
$ofh =  fopen($outputfile, 'wb');
 
// encode string
$encoded = gzencode(fread($ifh, filesize($inputfile)));
 
if ( !fwrite($ofh, $encoded) ) {
    // write failed
}
 
// close files
fclose($ifh);
fclose($ofh);

To uncompress a gzip file use the following script.

// uncompress
$inputfile = 'text.gz';
$outputfile = 'text.txt';
 
$ofh =  fopen($outputfile, 'wb');
 
$string = '';
 
$ifh = gzopen($inputfile, 'r');
while ( $line = gzgets($ifh, 1024) ) {
    $string .= $line;
}
 
if ( !fwrite($ofh, $string) ) {
    // write failed
}
 
echo $string;
 
gzclose($ifh);
fclose($ofh);

Notice from these examples that you can open a compressed file using fopen(), but you need to use the 'b' flag to indicate to fopen that you want the file to be opened in a binary format. Basically, the two following calls are very much the same.

$ifh = gzopen($inputfile, 'r');
$ifh = fopen($inputfile, 'rb');

The gzopen() function can also take some other parameters as the mode. These include the compression level (eg. wb1 or wb9) or a strategy. The strategy can be either f for filtered (used as wb9f) or h for Huffman only compression (used as wb1h).

Categories: PHP Tags: , , , , , , ,

Sequentially Rename All Image Files In A Directory With PHP

March 2nd, 2009 1 comment

The following function will rename all of the image files in a directory to be sequential. The parameters are the path of the directory that the files are in and the name of a function that will be used to sort the array of files through the PHP usort() funciton.

function sequentialImages($path, $sort=false) {
 $i = 1;
 $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT);
 
 if ( $sort !== false ) {
  usort($files, $sort);
 }
 
 $count = count($files);
 foreach ( $files as $file ) {
  $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT);
  $ext = substr(strrchr($file, '.'), 1);
  $newname = $path.'/'.$newname.'.'.$ext;
  if ( $file != $newname ) {
   rename($file, $newname);
  }
  $i++;
 }
}

The following function can be used in the second parameter to sort the files by their last modified time.

function sort_by_mtime($file1, $file2) {
 $time1 = filemtime($file1);
 $time2 = filemtime($file2);
 if ( $time1 == $time2 ) {
  return 0;
 }
 return ($time1 < $time2) ? 1 : -1;
}

Putting these two function together we can call the sequentialImages() function like this.

sequentialImages('files','sort_by_mtime');

This function takes the following set of images:

file1.gif
file2.gif
wibble.gif
wobble.gif
02.gif

And renames them to the following:

01.gif
02.gif
03.gif
04.gif
05.gif

Categories: PHP Tags: , , , , , , , , , ,

Create Compressed Files With Phing

January 15th, 2009 1 comment

Building your projects into directories is nice, but distributing these projects is difficult if you have to build the compressed files yourself. Phing has the ability to create zip and tar files using simple commands.

The most convenient way of using the tar and zip commands is by using a fileset. But rather than use the fileset that was used to copy the files into the build directory it is best to create a separate fileset that is used to compress the contents of the build directory.

<fileset dir="./" id="zipFiles">
<include name="myProject_build/**" />
</fileset>

To compress the files into a tar use the tar element. This accepts two parameters, the destination file (called destfile) and the compression to use (called compression). The compression attribute can take one of three values, these are gzip, bzip2 and none. Using none will not run any compression algorithms on the files. The following example will create a file called myProject.tar in the current directory, which contains all of the files and directories from the myProject_build directory.

<tar destfile="myProject.tar" compression="gzip">
<fileset refid="zipFiles" />
</tar>

To compress the files into a zip file you need to use the zip element. This works in exactly the same way as the tar element, except it doesn’t have a compression attribute.

<zip destfile="myProject.zip">
<fileset refid="zipFiles" />
</zip>

The tar element works very well and the file created was as expected, but I had a little bit of trouble with the zip element. I am using Windows XP to run phing and the file that was created was blocked by Windows for having odd content. After I figured out how to open it I realized that phing had used the full path to the build folder. So rather than the zip file containing a folder called myProject_build, it contained the following folder structure, with the correct files included in the end directory.

C:\dev\tests\phing\myProject_build

Has anyone else seen this? I would be grateful for any help on the subject.

You can also use the zip and tar elements without the fileset element by using the basedir attribute. By setting the basedir you are telling phing to use everything in that directory and every sub directory.

<tar destfile="phing.tar" basedir="." compression="gzip"/>

There is a warning on the phing website that states using basedir and fileset simultaneously can result in strange contents in the archive. So I would suggest using one or the other.

Categories: PHP Tags: , , , , , ,

Moving Files In PHP

November 11th, 2008 No comments

I have been asked a couple of times recently if PHP has a function that will move a file, so I thought I would put the solution here.

PHP has a function called rename() which can be used to rename a file, but because of the way it works it can be used to move files. Let’s say that you wanted to rename a file called test.txt to test_back.txt, this can be accomplished by doing the following.

rename("test.txt", "test_back.txt");

However, if you want to move the file from one directory to another you can do the following.

rename("test.txt", "backups/test_back.txt");

The return value of rename() is boolean that tells you if the rename was successful or not, this can be used to error check like this.

if ( !rename("test.txt", "backups/test_back.txt") ) {
 // rename not successful, try another way
}

Be aware that if you try the following:

rename("test.txt", "test.txt");

The function will return true.

To rename a directory you should do the following:

rename("directory/directoryold","directory/directorynew");

Note the absence of the trailing slash on the directory name, PHP will give an error if this slash is added.

Categories: PHP Tags: , , , ,

Getting Started With WordPress Templates

July 29th, 2008 No comments

If you are setting up a WordPress blog the chances are that you will be looking into modifying the default theme to be something a little more customised to your site. Theme development can be as complicated or as simple as you want, or are capable of doing.

WordPress themes are stored in the folder wp-content/themes/, each theme being stored in it’s own directory.

The basic theme must contain two basic files, the main control is done from a file called index.php and a file called styles.css, which is also needed to allow you to display the theme within the admin section of WordPress. If you don’t want to use the styles.css file then this is fine, but it should be present and contain the following lines.

/**
* Theme Name: Your theme name
* Theme URI: www.talkincode.com
* Description: A theme designed by the guys at talkincode.com
* Author: Tech
* Author URI: talkincode.com
* Version: 1.0
*  
* General comments can go in this space.
*/

This is all integrated into your WordPress administration section under themes. If you want a screenshot to appear as well as the description then create a file called screenshot.png, make it 300 pixels wide by 225 pixels high and put it in the same folder as the rest of the files.

There is also a file called functions.php in which you can define custom functions that can be used in your template. This includes, but is certainly not limited to, adding a widget definition. The functions file is loaded right at the start of the template and is looked at when viewing the administration section of your site. Any code kept in the functions.php file is called rather like a plugin and so it is possible to write plugin-like code in this file and have it act accordingly.

Other files can be included very easily.

The header file will contain the HTML at the top of the page (including styles and meta tags) and will get included via the get_header() function like this.
<?php get_header(); ?>

The footer file will contain the HTML at the bottom of the page (including copyright and site tags) and will be included via the get_footer() function like this.
<?php get_footer(); ?>

The sidebar of the site can be included using the get_sidebar() function. This can contain a widget call or
<?php get_sidebar(); ?>

If anything else is to be included from the template folder then the TEMPLATEPATH constant can be used in conjunction with a include() function call.
<?php include(TEMPLATEPATH . '/searchform.php'); ?>

WordPress will automatically recognise certain files depending on what action is being taken. For example, when looking at a single post or page the single.php file is used instead of the index.php file to load the template. If this file doesn’t exist then it uses the standard index.php file.

Also, if the user clicks on a link for a category, WordPress will load the category.php file. If this is not present then WordPress tries to load a file called archive.php. If both of these files are not present then WordPress load the main index.php file instead.

A files called 404.php is also used when a 404 response is needed. This file is called automatically during a 404 response and does not require any .htaccess modifications.

A lot of default tags are available for you to use if you don’t want to hard code things into your template. For example, to include the name of your blog in your template you can use the following code.

<?php bloginfo('name'); ?>

In addition to the name tag the tags description, url, admin_email and version are also available.

The Loop is used by WordPress to display each post in turn. The loop takes the following format.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
// the contents of the post can be displayed here
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

There are a number of different tags that can be placed within the loop to print out different information. For example, to print out the content you just need to call the the_content() function.

<?php the_content(); ?>

The best way to get acquainted with WordPress templates is to simply make a copy of the default template that comes with WordPress and edit it to suit your needs. In this way you can figure out how things work, why the template is set up as it is and what files do what.

The following links go to specific pages within the WordPress documentation and should also help out.

codex.wordpress.org/Stepping_Into_Templates: The WordPress documentation on getting started on templates.

codex.wordpress.org/Stepping_Into_Template_Tags: A list of the different tags available for both the bloginfo() function and within the loop.

codex.wordpress.org/Template_Hierarchy: This page looks at the files available for a theme and when they are called.

codex.wordpress.org/Theme_Development: The WordPress documentation on developing themes.

codex.wordpress.org/Site_Architecture_1.5: The different files available for templating. Although this document was written with version 1.5 the content seems valid.

codex.wordpress.org/Function_Reference: A reference document for all of the functions available in WordPress. Although some don’t matter for template development this is still a good resource for template functions.

codex.wordpress.org/The_Loop: Help on The Loop.

codex.wordpress.org/Using_Themes: Help on using themes.