Example #2
From; https://medium.com/@lfoster49203/creating-a-php-extension-with-c-52
6c336e6a79
Creating a PHP Extension with C
PHP is a powerful scripting language widely used for web development. While
PHP offers a rich set of built-in functions, sometimes you may need to
extend its functionality by creating custom extensions in C. This tutorial
will walk you through the process of creating a PHP extension with C, from
setting up your development environment to building a custom extension
with code examples.
Note: To follow this tutorial, you should have a good understanding of PHP
and some knowledge of C programming. You’ll also need a development
environment with PHP and a C compiler installed.
Setting Up the Development Environment:
Before you can start creating a PHP extension in C, you need to set up your
development environment. Follow these steps:
- Install PHP Development Tools: Make sure you have PHP and PHP development
tools installed. On Linux, you can use package managers like apt or yum.
On Windows, consider using WAMP or XAMPP for an easy setup.
- Install a C Compiler: You’ll need a C compiler like GCC (GNU Compiler
Collection). Ensure it’s properly installed on your system.
- Download PHP Source Code: Download the PHP source code corresponding to
the PHP version you intend to create an extension for from the official
PHP website (https://www.php.net/downloads.php).
- Extract the Source Code: Extract the downloaded PHP source code to a
directory of your choice.
- Configure PHP for Compilation: Run the following command inside your PHP
source code directory to configure PHP for compilation:
./configure
- Build PHP: Build PHP using the make command:
make
- Locate the phpize Tool: Use the phpize tool to prepare your extension's
build environment. It's usually located in your PHP source code directory
under ext/.
Creating Custom PHP Functions and Classes in C:
Now that your development environment is set up, let’s create custom PHP
functions and classes in C. Here’s a simple example:
- Create a New Directory for Your Extension: Create a directory for your
extension within the PHP source code directory, typically under ext/. Name
it something meaningful, e.g., myextension.
- Create the Extension’s C File: In your extension directory, create a .c
file, e.g., myextension.c, and define your custom functions and classes.
Here's a basic example:
#include "php.h"
PHP_FUNCTION( hello_world )
{
php_printf( "Hello, world!\n");
}
ZEND_FUNCTION( add_numbers )
{
long num1, num2;
if( zend_parse_parameters( ZEND_NUM_ARGS(), "ll", &num1
, &num2) == FAILURE)
{
return;
}
RETURN_LONG( num1 + num2);
}
const
zend_function_entry myextension_functions[] =
{
PHP_FE( hello_world, NULL)
PHP_FE( add_numbers, NULL)
PHP_FE_END
};
- Create the Configuration File: Create a config.m4 file in your extension
directory to configure the build process. Here's a simple example:
PHP_ARG_ENABLE(myextension, whether to enable My Extension support,
[ --enable-myextension Enable My Extension support])
if test "$PHP_MYEXTENSION" = "yes"; then
AC_DEFINE(HAVE_MYEXTENSION, 1, [Whether you have My Extension])
PHP_NEW_EXTENSION(myextension, myextension.c, $ext_shared)
fi
- Run phpize and Configure: In your extension directory, run phpize and then
configure your extension:
phpize
./configure --enable-myextension
- Build and Install Your Extension: Build your extension with make and
install it with make install.
- Modify php.ini: Add the following line to your php.ini file to enable your
extension:
extension=myextension.so
Memory Management and Zend Engine’s Internals:
When writing PHP extensions in C, it’s crucial to manage memory properly
and understand the Zend Engine’s internals. The Zend Engine
documentation (https://www.php.net/manual/en/internals2.php) is an
excellent resource for this.
Creating an Example Extension:
a. Include the Necessary Header Files and Initialize libcurl: In your
extension’s C code, include the required header files and initialize the
“libcurl” library. Here’s an example:
/*F******************************************************
*
********************************************************/
#include "php.h"
#include <curl/curl.h>
PHP_FUNCTION(fetch_url) {
char *url;
size_t url_len;
if( zend_parse_parameters( ZEND_NUM_ARGS(), "s", &url
, &url_len) == FAILURE)
{
RETURN_NULL();
}
// Initialize libcurl
CURL *curl = curl_easy_init();
if (curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, url);
// Perform the HTTP request
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
php_error_docref(NULL, E_WARNING, "curl_easy_perform() failed:
%s", curl_easy_strerror(res));
}
// Clean up libcurl
curl_easy_cleanup(curl);
}
RETURN_TRUE;
}
const zend_function_entry myextension_functions[] = {
PHP_FE(fetch_url, NULL)
PHP_FE_END
};
In this example, we define a PHP function named fetch_url that accepts a
single string parameter, the URL to fetch. We use the
zend_parse_parameters function to handle parameter parsing and validation.
Inside the function, we initialize "libcurl," set the URL to fetch,
perform the HTTP request, and handle any errors.
b. Compile and Install Your Extension: After defining your PHP function,
you need to compile and install your extension, just like we did
previously. Be sure to follow the same steps for creating the config.m4
file, running phpize, configuring, building, and installing the extension.
c. Using Your Extension in PHP Code: Once your extension is installed, you
can use it in your PHP code. Here’s an example of how to fetch data from
a remote URL using your custom extension:
In this PHP code snippet, we call the fetch_url function from our custom
extension, passing the URL we want to fetch. If the function succeeds in
fetching the data, it returns TRUE, and we print a success message.
Otherwise, we print an error message.
Creating a PHP extension with C allows you to extend PHP’s capabilities
and integrate with external libraries. This tutorial covered the essential
steps, from setting up your development environment to creating custom PHP
functions and classes in C. Remember to handle memory management and refer
to the Zend Engine’s documentation for a deeper understanding of PHP’s
internals. Thanks!
I hope you found this article useful. If so, please consider following me
here and on social media.