Linking PHP with local C++ program - php

I've been looking into this for several hours, but everything I've looked at seems rather daunting. I've been using PHP for all of the simple stuff on my website so far. I'm doing a lot of statistical work, and I would like to have c++ available for the more intense calculations.
The c++ would be running locally on the same Unix machine as PHP.
Something like the following is what I'm at a loss for how to do:
<?php
//c++ program has a counter initialized to 0
//PHP tells c++ to add 5 to the counter. $incremented is 5
$incremented = increment_in_cpp_and_return(5);
//$incremented_again will be 7
$incremented_again = increment_in_cpp_and_return(2);
?>
Of course, I'm running some monte-carlo simulations and traversing really big trees instead of incrementing numbers, but that's not what's holding me back.
C++ just needs to listen for a number and return another number (maybe some stuff in JSON at most). It is important for the c++ to keep track of its variables between calls.
I've done a lot of reading on TCP, socket programming, etc and I'm just a little doubtful that this as complicated as the examples make it out to be. A lot of things have pointed me to this https://beej.us/guide/bgnet/html/multi/clientserver.html#simpleserver
If it really is more than 100 lines of c++, are there some popular libraries, or is there a simple implementation in another language?
Thanks!

If you only want to access your C++ program from PHP (or use PHP as the web frontend for your C++ code), an alternative to communicating over a socket would be to embed the C++ code into PHP as an extension.
There's a fair amount of boilerplate code associated with it, but most of it is generated for you by the ext_skel script (included in the PHP source).
Most information online about writing PHP extensions relates to using C, see Extending PHP with C++? for a couple of gotchas related to using C++ for this.

If your C++ is executeable, you could open it as a program, pass data to it via STDIN and pass the return value back to PHP via STDOUT. See proc_open­Docs.
Your standard C++ library should offer access to STDIN and STDOUT, so you already have what you need.
I'm a little confused about how the c++ keeps its state between calls. Can proc_open be used to pass via STDIN to a c++ program that is continuously running? I'm worried that it starts a new instance of the c++
You might be looking for a Named pipe­Wikipedia, a form of inter-process communication (see as well: What are named pipes?), that is supported by most operating systems. It's simple I/O (FIFO) and similar compared to STDIN and STDOUT. You can keep your executable in memory while the other processes can send data to it.
Another simple way is to use sockets, those are supported by PHP as well and should be with your C/C++. Sockets will work across different machines, so you can run your (memory/CPU intensive?) own executable on a dedicated server that does only the calculation for example. Just looks what suits better in your case, from the comment I read you're looking for interprocess communication.
posix_mkfifo­Docs (including sample PHP code in user-notes)
Sockets Tutorial - a simple tutorial on using sockets for interprocess communication (Linux Howtos)
Introduction to Named Pipes (Linux Journal)
Introduction to Interprocess Communication Using Named Pipes (Sun Developer Network)
(these are just some resources, you naturally can find more with a little research, I think for both named pipes and sockets you should be able to find source-code examples for your case)

You could try:
exec()
You send the data from PHP as arguments for the C++ written program that will be executed and the program will return the output so you can use it in PHP after the C++ program's execution.

I've been using gSOAP for remote procedure calls between C++ and PHP, and if you're using PHP5, the interaction is made very easy; see http://www.php.net/manual/en/class.soapclient.php

Related

How do I run a Python script in PHP without using `exec()`,` system()` ...?

My LAMP server is CentOS 7.4 with Apache 2.4, PHP 5.4, and Python 3.6.
I am new to Python; I migrated from R to Python just now. I need some Python package to do statistics, and then deliver the output to PHP.
I reviewed lots of similar questions. The answers are around exec(), passthru(), system(), and shell_exec(). They are dangerous commands and should not be enabled in PHP.
In the Python official manual, "Integrating Python With Other Languages", mentioned are only two tools, ppython and PHP "Serialize" in Python.
ppython seemed no longer maintained, but that's what I need, just like Rserve when I use R.
I also read this post:
Simple and standard solution is using Socket or Webservice(API)
Now, how do I run a Python script in PHP without using exec(),system()...(maybe socket communication)?
Everything is dangerous (even a fork) if you don't know how to use it. Well, you have several options:
Standard: Running the Python interpreter in PHP with exec() / shell_exec(), etc. Plus there will be a small latency and ability to run Python compiled byte-code, so performance wins here.
Non-standard: If you are concerned a lot about security issues at hand I suggest better to insert Python commands into some batch table and run these regularly with the CRON scheduler. After execution, fetch results with PHP. In this way PHP / Python execution will be de-coupled and you will have a better control on how / when to execute Python scripts.
Non-standard (avoid at all costs): Your mentioned project is moved to Git at php-python. It simply starts a new Python server on port 21230 and waits for Python commands from a PHP scripts. Now, THESE solutions are a most dangerous one, because of the additional opened port in the web server, which is a big headache to administrators and thus highly not recommended.
The last option is to question an assumption that Python is needed at all in web development of PHP. The more different languages in the company IT farm - the harder it will be to maintain all sources and harder to beat time-to-market of new features / bugs fixing. So before considering execution of Python script(s), at first think about re-writing them to plain PHP.
You can do it automatically, but these type of translators are very error-prone and incomplete - for example this one doesn't supports imports. (What the hell? Python without imports is like a bread without a flour). The second option is to learn Python and re-write code at hand into PHP. Or simply get a customer requirements and code these into PHP. Everything that can be done in Python, can be done in PHP too (at least in web development perspective).
Convert your Python script to the Django REST API, and then call it using cURL.

How does PHP works and what is its architecture ?

Guys recently I decided to go back to PHP and do some more complex stuff than a simple log in page. For 3 years I've been programming with Java/JavaEE and have a good understanding of the architecture of of Java Applications. Basically, a virtual machine ( a simple OS process ) that runs compiled code called byte code. a simple Java web server is basically a java application that listens on provided TCP port for Http requests and responds accordingly of course it is more complicated than that but this is its initial work.
Now, what about PHP ? How does it work ? What, in a nutshell, is its architecture.
I googled about this question but in 90% the articles explain how to implement and construct a web application with PHP which is not what I am looking for.
The biggest difference between a Java web server and PHP is that PHP doesn't have its own built-in web server. (Well, newer versions do, but it's supposed to be for testing only, it's not a production ready web server.) PHP itself is basically one executable which reads in a source code file of PHP code and interprets/executes the commands written in that file. That's it. That's PHP's architecture in a nutshell.
That executable supports a default API which the userland PHP code can call, and it's possible to add extensions to provide more APIs. Those extensions are typically written in C and compiled together with the PHP executable at install time. Some extensions can only be added by recompiling PHP with additional flags, others can be compiled against a PHP install and activated via a configuration file after the fact. PHP offers the PEAR and PECL side projects as an effort to standardise and ease such after-the-fact installs. Userland PHP code will often also include additional third party libraries simply written in PHP code. The advantage of C extensions is their execution speed and low-level system access, the advantage of userland code libraries is their trivial inclusion. If you're administering your own PHP install, it's often simple enough to add new PHP extensions; however on the very popular shared-host model there's often a tension between what the host wants to install and what the developer needs.
In practice a web service written in PHP runs on a third party web server, very often Apache, which handles any incoming requests and invokes the PHP interpreter with the given requested PHP source code file as argument, then delivers any output of that process back to the HTTP client. This also means there's no persistent PHP process running at all times with a persistent state, like Java typically does, but each request is handled by starting up and then tearing down a new PHP instance.
While Java simply saves persistent data in memory, data persistence between requests in PHP is handled via a number of methods like memcache, sessions, databases, files etc.; depending on the specific needs of the situation. PHP does have opcode cache addons, which kind of work like Java byte code, simply so PHP doesn't have to repeat the same parse and compile process every single time it's executing the same file.
Do keep in mind that it's entirely feasible to write a persistent PHP program which keeps running just like Java, it's simply not PHP's default modus operandi. Personally I'm quite a fan of writing workers for specific tasks on Gearman or ZMQ which run persistently, and have some ephemeral scripts running on the web server as "frontend" which delegate work to those workers as needed.
If this sounds like a typical PHP app is much more of a glued-together accumulation of several disparate components, you'd be correct. Java is pretty self-contained, except for external products like RDBMS servers. PHP on the other hand often tends to rely on a bunch of third party products; which can work to its advantage in the sense that you can use best-of-breed products for specific tasks, but also requires more overhead of dealing with different systems.
This is how does PHP work:
(one of the best over the Internet)
In general terms, PHP as an engine interprets the content of PHP files (typically *.php, although alternative extensions are used occasionally) into an abstract syntax tree. The PHP engine then processes the translated AST and then returns the result given whatever inputs and processing are required.
Below image will depict more information
Source: freecodecamp.org

How do PHP libraries that interface PHP with database systems actually call the database?

I've been looking through the Predis code on GitHub and it's massive so it's a bit difficult for me figure this out from just looking at the code because I don't understand what each folder/file is for
What I'd like to know is, how does PHP actually contact the database when using MySQL or Redis or any other database system? Does it make system calls similar to how you can do in C with system("some command here"); or does the developer have to actually extend the compiler for the PHP language to do this?
You don't have to "extend the compiler", but you have to do what you probably meant by this: write a PHP module/extension in C that talks to the database's (typically) C library API. What does that mean? A database typically comes with connector libraries that are often written in low level C and thereby offer a C based API. That more or less works like an include 'api.php' which then allows you to call functions of whatever you just included, but it's specific to C. PHP code cannot talk to C code directly, but a PHP extension written in C can act as a "bridge" between PHP code and the C API.
That C library then has many options how it may talk to the actual database. It may talk directly to another C API of the database, though that's not necessarily typical. Often a UNIX socket or TCP socket is used, sometimes across the network if the database is on a different machine. You could be talking directly to that UNIX/TCP socket from your PHP code if you wanted to, but that means you'd have to reimplement the entire protocol to talk to the database in PHP code. That's typically inefficient, since PHP is a rather high level language and doesn't offer any direct access to raw computer resources like memory, which makes this implementation rather inefficient.
So, the way it typically goes is:
the database offers a protocol to talk to it over a socket of some kind
an official protocol client is implemented in a C library, because it's efficient and portable
someone writes a PHP extension to bridge that C library API into PHP userland code
There's nothing stopping you from implementing that protocol in other languages in alternative clients, but since this is often a tedious process and C is a widely used system, people typically end up writing wrappers around the existing official C library.
The functions/classes for interacting with the various databases are provided (like pretty much everything in PHP) by PHP extensions, e.g. the mysqli extension. They are .so files on Linux or .dlls on Windows. Or they can be compiled into PHP when it's built. Either way, they call functions in the Zend code to register the functions/classes that will be called in PHP (e.g. mysqli_connect) and hook them up to code that knows how to interact with the database. PHP and the extensions are written in C. If you look at examples of how to write C code that connects to MySQL, that's probably what the mysqli/mysql extensions in PHP use.

How do you use PHP to interact with a running C++ process?

Is it possible to have a C++ program running on a server that sits and waits to be passed arguments by a PHP process.
The C++ program would then process these arguments and return a result to PHP.
I’ve been searching the web and can see a couple of ways to run a C++ program from PHP but can’t find a way to interact with a C++ program that is already running.
The sort of C++ programs I’m thinking of are ones that might take time to set up e.g. They create a big data structure of some kind and so I don’t want to run them every time I need them. I want the C++ programs to create their data structures and then sit back and wait until asked by PHP for information from that data structure.
Thanks
Use named pipes.
https://web.archive.org/web/20140223054156/http://my.opera.com/zomg/blog/2007/08/29/php-and-named-pipes
and
C++ https://web.archive.org/web/20110926155246/http://ist.marshall.edu/ist480acp/namedpipes.html
Write a C++ listener that recognizes XML RPC or SOAP requests so it can process the requests natively and return the results to PHP as an XML RPC or SOAP response.
Here are some references:
http://xmlrpc-c.sourceforge.net/
http://www.cs.fsu.edu/~engelen/soap.html
Would something like SWIG be of use to you? (http://www.swig.org/Doc1.3/Php.html) You could wrap the functionality you want to use, to expose it to your PHP code.

PHP complex uses - Interact with external devices

Is it possible to access & control external devices in PHP?
For example, would it be capable of changing the speed of a USB fan or change the direction of a wireless toy car.
I'm trying to go beyond web dev and I'm wondering if the programming language I use is capable of handling my ideas or should I consider changing the environment.
If these would be possible, I'd very much appreciate any pointers to reading materials or suggestions on other languages that might be more suitable.
Thanks!
On Linux it surely is possible by accessing /dev/ files. But it'll be very tedious. I'd recommend you switching to Python, Ruby, Lua or Java.
For example there are bindings for libusb for Python, Ruby, Lua and Java.
You could write an external program, then use PHP's exec (or was it system?) function to interact with the executable or script.
Seems like the most sane way to do it. Another good alternative is to build a program or script that controls an external device that can communicate with a RESTfull type API exposed via HTTP - and then use lib_curl in PHP land to talk back and forth between it. Believe me, building a basic HTTP server in C++ that can be used to be remote controlled with PHP (or JS for that matter) is very simple.
Wait
I think I read the question wrong ;)
If you want to get into really cool stuff, I say that you learn C++. C++ is a great language that not only opens a lot of doors, but also provides a good learning experience. C++ is lots and lots of fun.
In response to comment
In the case with USB its a bit different and more complicated (as USB has an established protocol and such) but serial is as easy as dumping data into a handle.
You should be able to pick up C++ to get to that point fairly soon. Either way it's a great experience.
This would be possible with a extension, but not with pure PHP code. I don't know of any extensions being able to do something like this, but I think it should be possible.
If you find a command line tool that does this, then you can control it using exec(), system(), passthru() or shell_exec() (based on what output the program gives you back)
Just be sure to escapeshellcmd() if you give access to this program from a public website.

Categories