Execute C scripts using PHP - php

I need to run a c program in PHP to establish a socket connection and to retrieve a result back from the server.
I have written a C Program to establish a socket connection and server receives the request.
How to convert a C program into .dll file to use as a PHP extension?

Using socket you can't run any c application directly .You need to call that executable to run .
My idea is you can run another client application on remote and send some data to socket and in remote the client will receive the message based on which it can run he application.

Method 1:
You can receive the file sent from client and save it to disk.
Then, you may use system to compile the file received.
The last step, you run it, use the system again.
But i am not suggest you do that, as it may be dangerous, you never know what the code does. It may deletes all your files in the disk. What's more, the libs the code depend on may not be installed.
Method2:
use the loadable library:
1. all the code sent to server is implement a generic interface
2. pre-compile the code to loadable library
2. server save the code to disk
3. server load the library and call the generic interface
More about loadable library, please check it out.

We can not run a C Program directly with PHP, Because to run a C script there is no compiler with any LAMPP, XAMPP, WAMP. If we need to run any C script, Create a PHP Extension with C code with ZEND Engine standards(Check the syntax to receive the parameters in C from PHP).
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls|b", &intNumber, &strVal, &return_long) == FAILURE) {
RETURN_NULL();
}
WINDOWS:
Refer this link to create a PHP Extension with C Scripts:
http://www.dreamincode.net/forums/topic/244215-introduction-to-creating-a-php-extension-for-windows/
Move the extension file to /ext/ folder and add the extension name in php.ini file
LINUX:
http://linux.ferhatbingol.com/2013/06/06/how-to-create-php-extensions/
In a linux, by default .so file will move to /usr/lib/php5/ XXXXXXXX/extension.so
, Specify this extension path in your PHP.ini file
Then restart the apache server, finally our PHP Extension will work fine.

Related

Where's the php-src/PHP-Internals Main Entry Point

What function or bit of code serves as the main entry point for executing/interpreting a PHP program in the source of PHP itself? Based on things I've googled or read in books, I know that PHP is designed to work with a server of some kind (even the CLI command works by starting up "the command line SAPI", which acts as a mini-server designed to process a single request), and that the server will ask PHP to execute a program.
I know about the minit and rinit lifecycle functions, which serve as entry points for a PHP extension.
What I don't know is where does the PHP source code have this conversation with itself
Hey look, there's a PHP program in this file/string. I ought to run it
I'm not trying to accomplish any specific task here. I'm trying to understand how the internals of PHP does what it does, and find a main entry point where I can start following its execution.
Where is the entry point of the code of some SAPI?
The CLI is a standalone application. As any other application written in C, its entry point is the function main() (file sapi/cli/php_cli.c, line 1200):
int main(int argc, char *argv[])
There are two versions of the CLI for Windows, one of them is a console application and starts with the main() function described above, the other is a Windows GUI application (it doesn't create a console when it starts and uses message boxes for output) that starts with the WinMain() function (file sapi/cli/php_cli.c, line 1198).
main() and WinMain() use the same code here. They have different name and different code fragments here and there by checking if the symbol PHP_CLI_WIN32_NO_CONSOLE is defined. It is defined in file sapi/cli/cli_win32.c that is used to generate the Windows GUI application.
</Windows>
The CGI version is also a standalone console application. Its entry point is also the main() function in file sapi/cgi/cgi_main.c, line 1792.
Similar, the FPM version starts with main() in file sapi/fpm/fpm/fpm_main.c, line 1570.
Apache2 handler is a dynamically loadable module (.dll on Windows, .so on Unix-like systems). It registers some functions as event handlers for the events published by the web server (server start, pre/post configuration loaded, process request etc). These handlers are registered by the php_ap2_register_hook() function in file sapi/apache2handler/sapi_apache2.c, line 738.
(You can find details about how a loadable module integrates with Apache in the Apache documentation.)
The handler that is interesting to us is the function php_handler() that is invoked to handle a HTTP request.
In a similar manner, every SAPI has an entry point (either main() or a function that is invoked by the web server).
All these entry points do similar processing:
initialize themselves;
parse the command line arguments (only if it's CLI, CGI or other kind of standalone application);
read php.ini and/or other configuration they have (the Apache module configuration can be overridden in .htaccess);
create a stream using the input file and pass it to the function php_execute_script() defined in file main/main.c, line 2496;
cleanup and return an exit code to the calling process (the shell or the web server).
Where is the code that actually executes a PHP script?
The function php_execute_script() is a wrapper; it interprets the php.ini configuration entries auto_prepend_file and auto_append_file, prepares the list of files (auto-prepend file, main script, auto-append file) and passes the list to zend_execute_scripts() that processes them.
php_execute_script() is not always invoked, some SAPIs and command line arguments of the CLI produce the direct invocation of zend_execute_scripts().
zend_execute_scripts() is where the interesting things happen.
It compiles the PHP file (and returns a list of OP codes in op_array then, if the compilation succeeds (the returned op_array is not NULL) it executes the OP-codes. There is also exception handling and cleanup; boring work but as important as the parsing and executions nevertheless.
The compilation is a tedious process. It is done by the function zendparse() defined in the file Zend/zend_language_parser.c. The definition of the zendparse() function and the file Zend/zend_language_parser.c are nowhere to be seen in the Git repo; the parser is generated using bison and re2c that read the language syntax rules and the definition of lexical tokens from Zend/zend_language_parser.y and Zend/zend_language_scanner.l and generate the actual compiler in file Zend/zend_language_parser.c.
However, even if the hard work is not visible in the repo, the interesting parts of the compilation process are visible in the files mentioned above.
The execution of the compiled script (the list of OP codes) is done by function zend_execute() that is defined in the file Zend/zend_vm_execute.h. This is also a generated file and the interesting part is that it is generated by a PHP script.
The generator script (Zend/zend_vm_gen.php) uses zend_vm_def.h and zend_vm_execute.skl to generate zend_vm_execute.h and zend_vm_opcodes.h.
zend_vm_def.h contains the actual interpreter code that is executes to handle each OP code.
Where is the code of some function provided by the PHP core or one of its bundled extensions?
The code of the PHP functions and functions provided by extensions is somehow easier to follow. The functions included in the PHP core are located in files in the ext/standard directory, the functions provided by other extensions are located in files in the corresponding ext subdirectories.
In these files, the C functions that implement PHP functions are declared using the PHP_FUNCTION() macro. For example, the implementation of the PHP function strpos()
starts in file ext/standard/string.c, line 1948. The function strchr() being an alias of strstr() is declared using the PHP_FALIAS() macro in file ext/standard/basic_functions.c on line 2833.
And so on, and so forth.

Check if a php script is executed in fpm environment [duplicate]

I use shared hosting.
There is possible to find out whether PHP is running via fastCGI (or maybe CGI) or as Apache module mod_php?
Is it possibly to find out by myself, without asking the hoster?
That's the Server API row on top of phpinfo()'s output:
However, please note that it won't necessarily tell you the exact version of Apache or the exact CGI handler. It just describes the SAPI in use.
You can also call the php_sapi_name() function (or the PHP_SAPI constant, which provides the same info):
Description
string php_sapi_name ( void )
Returns a lowercase string that describes the type of interface (the
Server API, SAPI) that PHP is using. For example, in CLI PHP this
string will be "cli" whereas with Apache it may have several different
values depending on the exact SAPI used
It's still a good idea to check your HSP's documentation because it possible to have several PHP versions available.
Remember you need to run phpinfo() from the same environment you want to check (web server won't tell you about command line and vice-versa):
C:\>php -i | findstr /C:"Server API"
Server API => Command Line Interface
$ php -i | grep 'Server API'
Server API => Command Line Interface
You can use the link below:
How to determine php is running as php cgi or apache module?
or create a file info.php and type
<?php
phpinfo();
?>
now run file with your domain name.
find Server API on file and it show you PHP is running on server with CGI OR Apache
Security consideration: Make sure to delete the file which outputs phpinfo() especially if the website is or is going to be hosted online. The information shown there is a gold mine for hackers.

Compile PHP code including cURL commands to exe file

Is it possible to create Windows exe file from PHP source which include cURLcommands?
I want to create a portable program which works even on machines where PHP or cURL are not installed.
Actually I don't expect that it is possible to create just one executable file which don't need additional libraries. Even full cURL tools can be attached if it is needed.
Maybe I just want some way to join it after.
When I use some php to exe compiler like Phalanger etc, the compilation is successful but when I run the file it throws an error:
Error: Call to undefined function: 'curl_init' in C:\Users\Pavel\Desktop\comm\comments.php on line 6, column 1.

Find out how PHP is running on server (CGI OR fastCGI OR mod_php)

I use shared hosting.
There is possible to find out whether PHP is running via fastCGI (or maybe CGI) or as Apache module mod_php?
Is it possibly to find out by myself, without asking the hoster?
That's the Server API row on top of phpinfo()'s output:
However, please note that it won't necessarily tell you the exact version of Apache or the exact CGI handler. It just describes the SAPI in use.
You can also call the php_sapi_name() function (or the PHP_SAPI constant, which provides the same info):
Description
string php_sapi_name ( void )
Returns a lowercase string that describes the type of interface (the
Server API, SAPI) that PHP is using. For example, in CLI PHP this
string will be "cli" whereas with Apache it may have several different
values depending on the exact SAPI used
It's still a good idea to check your HSP's documentation because it possible to have several PHP versions available.
Remember you need to run phpinfo() from the same environment you want to check (web server won't tell you about command line and vice-versa):
C:\>php -i | findstr /C:"Server API"
Server API => Command Line Interface
$ php -i | grep 'Server API'
Server API => Command Line Interface
You can use the link below:
How to determine php is running as php cgi or apache module?
or create a file info.php and type
<?php
phpinfo();
?>
now run file with your domain name.
find Server API on file and it show you PHP is running on server with CGI OR Apache
Security consideration: Make sure to delete the file which outputs phpinfo() especially if the website is or is going to be hosted online. The information shown there is a gold mine for hackers.

Run PHP script in background on Apache start/restart(Windows Server)

I've installed Apache 2.4 with PHP 5.4 on Windows Server 2008 following instructions from this manual:
Apache installing manual.
Apache runs as a service now.
My application requires a php websocket script to run in the background. I'm running it manually with:
php myscript.php
The question is: Is there a way to start a background script automatically on system(apache) restart?
I found the following topic, but I didn't know where I could find an apache startup script for Windows.
Any help will be much appriciated.
I come up with a solution :)
Create an environment variable pointing to your Apache directory
APACHE_HOME = C:/PATH/TO_APACHE
Rename %APACHE_HOME%\bin\httpd.exe to %APACHE_HOME%\bin\httpdVendor.exe
Create a batch file and put the following code :
php myscript.php
%APACHE_HOME%\bin\httpdVendor.exe -k runservice
exit 0
Download/Install the free software BatToExeConverter (next, next, ...)
Open the installed converter and open your freshly created batch file
Click on the button Build EXE (let the default configuration)
Save the file : %APACHE_HOME%\bin\httpd.exe
Start your Apache Server
Tested on : Windows 7, Apache 2.4, Advanced Bat to Exe Converter 2.92
Use built in Windows Task Scheduler which triggers .bat script, which calls curl with defined url.
Download curl from http://curl.haxx.se/download.html and extract curl.exe on any directory, but we will use c:\backgroundtasks
Adjust script below to your needs:
cd c:\
cd c:\backgroundtasks
curl http://localhost/path/to/script.php
exit
Configure Task Scheduler to run as basic task:
General tab - as system account (to run when you are not logged in server)
Triggers tab - adjust frequency
Settings tab - at bottom set If the task is already running... to Stop the existing instance
The best method here would be to use Windows services dependencies.
Make a php-websocket-server.cmd file with any necessary environment settings (e.g. changing to a directory, setting PATH, etc...) with the last line:
php myscript.php
Install the Windows Server Resource Kit Tools, to get srvany and instsrv to create a user defined service. Note the install path as you'll need it in the next step.
Open a cmd shell and run:
<path_to_resource_kit>\instsrv PHPWebSocketServer <path_to_resource_kit>\srvany.exe
Next, create a file php-websocket-server.reg containing the following (update for your environment):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PHPWebSocketServer\Parameters]
"Application"="c:\\path\\to\\php-websocket-server.cmd"
Import it by double-clicking or regedit /s php-websocket-server.reg
Back in your cmd shell:
sc config Apache2.4 depend= PHPWebSocketServer
to make the Apache2.4* service depend on your php service. Now, when Apache is started, the php service will be brought up first. And likewise, if you stop the php service Apache will stop along with it.
*the howto indicates that the service is named "Apache2.4" but you may want to verify in your installation.
When running as service, you won't have the startup script.
Execute some service implementation that allows running other programs as services, and then make the new service (which is running your script) a dependency of the Apache service. However, this will not restart the script when apache restarts.
One possible solution using SrvStart, and another using ServiceEx.
Perhaps don't install Apache as a service, and then edit the startup/restart script, and use the above method to run Apache as service (instead of using Apache's own installer).
Create bat file,e eg 'myphp.bat' containing path/php myscript.php. Include the correct path to php if it's not path'd.
create a bat file, eg runmyphp.bat containing
AT 00:00 /every:M,T,W,Th,F "cmd /c /path/myphp.bat", again including the correct path.
Then use explorer to drag runmyphp into the startup folder, so it will always run on system startup.
Google 'windows at command' or 'windows cron' to get all the correct syntax for the 'at' command, but you can currently find a detailed explanation here.
I found another answer C:\wamp\scripts\wampserver.lib.php this file is run every time when your wamp starts
include your file path include_once("file_path"); to this file and its done . this is perfect solution which you want
Enjoy!!!!!!!!!
Although the solution of Halayem Anis is very creative, I think its important to note that you can never be sure that a PHP script keeps running in the background. So if you choose to start your script on "Apache start", then you probably end op resetting Apache quite often, simple to reboot your script.
I assume that's even how you came to this question, as on a normal server you never have to touch the Apache reset button. It starts on system start and then it just runs. If that was the case, you could simple run your php myscript.php command on start up.
Considering there is no way to make sure the script keeps running, I would use a different approach, where I check if it is running and if not, restart it.
So the first step is to make it possible to track if the script is running. I would go for the simple approach where your myscript.php writes a single byte to a file every 5seconds or so. This way I can use the last modified time on the file to see if it is still running, because last modified time + 5 seconds < now == not running.
You could also store the last access time in a database every 5 seconds or so. Might be slightly faster then accessing files if you have a lot of traffic.
The second part is to have each request check if the script is running. For this two work I would use the PHP.ini to prepend a php script on every request. You can do it with the auto_append_file option.
This prepend script would work like this:
<?php
$filename = 'checkonline.txt';
$cmd = "php myscript.php";
if (filemtime($filename)+5<time()) {
//run in background without freezing php
//based on code posted on PHP exec manual, linked below
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
?>
Make sure to check how filemtime and exec work and what you need to keep in mind. They work slightly different on Windows/*nix.
Wrap-up all your required processes in a batch file and use RunAsService
With some tweaking, you can ensure that your service starts before Apache.

Categories