Archive for the 'howto' Category
How to create a zip archive using PHP
by Justin Silverton
The following is a library that allows you to generate zip file archives using php.
<?php
include("ziplib.php");
$zipfile = new Ziplib;
$zipfile->zl_add_file("This is a test file","path/to/file","g9");
//You can stream the ZIP file or write it in a file on your server
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"testfile.zip\"");
echo $zipfile->zl_pack("zip file comments");
?>
This script will dynamically create a zip archive using the files specified with zl_add_file and output it to the browser (the final zip file will be named: testfile.zip).
Options
zl_add_file allows you to specify the compression level of the file file that will be added to the archive.
- n (none)
- b (bzip)
- g (gzip)
Download
The php zip library can be downloaded Here
11 commentsHow to create Microsoft Office Documents with PHP
By Justin Silverton
There are two main ways to build Excel, Word, and PowerPoint documents using PHP. The first is by using the COM library (only if you are using a Windows server) and the other is by using a more standardized approach such as HTML or CSV.
Dynamically creating a word document:
<?php
$word = new COM("word.application");
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '2"';
$word->Selection->PageSetup->RightMargin = '2"';
//Setup the font
$word->Selection->Font->Name = 'Verdana';
$word->Selection->Font->Size = 8;
//Write some text
$word->Selection->TypeText("This is a test document");
//Save the document as DOC file
$word->Documents[1]->SaveAs("c:\\docs\\test1.doc");
//quit and release COM resources
$word->quit();
$word->Release();
$word = null;
?>
Dynamically creating an excel document
<?php
$excel = new COM("excel.application");
$excel->Visible = 0;
//Create a new workbook
$wkb = $excel->Workbooks->Add();
$sheet = $wkb->Worksheets(1);
//This code adds the text 'myvalue' on row 2, column 4
$sheet->activate;
$cell = $sheet->Cells(2,4);
$cell->Activate;
$cell->value = 'myvalue';
$wkb->SaveAs("C:\docs\test.xls");
//close and free resources
$wkb->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
?>
Dynamically creating a powerpoint presentation
<?php
$powerpnt = new COM("powerpoint.application");
//Creating a new presentation
$pres=$powerpnt->Presentations->Add();
//Adds the first slide. "12" means blank slide
$pres->Slides->Add(1,12);
//Adds another slide. "10" means a slide with a clipart and text
$pres->Slides->Add(2,10);
//Adds a textbox
$pres->Slides[1]->Shapes->AddTextbox(1,20,50,300,40);
//Save the document as PPT file
$powerpnt->Presentations[1]->SaveAs("C:\Docs\test1.ppt");
//free resources and quit powerpoint
$powerpnt->quit();
?>
How to find Word, Excel, and Powerpoint functions
The following will show you all of the functions that are possible when accessing Microsoft Office components through php:

- Open Microsoft Word, Excel, or Powerpoint
- Press Alt+F11 to start the Visual Basic Editor
- Press F2
- Find “ThisDocument” on the left. In the right frame you’ll see the available variables and functions that can be used with the COM object.
compressing files in PHP
by Justin Silverton
Zlib compression has been built into php since version 3 and it can be used to compress the output of your php applications (which can significantly decrease the amount of bandwidth of a page), but what you can also do is compress any file accessible from your webserver.
The code
The following are two functions: compress and uncompress, which can compress and uncompress a specified file.
function uncompress($srcName, $dstName) {
$string = implode(”", gzfile($srcName));
$fp = fopen($dstName, “w”);
fwrite($fp, $string, strlen($string));
fclose($fp);
}
function compress($srcName, $dstName)
{
$fp = fopen($srcName, “r”);
$data = fread ($fp, filesize($srcName));
fclose($fp);
$zp = gzopen($dstName, “w9″);
gzwrite($zp, $data);
gzclose($zp);
}
compress(”test.php”,”test.gz”);
uncompress(”test.gz”,”test2.php”);
Source code can be downloaded here
Description of related zlib functions
More information on zlib related functions can be found here
8 commentsusing php and smarty templates
By Justin Silverton
Why use smarty templates?
One of Smartys primary design goals is to facilitate the separation of application code from presentation. Typically, the application code contains the business logic of your application, written and maintained in PHP code. This code is maintained by programmers. The presentation is the way your content is presented to the end user, which is written and maintained in template files. The templates are maintained by template designers.
At its most basic function, the application code collects content, assigns it to the template engine and displays it. The content might be something like the headline, tagline, author and body of a newspaper article. The application code has no concern how this content will be presented in the template. The template designer is responsible for the presentation. They edit the template files, adding markup and bringing it to completion. This typically involves things like HTML tags, cascading style sheets and other tools provided by the template engine.
This paradigm serves several purposes:
*) Designers can’t break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.
*) Errors in the templates are confined to the Smartys error handling routines, making them as simple and intuitive as possible for the designer.
*) With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.
*) Programmers aren’t messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.
*) Templates are a close representation of what the final output will be, which is an intuitive approach. Designers don’t care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.
*) You are not opening your server to the execution of arbitrary PHP code. Smarty has many security features built in so designers won’t breach security, whether intentional or accidental. They can only do what they are confined to in the templates.
Although application code is separated from presentation, this does not necessarily mean that logic is separated. The application code obviously has logic, but the templates may have logic based on the condition that it is for presentation only. For example, if the designer wants to alternate table row colors or upper-case some assigned content, they can. This is presentation logic, something the programmer should not be concerned with. How often have you had some presentation displayed in a single column and then you wanted it in two or three columns, so the application code needs adjusting to accomodate this? A better approach is to assign the content in one single array and let the template handle the presentation. This will simplify your application and keep your templates flexible. Smarty supplies the tools to handle this kind of situation.
Getting Started with smarty
The first step is to download the smarty template engine Here
1. copy the following to a new file named “smartywrapper.php
// require the Smarty class
require_once(’Smarty.class.php’);
// extend the Smarty class
class smartywrapper extends Smarty {
//this will only work with php 5.X
function function __construct() {
// create the Smarty object
$this->Smarty();
// make sure these folders exist and the permissions are set accordingly
$this->template_dir = ‘/www/example.com/webapp/template/’;
$this->compile_dir = ‘/www/example.com/webapp/compile/’;
$this->config_dir = ‘/www/example.com/webapp/config/’;
$this->cache_dir = ‘/www/example.com/webapp/cache/’;
}
}
2. copy the following to a file named “smartytest.php”
// require the new wrapper class we just created from above
require_once(’smartywrapper.php’);
// create the Smarty_WebApp object
$smarty = new smartywrapper();
// assign a variable, first parameter is the var name, second is the value
$smarty->assign(’test_var_1′,’this is a test’);
//display the template file (all html can now be placed here instead of in your php files)
$smarty->display(’my_template.tpl’);
create a file called my_template.tpl and place it in the directory in $this->template_dir = ‘/www/example.com/webapp/template/’; from above:
This is a test page from smarty, my variable is: {$test_var_1}
launch smartytest.php from you webbrowser and if it is successful, you should see the following
output:
This is a test page from smarty, my variable is: this is a test
Conclusion
Smarty templates can not only be used to increase the overall speed of your php scripts through caching (more about caching can be found Here), but make it easier to develop large-scale applications through the separation of HTML code and php script.
No commentsusing php and imagemagick
by justin silverton
What is imagemagick and why do i need it?
image magick is a free and useful tool that can do the following:
1) Convert an image from one format to another (e.g. PNG to JPEG
2) Resize, rotate, sharpen, color reduce, or add special effects to an image
3) Create a montage of image thumbnails
4) Create a transparent image suitable for use on the Web
5) Turn a group of images into a GIF animation sequence
6) Create a composite image by combining several separate image
7) Draw shapes or text on an image
8) Decorate an image with a border or frame
9) Describe the format and characteristics of an image
Accessing it from PHP
In my experience, image magick is most likely installed here (on *nix systems) (it also may be in a different area on your system) : /usr/bin/convert
as an example of how I used it, I needed to automatically create thumbnails of images that were being uploaded through and administrative interface for a photo gallery.
exec (”/usr/local/bin/convert -geometry 480X -quality 70 $sourcepath $destpath”);
?>
notes: change /usr/local/bin to the directory on your system where it is installed.
$sourcepath: source image we want to convert (including image name)
$destpath: destination image name (including image name)
command line options
-adjoin join images into a single multi-image file
-affine matrix drawing transform matrix
-antialias remove pixel-aliasing
-append append an image sequence
-average average an image sequence
-background color background color
-blur geometry blur the image
-border geometry surround image with a border of color
-bordercolor color border color
-box color color for annotation bounding box
-cache threshold megabytes of memory available to the pixel cache
-gaussian geometry gaussian blur an image
-geometry geometry perferred size or location of the image
a full list can be found by executing convert –?
Download
Don’t have imagemagick on your system? download it for free Here
It’s free and licensed under the GNU





