Build PHP extensions with swig

Source: Internet
Author: User
Tags ibm db2 mcrypt 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, Typeapt-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 http://prdownloads.sourceforge.net/swig/swig-1.3.40.tar.gz$ tar xzf swig-1.3.40.tar.gz $ cd swig-1.3.40$ ./configure $ make$ sudo make install $ which swig/usr/local/bin/swig

Build an extension

Let's build an extension to use LinuxmcryptThe library encrypts and decrypts messages. PHP providesmcryptLibrary, but it is only the result of a 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 appropriatemcryptLibrary and header file:$ sudo apt-get install libmcrypt-dev libmcrypt4 mcrypt libmhash2.

If you prefer to build from scratch, or your distribution does not includemcryptYou can download the source code from its home page (see references ). ReplacedcryptOfmcryptUtilities also depend onlibmhashTherefore, you must compilemcryptPreviously builtlibmhash. Listing 2 shows the buildlibmhashThe required code.

List 2. Buildlibmhash

$ # libmhash$ wget http://sourceforge.net/projects/mhash/files/mhash/0.9.9.9//  mhash-0.9.9.9.tar.bz2/download$ tar xfj mhash-0.9.9.9.tar.bz2$ cd mhash-0.9.9.9$ ./configure$ make$ sudo make install # libmcrypt$ wget ftp://mcrypt.hellug.gr/pub/crypto/mcrypt/libmcrypt//  libmcrypt-2.5.7.tar.gz$ tar xfz libmcrypt-2.5.7.tar.gz$ cd libmcrypt-2.5.7$ ./configure$ make$ sudo make install$ # mcrypt$ wget wget http://sourceforge.net/projects/mcrypt/files/MCrypt/2.6.8//  mcrypt-2.6.8.tar.gz/download$ tar xfz mcrypt-2.6.8.tar.gz$ cd mcrypt-2.6.8$ ./configure$ make$ sudo make install            

Next, create the C code for this extension. The most interesting function in the Code is located at the bottom of listing 3encode()Anddecode(). 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 displayed12345678(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. Several steps are required for compilation: 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, andmcryptLibrary. Be sure to use-fpicOption to build each c source file, because this option can generate code independent from the location, which is very suitable for sharing libraries.

$ cc -fpic -c secret.c$ gcc `php-config --includes` -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.-lmcryptOption to parse the entry point in this extensionmcryptThe calls in the database. 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();?>            

SearchLoaded Configuration FileA line of code starting. For example, on the test platform used in this article, this program generates an outputLoaded 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 encoded stringDouble secret probationBase64 is used to convert the encrypted string into 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 installed in/usr/local/lib of the system.mcryptLibrary, using PHPCLICommand to run the sample code:

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

Back to Top

Conclusion

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. IGenerate a package for other scripting languages. You only need to write an extension once, and then you can share it with PHP, Perl, Python, Ruby and other developers.

References

Learning

  • 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.
  • Php.net 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.
  • To listen to interesting interviews and discussions for software developers, visit {
    Linkqueryappend (this)
    } "Href =" http://www.ibm.com/developerworks/podcast/ "> 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.
  • {
    Linkqueryappend (this)
    } "Href =" http://www.ibm.com/developerworks/community "> my developerworks community is an example of a successful community that covers topics of various content.
  • Stay tuned to developerworks technical events and network broadcasts.
  • Refer to recent seminars, trade exhibitions, network broadcasts, and other {
    Linkqueryappend (this)
    } "Href =" http://www.ibm.com/developerworks/views/opensource/events.jsp? S_tact = 105agx52 & s_cmp = content "> activity.
  • 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.
  • DownloadmcryptSource code of the 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.

Discussion

  • Participate {
    Linkqueryappend (this)
    } "Href =" http://www.ibm.com/developerworks/blogs "> developerworks blogs and join the developerworks community.
  • Participate in developerworks {
    Linkqueryappend (this)
    } "Href =" http://www.ibm.com/developerworks/forums/dw_forum.jsp? Forum = 992 & cat = 51 "> PHP Forum: Use IBM information management products (DB2 and IDs) to develop PHP applications.

 

 

Source: http://www.ibm.com/developerworks/cn/opensource/os-php-swig/index.html

 

Related Article

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: info-contact@alibabacloud.com 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.