Click here to Skip to main content
15,881,172 members
Articles / Web Development / HTML

Useful PHP Extensions

Rate me:
Please Sign up or sign in to vote.
4.88/5 (15 votes)
17 Nov 2009CPOL16 min read 85.8K   5.1K   41   14
An article about some useful PHP 5 extensions with a fully functional demo and all required files

Introduction

Here you can download some useful PHP 5 extensions with a fully functional demo and all required files.
My idea is to let this article grow in the future by adding new functionality and more extensions.

All the code you can download here is cleanly written and reusable PHP code that can be copy-and-pasted unchanged into your project.
The downloads here also contain a manual and the required PHP extensions for Linux and Windows.

Currently this article contains the following chapters:

  1. Project 1: Upload Progress Display
  2. Project 2: Image Processing with MagickWand
  3. Project 3: Image Cutter allows to crop a part out of an uploaded image online
  4. Problems with Wamp server
  5. Beginner Tutorial: How to run the code from this article on Windows (Xampp)
  6. Hacker-Secure Webprogramming

Project 1: Upload Progress Display

This project shows the progress of one or multiple file uploads in the browser.

Image 1

I never understood why browsers show a window for all the current downloads but for uploads the browser simply shows NOTHING ????
The poor user who uploads a huge file has NO IDEA if his upload will take 10 minutes more or if it will finish in 10 hours.
An intelligent browser should show a progress bar and the remaining time for lengthy file uploads - the same way as it does for downloads.
Incredible: Not even one of the currently existing browsers has such a useful and basic feature !!

It's really absurd: Now the web developers must do the work which the browser developers have neglected !!
And this is not easy: PHP must obtain the upload status in a complicated way from the webserver. (e.g. Apache / IIS)
Therefore a PHP extension is required which must be installed on the server.

If you start Googling for this topic, you find a lot. But most of the stuff is buggy and doesn't work or doesn't support multiple files. Documentation normally does not exist.

I decided to use the PHP extension with the name "uploadprogress". But this extension comes with no documentation and a really ugly demo from his author that uses two IFrames.

Here you find a fully functional demo with the following features:

  • Javascript obtains the progress info via Ajax from the server and updates the display every 3 seconds.
  • Display of an upload progressbar
  • Display of the upload status: number of the current file, uploaded bytes, total bytes, current speed, remaining time.
  • The upload can be cancelled with a Cancel link or with the Stop button of the browser.
  • While an upload is active, the entire webpage is completely blocked and transparently greyed and the Wait cursor is displayed.
  • The code is tested on various browsers.

Upload Progress - Installation

Windows

In the ZIP file that you can download here, you find php_uploadprogress.dll. Copy this DLL into your PHP extension folder (the folder defined in extension_dir in PHP.ini).

It was not easy to find this DLL for Windows. You find only very few websites where you can download this DLL already compiled for Windows. And after trying some different versions of this DLL, I found that most of these DLLs have their individual bugs or even crash Apache. I invested several frustrating days to get a version of this DLL which works correctly and get it running! I finally found it on the page of Pierre.

Linux

In the ZIP file, you also find a PECL package which contains the source code.

Upload Progress - Configuration

You have to add the following lines to your PHP.ini file:

extension = php_uploadprogress.dll
uploadprogress.file.filename_template = C:\Program Files\xampp\tmp\info_%s.txt
uploadprogress.get_contents = 0

IMPORTANT

The path for the template file must be valid and it must contain a "%s" !!
This "%s" will be replaced with the identifier of the upload.
For each upload, a little text file is generated in the given folder which stores the actual status of the download. This file is deleted after the upload has finished.

UploadProgress - Testing

It will be completely IMPOSSIBLE to test the upload progress display if your Browser runs on the same computer as the server (localhost).
Even if you upload a 100 MB file, you will not even see one single actualization of the display.

If you have no web server in the internet to test with or if you want to test on localhost for easier debugging, there is a trick:

Install Proxomitron! This is a local proxy server with many functionalities that I will not explain here. One feature is to display the traffic to and from your browser.

In your browser, you must configure a proxy server on localhost port 8080 and remove any exceptions for localhost.

Image 2

Then in Proxomitron, click the Button Log Window, do a right-click into the Log Window and in the menu click "View Posted Data". That's all.

Image 3

Now Proxomitron shows all the traffic to your browser (yellow) and from your browser (green). If you upload a 20 MB file to the server, you will see all the posted data (grey). But if you ever have printed 20 MB data to a Log Window, you know how slow this is. With this trick, you have drastically slowed down the data transfer and the upload progress display will work perfectly - even on localhost. Do NOT close the Log window! It must be open all the time while you are testing UploadProgress.

Project 2: Image Processing with MagickWand

Why not using the GD Library ?
PHP comes with the built-in GD library for image processing which is quite basic. It supports only GIF, JPG and PNG and has few functionality.

Some years ago, I was shocked when I used the GD library for the first time because support for GIF had recently been removed! I could not believe that in the brains of some PHP developers, the completely mad idea was born to remove the most important graphics format for the internet! For the lack of GIF support, I decided not to use GD. It took some years until they recognized their fatal error and added GIF support again.

Some months ago, I gave the GD library a second chance. But rotating a 7 Megapixel image by 90 degree PHP threw an out of memory error. I needed an online image editor where people can upload ANY image - also from their digital camera. So the GD library was sorted out another time. Additionally the GD library offers only basic functionality and the quality of resulting images is not the best.

I searched for alternatives and found the MagickWand library:

  • MagickWand is programmed more intelligently: when you work with huge images, they are stored in filemappings instead of holding all the image data in memory. I have never seen an out of memory error while working with MagickWand.
  • The MagickWand library has a vast amount of functionality including transparent image operations, various transformations and filters.
  • The Resize functionality alone offers you a long list of filters to resize an image: Bessel, Gaussian, Blackman, Hermite, Hanning, Hamming, Catrom, Mitchell, Lanczos, Quadratic, Cubic, Triangle, Point, Box, Sinc,....
  • The list of supported image formats is long: A, ART, AVI, AVS, B, BIE, BMP, BMP2, BMP3, C, CAPTION, CIN, CIP, CLIP, CLIPBOARD, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DFONT, DNG, DPS, DPX, EMF, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EPT2, EPT3, EXR, FAX, FITS, FRACTAL, FTS, G, G3, GIF, GIF87, GRADIENT, GRAY, HISTOGRAM, HTM, HTML, ICB, ICO, ICON, INFO, IPL, JBG, JBIG, JNG, JP2, JPC, JPEG, JPG, JPX, K, LABEL, M, M2V, MAP, MAT, MATTE, MIFF, MNG, MONO, MPC, MPEG, MPG, MRW, MSL, MSVG, MTV, MVG, NEF, NULL, O, ORF, OTB, OTF, PAL, PALM, PAM, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PEF, PFA, PFB, PFM, PGM, PGX, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG24, PNG32, PNG8, PNM, PPM, PREVIEW, PS, PS2, PS3, PSD, PTIF, PWP, R, RAF, RAS, RGB, RGBA, RGBO, RLA, RLE, SCR, SCT, SFW, SGI, SHTML, STEGANO, SUN, SVG, SVGZ, TEXT, TGA, THUMBNAIL, TIFF, TIFF64, TILE, TIM, TTC, TTF, TXT, UIL, UYVY, VDA, VICAR, VID, VIFF, VST, WBMP, WMF, WMFWIN32, WMZ, WPG, X, X3F, XBM, XC, XCF, XPM, XV, XWD, Y, YCbCr, YCbCrA, YUV
  • The quality of resulting images is excellent as you can see in the demo
  • You can use any TTF font to write text into an image. The font is specified as TTF file which need NOT be installed on the server
  • A very long list of graphics commands: MagickWand: 247 commands, DrawingWand: 117 commands, PixelWand: 51 commands
  • The library runs stable. I have never seen crashes (e.g. by passing corrupt image files)
  • The code is Open Source

But the MagickWand library has one drawback:
A documentation is not available. What you may find in the internet is a definition of the commands and their parameters. But a detailed explanation does not exist and sample code is very difficult to find.

This is one of the reasons why I publish this article. My ready-to-use package makes it ultra easy for you to start with MagickWand.

MagickWand - Demo Project

To add the text to this image, you need exactly 4 lines of PHP code:

Image 4

The demo project contains a PHP class "Magick" which you can reuse to process images.
It contains the following functionality:

  • Loading images of any size, also with transparent backgrounds
  • Resizing images (creating thumbnails)
  • Cropping images (see ImageCutter project below)
  • Rotating images
  • Blurring images
  • Flipping/Mirroring images
  • Writing Text into images
  • Creating Captcha images
  • Saving images to disk
  • Streaming images directly to the browser
  • Defining the quality of JPG compression
  • Obtaining information from the image header (e.g. width, height, type) without loading the entire image
  • The class has a clean error handling (no crap code) and throws exceptions on error

The class demonstrates the usage of MagickWand, DrawingWand, PixelWand with the following "magick" commands:
NewMagickWand, NewDrawingWand, NewPixelWand, MagickPingImage, MagickGetImageType, MagickReadImage, MagickNewImage, MagickCompositeImage, MagickGetExceptionString, PixelGetExceptionString, DrawGetExceptionString, MagickGetImageWidth, MagickRotateImage, MagickResizeImage, MagickCropImage, MagickFlipImage, MagickFlopImage, MagickBlurImage, DrawSetFont, DrawSetFontSize, DrawSetGravity, PixelSetOpacity, DrawSetFillColor, MagickAnnotateImage, MagickSetFormat, MagickEchoImageBlob, MagickSetImageCompression, MagickSetImageCompressionQuality, MagickWriteImage, DestroyMagickWand, DestroyPixelWand, DestroyDrawingWand.

MagickWand - Adding more Functionality

Obviously my class covers only a very small percentage of the vast variety of functionality in the MagickWand library.

If you need more functionality, please do NOT post questions here like "How do I draw a circle?".
I never did it because I don't need it, so I don't know it!
Instead try it on your own and when you've got it, add a new function to the class and send me the code together with a demo!
If your code is useful, works correctly and is cleanly written, I will publish it here on CodeProject.
I hope that with your help, my Magick class will grow and become more and more versatile.

So if a functionality, that you need, is missing in the Magick class, this is because YOU did not yet add it!

MagickWand - Creating Captcha Images

The internet is full of BAD captcha images:

Image 5 Image 6

These captcha are bad because the characters and the random data of the image have different colors. It would be extremely easy to apply a color filter which filters out everything that is not black and send the rest to OCR software which would recognize the characters 100% correctly. These captcha's are ultra easy to crack!

Image 7 Image 8

These captcha are bad because the characters are cropped. In the left image the second character may be an "I" or a "T". The last character may be an "U" or a "0". You have to guess.

Image 9

This is the worst captcha: It is unreadable. You have to guess.

Image 10

This is a good example for a captcha which I created with my Magick class.

  1. The characters and lines of background have exactly the same color (no color filtering possible)
  2. The characters and background have the same line width (no filtering possible)
  3. The characters have random size, rotation and position
  4. The characters are entirely visible and not cropped
  5. The background has similar roundings as the characters
  6. This captcha is easy to read for humans but impossible to detect for text recognition software (OCR)

You can play around with your own background image and your own font (any TTF). It would also be possible to modify the background image each time you generate a new captcha. I recommend to use a big background image and crop a random part of it. Be aware that rotating is slow, so I do not recommend to rotate the background!

The demo project also demonstrates how easy you can verify with Ajax if the user has entered a valid captcha code.

IMPORTANT

You should always check the captcha code case-insensitive because the characters vary in size (random size) and a lowercase "x" may look the same as an uppercase "X".

MagickWand - Version Confusion

The MagickWand extension may be compiled as:

  • Q8, which means that each pixel of the image uses 8 Bit for Red, 8 Bit for Green and 8 Bit for Blue = 24 Bit per pixel (2^24 colors = 16 million colors)
  • Q16, which means 16 Bit for each color = 48 Bit per pixel (2^48 colors = 281.474.976.710.656 colors) I have absolutely no idea who needs so many colors but I know for sure that the human eye cannot distinguish that many colors.

There is no reason why you should use the Q16 version. The Q8 version offers excellent image quality, uses less memory and is faster than Q16. In phpinfo(), you can see which version is installed.

Apart from that, the MagickWand extension can be compiled as:

  • static, which means that all the required code is compiled into one single big stand-alone DLL
  • dynamic, which means that the MagickWand extension for PHP is a small DLL which requires the entire ImageMagick package (12 MB) to be installed additionally on the server. The small dynamic PHP extension DLL loads two dozen additional DLLs.

MagicWand - Installation

Windows

In the ZIP file that you can download here, you find a Q8 static compiled php_magickwand.dll. Copy this DLL into your PHP extension folder (the folder defined in extension_dir in PHP.ini) There is NOTHING ELSE to be installed on the server! This DLL is stand-alone!

It was not easy to find this DLL because you will notice that all links to Windows binaries are dead. On the homepage of MagickWand for PHP, you see that Windows is not supported anymore (the folder on the FTP server still exists, but it is empty). I finally found this DLL on the page of Dirk.

Linux

In the ZIP file, you also find a RPM package. The ImageMagick library must be additionally installed on the server. (The PHP extension is dynamic compiled)

MagickWand - Configuration

Add this line to your PHP.ini:

extension = php_magickwand.dll

Project 3: Image Cutter

This project allows users to upload an image of any size and any format (e.g. a 7 MegaPixel photo from their digital camera) and cut it online. I wrote this project because my server allows users to add a passport photo of themselves to their personal data. This passport photo always has the fixed size of 120 x 150 pixels. As the majority of people is not able to use programs like Photoshop to upload an image with the final resolution this image cutter allows them to crop a portion out of an uploaded image online very easily.

Features

  1. The user uploads an image with high resolution (the demo uses Gandalf with his Magic Wand)
  2. This image will be shrinked to a maximum size of 600 pixels which is then displayed to the user.
  3. The user can rotate the image if necessary
  4. The user then positions a green rectangle over the face in the shrinked image and clicks the button "Crop".
  5. He will see a preview of the cropped image.
  6. When clicking the final "Accept" button the temporary Shrink Image will be deleted and the Crop Image will be moved to it's final destination.
  7. You should have a taskjob which deletes all old files in the Temp folder once in the night because if a user does never accept the final image the temporary images will remain on the server's disk.
  8. While doing all these steps the page is never reloaded: The code uses Ajax and a complex JavaScript.
  9. The code has been tested on various browsers.

Image 11

Download

The image cutter project is a separate download. You will have to install the MagickWand extension which is not included in this download. So you have to download additionally the MagickWand project. To keep the project simple, the code to upload an image is not included. You will obviously use my UploadProgress project for that. The demo project uses 4 fixed images that you can use to play around with.

Problems with Wamp Server

If you have a Wamp server, you will not be able to use the DLLs that you can download here.
Wamp shows a very stupid error message saying that the versions of the extension DLLs are not compatible with the PHP version of the server.
This is complete nonsense because between the various PHP versions there may be only very small differences which usually in no way affect the functioning of extensions. Wamp forces you to recompile the extensions each time when you update your server to a new version.

There is a simple solution: Do not use Wamp! Use Xampp instead which works perfectly.

Beginner Tutorial: Running the Samples on Windows (Xampp)

  1. Check that there is no program on your PC which runs a server on Port 80. If you have installed Skype, make sure that under the menu Tools -> Options -> Connection, the checkbox "Use Port 80 and 443 as alternatives for incoming connections" is NOT checked!! FileSharing software may also occupy Port 80.
  2. Check that your browser does not have a Proxy server for HTTP configured. If so, turn it off!
  3. Install Xampp Server which includes Apache, mySql, PHP and more into C:\Program Files\Xampp.
  4. Open the file C:\Program Files\Xampp\apache\bin\php.ini and make the changes described above in the chapters "Configuration".
  5. Copy php_uploadprogress.dll and php_magickwand.dll into the folder C:\Program Files\Xampp\php\ext\
  6. After that, start the Apache Server from the Xampp Control Panel in startmenu.
  7. Copy the entire content of the ZIP file from CodeProject into the folders: C:\Program Files\Xampp\htdocs\UploadProgress and C:\Program Files\Xampp\htdocs\MagickWand
  8. If you did it correctly, this file will exist: C:\Program Files\Xampp\htdocs\UploadProgress\index.php
  9. Enter http://localhost in your browser. From the Xampp menu on the left, chose phpinfo().
    Now you must see the two extensions "magickwand" and "uploadprogress" each with an own table.
  10. In your browser, enter http://localhost/UploadProgress or http://localhost/MagickWand and start playing with it!
  11. NOTE: After each change in PHP.ini, you must restart Apache!

Hacker-secure Webprogramming

Today, very important topics are:

  • How do I write code that is secure against hacker attacks?
  • How do I configure a PHP server correctly (Apache / IIS)?
  • What are botnets and how can my server be abused by them?
  • What important additions to Virus Scanners should I install?
  • How can I check a server remotely for vulnerabilities?
  • Were can I learn hacking and how to defeat it?

I wrote a very detailed article about Server Security here on CodeProject.
I highly recommend reading this entire article whatever webapplication you write!
There you can also download a SecurityCheck script in PHP and ASP.

Webservices

You may also be interested in my article about Webservice Servers and Clients in PHP here on CodeProject.

Elmü

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ElmüSoft
Chile Chile
Software Engineer since 40 years.

Comments and Discussions

 
Questionuploadprogress.dll problem - again Pin
alkaptonuric9-Dec-12 15:11
alkaptonuric9-Dec-12 15:11 
AnswerRe: uploadprogress.dll problem - again Pin
Elmue15-Dec-12 2:18
Elmue15-Dec-12 2:18 
Questionuploadprogress problem Pin
introcosmo9-Oct-12 7:23
introcosmo9-Oct-12 7:23 
AnswerRe: uploadprogress problem Pin
Elmue13-Oct-12 3:58
Elmue13-Oct-12 3:58 
GeneralRe: uploadprogress problem Pin
introcosmo13-Oct-12 23:19
introcosmo13-Oct-12 23:19 
GeneralRe: uploadprogress problem Pin
Elmue17-Oct-12 16:34
Elmue17-Oct-12 16:34 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey23-Feb-12 18:50
professionalManoj Kumar Choubey23-Feb-12 18:50 
QuestionImage upload progress Pin
kannan pichumani7-Dec-11 20:37
kannan pichumani7-Dec-11 20:37 
AnswerRe: Image upload progress Pin
Elmue8-Dec-11 3:41
Elmue8-Dec-11 3:41 
GeneralMagickWand extension Pin
AmritaShaha29-Mar-10 2:19
AmritaShaha29-Mar-10 2:19 
GeneralRe: MagickWand extension Pin
Elmue29-Mar-10 2:52
Elmue29-Mar-10 2:52 
????
GeneralGreat Article Pin
Jon Anthony17-Dec-09 2:46
Jon Anthony17-Dec-09 2:46 
GeneralMy vote of 2 Pin
Priyank Bolia18-Nov-09 16:02
Priyank Bolia18-Nov-09 16:02 
GeneralRe: My vote of 2 Pin
Brunhilde19-Nov-09 7:50
Brunhilde19-Nov-09 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.