Part 2 : Writing PHP Extension

In 1st Part of this article, we already warmed up by preparing your development environment and grab the concept of PHP internal (including IIS 7.0). In this part I will guide you to write your first PHP extension (the simplest one), with VC++ 2008 in Windows Vista. Continuing the previous two steps in Part 1, lets go to step 3.

3. Setup Build Environment with VC++ 2008
I assume you have installed IIS 7.0 and VC++ 2008. After you’ve got PHP 5 installed and configured for your server, download and extract the complete PHP 5 source code, also from www.php.net. DO NOT extract the source archive over top of your existing binary installation. This article’s  my PHP 5.2.6 binaries installed to C:\PHP, and its source codes extracted to D:\PHP on Windows\PHP-DEV\PHP-5.2.6.

In VC++ 2008, create a new Win32 project using the project template, name it FirstPHPExt. Select DLL app type in the VC++ Wizard and click finish.  Open your C++ Project Property form and do the following changes in:

Configuration Properties > General
- Character Set                                 --> Use Multi-Byte Character Set

Configuration Properties > C/C++ > General
- Debug Information Format             --> Program Database (/Zi)
- Detect 64-bit Portability Issues     --> No
- Additional Include Directories        --> Root, Zend, TSRM, Regex, and Main

01

Configuration Properties > C/C++ > Preprocessor

Add : ZEND_DEBUG = 0; ZTS =1; ZEND_WIN32; PHP_WIN32

02

Note: Do not be tempted to change ZEND_DEBUG to 1, even for Debug build, this will prevent our extension from being loaded into the pre-built PHP binaries installed on your system.

Configuration Properties > Linker > General
- Additional Include Directories        --> C:\PHP\Dev (where php5ts.lib located)
- Output Files                                     --> $(OutDir)\MyPHP-Custom.dll

03

Configuration Properties > Linker > Input
- Additional Dependencies                 --> php5ts.lib

Ok, now we are ready to write extension codes.

4. Writing PHP Extension Codes

We will write a simple PHP extension to calculate the double up value of an inputted parameter. We will use this method in PHP user-space like this:

<?php
      $value = 14;
      $result = DoubleUp($value);
      print "Calling DoubleUp($value) returned $result";
?>

Start with modifying stdafx.h header file to include PHP Extension headers.

#pragma once
/* PHP Zend Extension headers */
/* include zend win32 config first */
#include "zend_config.w32.h"
/* include standard header */
#include "php.h"

Then add the following codes to FirstPHPExt.cpp file:

#include "stdafx.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(DoubleUp);

/* compiled function list so Zend knows what's in this module */
zend_function_entry FirstPHPExtModule_functions[] = {
    ZEND_FE(DoubleUp, NULL)
    {NULL, NULL, NULL}
};

/* compiled module information */
zend_module_entry FirstPHPExtModule_module_entry = {
    STANDARD_MODULE_HEADER,
    "FirstPHPExt Module",
    FirstPHPExtModule_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET, STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
ZEND_GET_MODULE(FirstPHPExtModule)

/* DoubleUp function */
/* This method takes 1 parameter, a long value, returns the value multiplied by 2 */
ZEND_FUNCTION(DoubleUp){
    long paramValue = 0;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &paramValue) == FAILURE) {
        RETURN_STRING("Bad parameters!", true);
    }
    paramValue *= 2;
    RETURN_LONG(paramValue);
}

If you compile your project now, you will get the following error:

Error C3163: '_vsnprintf': attributes inconsistent with previous declaration   

Don't be panic, this is a common error in compiling old C/C++ codes in VC++ 2008 (I found it when I compiled Squid and Winpcap with VC++ 2008). In our case, zend_config.w32.h contains a re-definition of snprintf and vsnprintf that already defined in stdio.h. Change zend_config.w32.h then you will not see that error again:

#if not defined(_MSC_VER) || defined(__MINGW32__)
   #define snprintf _snprintf
   #define vsnprintf _vsnprintf
#endif

After the building the project, we get MyPHP-Custom.dll file (depends to Output file configuration) that is ready to deploy.

4. Deploying the Extension

Place the resulted DLL (MyPHP-Custom.dll) to PHP extension directory, in this case  C:\PHP\ext. If want to attach a debugger to this extension, you will also want to copy the .pdb files. After that, please configure PHP to load your extension DLL by modifying PHP.ini file, add  "extension=MyPHP-Custom.dll". Once you’ve edited and saved php.ini, restart your Application Pool in IIS 7.0 then browse index.php web page to test the result. If you do not already have index page, just create one using the following text, and save it to one of your virtual directories:

<?php
      phpinfo();
?>

Now browse the index.php and see that new extension should now be seen in the listing. If you are not lucky enough, please do some troubleshot :).

05 

Then the latest step is to test our extension (calling DoubleUp). Just modify the index.php as below:

 06

I perfectly get the right result in my browser :

07

Great... Now we understand how to build simple PHP extension using VC++ 2008 in Windows Vista. I will cover PHP extension debugging in other part of my article. What is left for the Part 3 of this article is explanation of many Zend functions appear in our codes. I will focus on Zend Framework in the Part 3 of this posting. I hope you will enjoy C++ codes like I did !


Hope this helps !!

Ciao - RAM

Share this post: | | | |
Published Sunday, June 15, 2008 1:41 AM by Risman Adnan Mattotorang

Comments

# Part 1 : Writing PHP Extension - Risman Adnan

Pingback from  Part 1 : Writing PHP Extension - Risman Adnan

Sunday, June 15, 2008 1:53 AM by Part 1 : Writing PHP Extension - Risman Adnan

# re: Part 2 : Writing PHP Extension

Cool...Ternyata bikin extension PHP gak sesulit yang terbayangkan :)

Kayaknya lagi semangat explore PHP nih ya bos?

Monday, June 16, 2008 4:41 AM by andriyadi

# re: Part 2 : Writing PHP Extension

Iya Andri, mau buat PHP Extension for Windows Live. Moga2 bisa jadi juni ini.

Monday, June 16, 2008 6:51 AM by Risman Adnan Mattotorang

# re: Part 2 : Writing PHP Extension

Pak Risman, sy sudah coba bikin extensi .dll untuk PHP, berhasil di komputer sy (tp sy belum coba tutorial yg ini).

tapi ketika saya jalankan di kompie lain yang tidak ada .NeT-nya kok ngga jalan yah?

Kira-kira apa masalahnya dan bagaimana solusinya?

btw, sy juga kompile pakai VC++  2008

Trims.

Monday, June 16, 2008 4:45 PM by CyberJupie

# re: Part 2 : Writing PHP Extension

Maksud kamu DLL extensionnya kamu deploy ditempat lain yang tidak ada .NET nya kan? PHP extension gak ada hubungannya dengan .NET, so harusnya bisa jalan.

Mungkin kamu belum register ke PHP.ini. Coba di cek.

Monday, June 16, 2008 6:00 PM by Risman Adnan Mattotorang

# Part 2 : Writing PHP Extension | PHP Indonesia

Pingback from  Part 2 : Writing PHP Extension | PHP Indonesia

Tuesday, June 17, 2008 10:55 PM by Part 2 : Writing PHP Extension | PHP Indonesia

# re: Part 2 : Writing PHP Extension

php.ini sudah saya cek berkali-kali Pak, kalau di komputer sy muncul, tapi kalau sy deploy di kamputer kantor ngga muncul sama sekali.

Coba deh, pak Risman deploy di komp lain yang ga ada .NET nya

Kayaknya sih dia butuh msvcr90d.dll. tapi dah sy sertakan nggajalan juga :(

Mohon pencerahan, sy sudah letih sekali mengoprek ini.

trims.

Monday, June 23, 2008 8:39 AM by CyberJupie

# re: Part 2 : Writing PHP Extension

@CyberJupie Sepertinya kamu harus install VC++ Runtime deh.

Wednesday, July 02, 2008 5:50 PM by Risman Adnan Mattotorang

# re: Part 2 : Writing PHP Extension

Alhamdulillah, iya pak, sudah bisa sekarang :).

Jazakumullahu khoiron.

Monday, July 07, 2008 12:44 PM by cyberjupie

# Preparing for PHP4Live... from the other side :)

Bos Risman has mentioned creating PHP extensions in Windows for PHP4Live (Live extensions for PHP). I&#39;m

Thursday, July 17, 2008 2:46 AM by BloggiZ - Blogging by Z

# re: Part 2 : Writing PHP Extension

I followed the tutorial, I'm using win xp home, Visual c++ 2008 XE and PHP 5.2.5

I get

1>.\FirstPHPExt.cpp(14) : error C2065: 'ZEND_DEBUG' : undeclared identifier

during the compile process.

Any clue?

I also didn't understand if I need to download SDK or if it's already included in VC++ 2008 XE.

Thanks!

Friday, April 24, 2009 4:18 PM by Eugenio

# re: Part 2 : Writing PHP Extension

ImxlPs  <a href="aldgvxksepbt.com/.../a>, [url=http://nuuhpvgomfso.com/]nuuhpvgomfso[/url], [link=http://thzkeldhmhve.com/]thzkeldhmhve[/link], http://sxvayygniqqb.com/

Tuesday, April 28, 2009 7:58 AM by yaprohpdwuq

# re: Part 2 : Writing PHP Extension

Cool article. Looking around for good articles around on these lines. Thanks a lot

Thursday, May 21, 2009 9:14 PM by St A

# re: Part 2 : Writing PHP Extension

linker commandline:

/FORCE:MULTIPLE

Monday, May 25, 2009 7:36 AM by lenz

# re: Part 2 : Writing PHP Extension

sorry for my bad english, but i have a little question:

Where's my mistake in the following function?

PHP_FUNCTION(tester_manuel)

{

   char *name, *link1;

   int name_len, i;

   if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", &name, &name_len, &link1) == FAILURE) {

       RETURN_STRING("Bad Parameter!", true);

   }

for (i=0;i<name_len;i++){

   php_printf(name,link1);

}

   RETURN_TRUE;

}

Monday, May 25, 2009 7:40 AM by manuel

# Used Reno Sale Suzuki Sx4 Sport, Suzuki Sx4 Exhaust Air Intake

Pingback from  Used Reno Sale Suzuki Sx4 Sport, Suzuki Sx4 Exhaust Air Intake

# Volvo 1800 Review Saint Roger Moore, V1800 Factory Vtx 1300

Pingback from  Volvo 1800 Review Saint Roger Moore, V1800 Factory Vtx 1300

# C7 Light Bulb C10, Ex Fc100 Review Casio Exilim

Pingback from  C7 Light Bulb C10, Ex Fc100 Review Casio Exilim

Friday, May 21, 2010 10:35 AM by C7 Light Bulb C10, Ex Fc100 Review Casio Exilim

# Oakland Intermediate School District Standard 142, 142 Ancient

Pingback from  Oakland Intermediate School District Standard 142, 142 Ancient

# 05 Gmc Sierra Denali Problems, 1999 2500 2000 Gmc Sierra Tailgate

Pingback from  05 Gmc Sierra Denali Problems, 1999 2500 2000 Gmc Sierra Tailgate

# Mercedes Benz 250se Headlight Spark Plug E55 Amg, Listen 250se

Pingback from  Mercedes Benz 250se Headlight Spark Plug E55 Amg, Listen 250se

# Highlander Home Depot Truck, Highlander Boiler Someone

Pingback from  Highlander Home Depot Truck, Highlander Boiler Someone

Saturday, May 22, 2010 7:42 AM by Highlander Home Depot Truck, Highlander Boiler Someone

# Hp Q6000a Refill Toner Cartridge, Part 2002 Gmc Sierra Denali All Wheel Drive Vortec 6000

Pingback from  Hp Q6000a Refill Toner Cartridge, Part 2002 Gmc Sierra Denali All Wheel Drive Vortec 6000

# Sale 2008 Subaru Impreza 2.5 I Photos, Aftermarket Truck Subaru Parts

Pingback from  Sale 2008 Subaru Impreza 2.5 I Photos, Aftermarket Truck Subaru Parts

# New York New Years Party Celebration, Corey Party Brat Max Markson

Pingback from  New York New Years Party Celebration, Corey Party Brat Max Markson

# Honda Prelude Rotors Install, Prelude Hacks

Pingback from  Honda Prelude Rotors Install, Prelude Hacks

Sunday, May 23, 2010 2:32 AM by Honda Prelude Rotors Install, Prelude Hacks

# Foxworth Sale, Aftermarket Fox Auto Parts

Pingback from  Foxworth Sale, Aftermarket Fox Auto Parts

Sunday, May 23, 2010 6:19 AM by Foxworth Sale, Aftermarket Fox Auto Parts

# Wenger Azera, Hyundai Azera Radiator My

Pingback from  Wenger Azera, Hyundai Azera Radiator My

Sunday, May 23, 2010 10:15 AM by Wenger Azera, Hyundai Azera Radiator My

# Celica 2nd Hand Toyota Paseo Fj Cruiser, Map Paseo De Gracia Finest - 6.binggreen.com

Pingback from  Celica 2nd Hand Toyota Paseo Fj Cruiser, Map Paseo De Gracia Finest - 6.binggreen.com

# Pencil Compass Precision, 2009 Jeep Compass Reviews Manual Transmission - 412.dlmreza.net

Pingback from  Pencil Compass Precision, 2009 Jeep Compass Reviews Manual Transmission - 412.dlmreza.net

# 1993 - 1983 @ Headlight Replacement Mazda Mx6, Mx6 Projector Headlights Euro Clear - 138.1fh.org

Pingback from  1993 - 1983 @ Headlight Replacement Mazda Mx6, Mx6 Projector Headlights Euro Clear - 138.1fh.org

# 1985 - 2005 @ 2001 Oldsmobile Bravada Fuel Pump Discount Spark Plug Wires, 1998 Oldsmobile Bravada Buying - 92.rkwrh.com

Pingback from  1985 - 2005 @ 2001 Oldsmobile Bravada Fuel Pump Discount Spark Plug Wires, 1998 Oldsmobile Bravada Buying - 92.rkwrh.com

# Part 1 : Writing PHP Extension &laquo; Enterprise PHP Center

Pingback from  Part 1 : Writing PHP Extension &laquo;  Enterprise PHP Center

Friday, August 20, 2010 1:17 AM by Part 1 : Writing PHP Extension « Enterprise PHP Center