27

We have a PHP web app running on a customer's machine. For an update, we have a bit of code in C that we'd like to include as a native opaque library along with the PHP web app.

How does one go about calling a C/C++ lib. function from PHP?

It cannot be assumed that the PHP app, called by the web server, has any sort of permission to call an exec(), eval(), or system() type of function to execute a C wrapper driver which in turn uses the C/C++ library, so it would need to be a direct C library use from within the PHP code.

5 Answers5

24

Take a look at some of the Zend tutorials on Extension writing, this one in particular "Wrapping C++ Classes in a PHP Extension"

yushulx
  • 11,695
  • 8
  • 37
  • 64
St. John Johnson
  • 6,590
  • 7
  • 35
  • 56
  • 3
    Linkrot : "Wrapping C++ Classes in a PHP Extension"... but this approaches the subject : https://www.php.net/manual/en/internals2.ze1.zendapi.php – MountainMan Feb 02 '20 at 07:30
  • Well, that one has also linkrotted. It also appears to be about PHP 4 ? https://php-legacy-docs.zend.com/manual/php5/en/internals2.ze1.zendapi – Henk Poley Aug 17 '21 at 11:53
10

The answer by St. John Johnson is correct. But you can now also us the php-cpp library. It offers a much easier bridge between PHP and C++. See http://www.php-cpp.com for more information.

4

Another option is to have the C code as a daemon, always running, and the php script connect to it throught unix domain sockets or some existing library to exchange data.

More info here

Community
  • 1
  • 1
Bernardo Ramos
  • 4,048
  • 30
  • 28
3

You can compile your code and use system, shell_exec or passthru functions to handle the output. Most web hosts allow you to compile c++ code, just ssh to your server, upload the code and compile it.

DUNBlend
  • 31
  • 1
1

You can use ZEND to plug your C code into PHP.

http://php.net/manual/en/internals2.ze1.zendapi.php

Ankit Marothi
  • 955
  • 10
  • 14