Build PHP extensions with swig

Source: Internet
Author: User
Tags ibm db2 mcrypt php cli php reader printable characters ibm developerworks

Author: Martin Streicher, software developer, pixel, byte, and comma
Although writing a PHP extension is not very difficult, swig does further simplify this task, mainly because it automates the work required to combine PHP with C or C ++. Given a description of a function-the name of the Function and Its Parameter-swig, a package is generated to connect PHP with lower-layer code.

Swig requires some prerequisites. Some Latest versions of swig require the PHP version to be V5. In addition, a C/C ++ compiler, such as GNU Compiler Collection (GCC) and PHP module development kit (MDK), is required ). In particular, you also need header files related to PHP installation. If you are using Ubuntu Linux or a Debian variant and have installed PHP V5 from a package repository, you can use advanced packaging tool (APT) added the MDK. For example, on Ubuntu kernel 9.10, type apt-Get install sudo apt-Get install -- install-recommends -- yes php5-dev.

By the end of 2009, the latest version of swig was v1.3.40 (see references ). Download the tarball (a tar file compressed by gzip), decompress it, configure the code for your system, and build and install the software. (To find all the configuration options, run./configure -- Help ). Listing 1 provides the commands required to download, decompress, and install swig.

Listing 1. Download, decompress, and install swig

$ Wget
$ Tar xzf swig-1.3.40.tar.gz
$ CD swig-1.3.40
$ Make
$ Sudo make install
$ Which swig

Build an extension

Let's build an extension to encrypt and decrypt messages using the Linux mcrypt library. PHP provides an mcrypt library, but it is only the result of slight modification to the C version of this library. Now, let's construct two more concise methods: one for string encryption and the other for string decryption.

On Ubuntu or similar systems, you can use apt to install the appropriate mcrypt library and header file: $ sudo apt-Get install libmcrypt-dev libmcrypt4 mcrypt libmhash2.

If you would rather build from scratch or your distribution does not include mcrypt, you can download the source code from its home page (see references ). Instead of crypt, The mcrypt utility also relies on libmhash. Therefore, libmhash must be built before mcrypt compilation. Listing 2 shows the Code required to build libmhash.

Listing 2. Constructing libmhash

$ # Libmhash
$ Wget //
$ Tar xfj mhash-
$ Mhash- CD
$ Make
$ Sudo make install

# Libmcrypt
$ Wget //
$ Tar xfz libmcrypt-2.5.7.tar.gz
$ Libmcrypt-2.5.7 CD
$ Make
$ Sudo make install

$ # Mcrypt
$ Wget //
$ Tar xfz mcrypt-2.6.8.tar.gz
$ Mcrypt-2.6.8 CD
$ Make
$ Sudo make install

Next, create the C code for this extension. The most interesting functions in the Code are the encode () and decode () at the bottom of listing 3 (). Both have two parameters-one string and one count-and both return strings. The former encrypts a plain text string and returns its encoding; the latter decrypts an encrypted string and returns plain text. A string can be of any length.

The code above uses the Data Encryption Standard-electronic codebook (DES-ECB) algorithm. The secret key can be any string of eight characters and can be displayed as 12345678 (for demonstration purposes only ). If you want to exchange encrypted messages with others, you need to obtain the exchange key or create a new key and share it. (The encryption algorithm is independent of the architecture and language. However, both the sender and receiver must know the secret key .)

Listing 3. php extension C code

# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <mcrypt. h>

Char * encode (char * string, int length );
Char * decode (char * string, int length );

Mcrypt start (){
Mcrypt TD = mcrypt_module_open ("des", null, "ECB", null );
If (TD = mcrypt_failed ){
Return (mcrypt_failed );

If (mcrypt_enc_self_test (TD )! = 0 ){
Return (mcrypt_failed );

Int I;
Char * IV;
Int iv_size = mcrypt_enc_get_iv_size (TD );
If (iv_size! = 0 ){
IV = calloc (1, iv_size );
For (I = 0; I <iv_size; I ++ ){
IV [I] = rand ();

Int keysize = mcrypt_enc_get_key_size (TD );
Char * Key = calloc (1, keysize );
Memcpy (key, "12345678", keysize );

I = mcrypt_generic_init (TD, key, keysize, IV );
If (I <0 ){
Mcrypt_perror (I );
Exit (1 );

Return (TD );

Void end (mcrypt TD ){
Mcrypt_generic_deinit (TD );
Mcrypt_module_close (TD );

# Define b64_def_line_size 72
# Define b64_min_line_size 4

** Encode 3 8-bit binary bytes as 4 '6-bit 'characters
Void encodeblock (unsigned char in [3], unsigned char out [4], int Len ){
Static const char
Cb64 [] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 + /";
Out [0] = cb64 [in [0]> 2];
Out [1] = cb64 [(in [0] & 0x03) <4) | (in [1] & 0xf0)> 4)];
Out [2] = (unsigned char) (LEN> 1? Cb64 [
(In [1] & 0x0f) <2) | (in [2] & 0xc0)> 6)]: '= ');
Out [3] = (unsigned char) (LEN> 2? Cb64 [in [2] & 0x3f]: '= ');

Char * base64encode (char * input, int size ){
Int I, X, Len;
Unsigned char in [3], out [4];
Char * target = calloc (1, (size + 2)/3) * 4 + 1 );
Char * t = target;

For (x = 0; x <size ;){
Len = 0;

For (I = 0; I <3; I ++ ){
If (x <size ){
Len ++;
In [I] = input [x ++];
Else {
In [I] = 0;

If (LEN ){
Encodeblock (In, out, Len );
For (I = 0; I <4; I ++ ){
* T ++ = out [I];

Return (target );

Char * encode (char * string, int length ){
Mcrypt TD = start ();
Int blocksize = mcrypt_enc_get_block_size (TD );
Int cryptsize = (Length + blocksize-1)/blocksize) * blocksize;
Char * target = calloc (1, cryptsize );

Memcpy (target, String, length );

If (mcrypt_generic (TD, target, cryptsize )! = 0 ){
Fprintf (stderr, "code failing ");

End (TD );

Char * result = base64encode (target, cryptsize );

Free (target );
Return result;

Char * decode (char * string, int length ){
Mcrypt TD = start ();
Int blocksize = mcrypt_enc_get_block_size (TD );
Char * block_buffer = calloc (1, blocksize );
Int decryptlength = (Length + blocksize-1)/blocksize * blocksize;
Char * target = calloc (1, decryptlength );

Memcpy (target, String, length );

Mdecrypt_generic (TD, target, decryptlength );

End (TD );

Free (block_buffer );
Return (target );

Copy and paste the code in listing 3 to a new file named secret. C. The next task is to describe the extended API using swig's own syntax.


Back to Top

Swig File

In the current development stage, you can manually build an extension based on secret. C. But swig can help you with this hard work-and you only need to use a small amount of pseudo code. The secret. I shown in Listing 4 is the swig template of the new extension.

Listing 4. Secret. I

% Module secret

% {
Extern char * encode (char * string, int length );
Extern char * decode (char * string, int length );

Extern char * encode (char * string, int length );
Extern char * decode (char * string, int length );

The full interpretation of swig syntax and options is beyond the scope of this article. Complete documentation can be found online (see references ). To put it simply, the swig file generally declares the extension name in line 3. Other part of the file declares the entry point. This is the content. The first step is to generate the code package: $ swig-PHP secret. I.

Swig converts secret. I to secret_wrap.c. The next few steps are to build and link these package code, this extension, and the mcrypt library. Be sure to use the-FPIC option to build each c source file, because this option can generate code independent from the location, which is very suitable for shared libraries.

$ CC-FPIC-C secret. c
$ GCC 'php-config -- include'-FPIC-C secret_wrap.c
$ Gcc-shared *. O-o secret. So-lmcrypt
$ Sudo CP secret. So 'php-config -- Extension-dir'

The first two commands construct the C source code. The third command builds the PHP extension. -The lmcrypt option resolves the calls of the entry points in this extension in the mcrypt library. The fourth command will put this new PHP extension into a suitable directory so that it can be loaded by PHP.

Before writing PHP code, the last step is to load the extension. Open the appropriate PHP. ini file-or the command line variant for Apache or PHP-and add a line of code: Extension = secret. So.

If you are not sure which PHP. ini file to edit, You can query the PHP file. Create a program with three lines of code as shown below and run it using a browser or interactive Interpreter:

<? PHP
Phpinfo ();

Search for a line of code starting with loaded configuration file. For example, on the test platform used in this article, this program generates the output loaded configuration file =>/etc/PhP5/CLI/PHP. ini. Therefore, the file to be edited is/etc/PhP5/CLI/PHP. ini.


Back to Top

Compile PHP code

With this outstanding new extension, you can start to write PHP. Listing 5 shows code. php.

Listing 5. Code. php

<? PHP
Include ("secret. php ");

$ String = "Double secret probation ";
$ Base64encode = secret: encode ($ string, strlen ($ string ));
$ Base64decode = base64_decode ($ base64encode );
$ Decode = secret: Decode ($ base64decode, strlen ($ base64decode ));

Echo $ Decode. "/N ";

Row 1 loads this extension. Line 4 encode the string double secret probation and use base64 to convert the encrypted string to printable characters for transmission by email or other programs. Line 5 decodes the base64 encoding to generate the original character. Line 6 decrypts the encrypted message into the original text.

Assume that the code is saved in coder. php and the mcrypt library is installed in/usr/local/lib of the system. You can run the sample code using the php cli command:

$ LD_LIBRARY_PATH =/usr/local/lib PHP./code. php
Double secret probation



Back to Top


Swig is an excellent way to reuse existing code. Wrap C or C ++ libraries with swig and integrate the results into your next web or system application. Even better, swig can also generate packaging programs for other scripting languages from the same. I file. You only need to write an extension once, and then you can share it with PHP, Perl, Python, Ruby and other developers.



Learn more about the swig extension generator at the swig site.

Read the swig document to get articles and Tutorials that make swig easier to use. This project also maintains several wikis. is the PHP developer resource center.

View the "Recommended PHP reader list ".

Browse all php content on developerworks.

View PHP project resources on IBM developerworks and expand PHP skills.

For interesting interviews and discussions for software developers, visit the developerworks podcasts.

How to use a database in PHP? Try Zend core for IBM, a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9.

My developerworks community is an example of a successful community that covers various topics.

Stay tuned to developerworks technical events and network broadcasts.

Check out recent seminars, trade exhibitions, network broadcasts, and other activities for IBM open source code developers to be held globally.

Visit the developerworks open source area to get a wealth of how-to information, tools and project updates, and the most popular articles and tutorials to help you develop with open source technology, they are used in combination with IBM products.

See the free developerworks demonstration center and learn about IBM and open-source technologies and product features.

Obtain products and technologies

Download swig from this project site.

Download the source code of the mcrypt library.

Use the IBM product evaluation trial software to improve your next open-source development project, which can be downloaded.

Download the IBM product evaluation trial software or ibm soa sandbox for reuse, and use application development tools and middleware Products from DB2, Lotus, rational, Tivoli, and websphere.


Join developerworks blogs and join the developerworks community.

Participate in the developerworks PHP Forum: Use IBM information management products (DB2, IDS) to develop PHP applications.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.