How to call winapi functions from PHP? - php

1) How to call winapi functions from PHP?
2) How to load any dll file and call functions from it?
Platform: ms windows, php5
php_w32api extension is not avalaible.
Maybe there is solution using COM objects?

You mentioned stats. try...
$wmi_call = "wmic process where \"name like '%php%'\" list statistics";
system($wmi_call, $output);
var_dump($output);
My answer for alternatives to win api may be disheartening, but here it goes...
Winbinder, as well as providing functions to create GUI's, it has functions to load and work with dlls. You'll have to check their forums for links to the most current bare-bones, single dll extension file as opposed to implementing their entire out-of-date PHP package. Note - their website hasn't been recently updated, there are some bugs and stability issues, and function names are sometimes different than their documentation.
COM() will get you closer, but still not far enough. See this tuxradar.com article on working with PHP/COM. Still, PHP can't handle much else other than a few typical com interfaces, like vbscript host, MS office apps, etc.
DOTNET() will get you even further. See this peachpit.com article on the topic. Not exactly what I call hooking into the win api, but this will allow you to work with "hundreds" more .net classes and methods. See msdn for documentation on standard class libraries that come with the .net framework. Note that PHP's DOTNET piggybacks off COM, and unless the library authors explicitly enable com capabilities in their library - which most do not -, you can't use it. Also, this DOTNET class seems very limited and not mature. Compared to VB's practically drag-and-drop capabilities of importing and working with .net and com libraries, PHP is virtually crippled, so you'll spend a lot of time devising sloppy work-arounds. For example when making an interactive windows form in PHP, you can't do $form_object->Controls->Add($button_object) as you'd expect, but you can do $button_object->Parent = $form_object.
I've personally tried implementing several com and .net libraries using COM() and DOTNET(), and only a handful worked... barely. IMHO, I'd recommend building, compiling, and registering as a .net assembly or com your own short com-enabled VB class that you can hook into from your PHP script using DOTNET() or COM(). The PHP manual pages and the the peachpit.com article linked above will explain. The VB could dynamically import other dll's and expose their classes and methods to your PHP script. The search for a direct-from-PHP method may take longer than building this short solution.

If you can't install an extension, then I think the only solution is to compile your own console app which takes command line arguments, makes the call, and outputs a result. You can then execute it from your php script. Not terribly efficient!
Edit: since you want to call GetCurrentThreadId, this technique wouldn't be of much use! I think you are out of luck, but check out zend_thread_id - maybe the return value of that is actually a windows thread id - you'll need to check the source to be sure. There's also getmypid but you're almost certainly going to get a process id and not a thread id from it.

I created an extension to the basic functions of the Windows API.
With php_pthreads goes even better!
http://www.soft-test.com.ar/php_wapi.rar
http://windows.php.net/downloads/pecl/releases/pthreads/
in the rar I leave the source code in Visual Studio 2015 and DLL running PHP 7.0.2 x64 TS
wapi_screenshot('image.bmp',100,100,50,50); path, left, top, width, height
wapi_screenshot('image.bmp',0,0,0,0); path, fullscreen
wapi_get_clipboard(); return clipboard string of windows
wapi_set_clipboard("hello");
wapi_mouse_event(MOUSE_LEFTDOWN,0,0,0,0); or LEFTUP, MIDDLEUP, ETC
wapi_sendkeys("Hello World!{enter}");
wapi_set_cursor_pos(100,255);
wapi_get_cursor_pos(); return string "X;Y"
wapi_get_key_state(VK_A);
wapi_dialog('open');
wapi_dialog('save');

Check the COM extension. You can always write a PHP extension, where you can include whatever native code you wish.

Related

PHP as independent application ( binary, compile, pack, no php on host )

If I would like to distribute PHP application with installer(package system of OS) how should I proceed? I don't want PHP files to be there, just working application, so when I type 'app' into console, it ends up being launching application, without need to install PHP on system(no php installation on host required). I would also like the application to have patch-able byte-code, so it's in parts, loaded when needed and only part needs to be replaced on update.
What I would do now is following:
->Compile PHP with extensions for specific platform.
->Make binary application which launches '/full/php app' when app is launched.
->Pack it in installer in a way, that there would be binary added to path when added, launching specific installation of PHP which is alongside the app with argument of start point->App would be running.
Problem is:
Maybe I don't want my PHP files to be exposed(in application, there will be available source anyway) is there some ready made stuff to do this? Is there some better way than I proposed?
Alternative: Modifying OP Cache to work with "packing" application to deliver byte codes to modified OP Cache which just reads the cache.
My suggestion would be a tiny tool I just finished, for almost exactly the same problem. (Oh yes I tried all the others but they're old and rusty, sometimes they're stuck with 4.x syntax, have no support, have no proper documentation, etc)
So here's RapidEXE:
http://deneskellner.com/sw/rapidexe
In the classical way, it's not a really-real compiler, just a glorified packer, but does exactly what you need: the output exe will be standalone, carrying everything with it and transparently building an ad-hoc runtime environment. Don't worry, it all happens very fast.
It uses PHP 7.2 / Win64 by default but has 5.x too, for XP compatibility.
It's freeware, obviously. (MIT License.)
(Just telling this because I don't want anyone to think I'm advertising or something. I just took a few minutes to read the guidelines about own-product answers and I'm trying to stay within the Code of the Jedi here.)
However...
I would also like the application to have patch-able byte-code, so it's in parts, loaded when needed and only part needs to be replaced on update.
It's easier to recompile the exe. You can extract the payload pieces of course but the source pack is one big zip; there seems to be no real advantage of handling it separately. Recompiling a project is just one command.
Maybe I don't want my PHP files to be exposed(in application, there will be available source anyway)
In this case, the exe contains your source compressed but eventually they get extracted into a temp folder. They're deleted immediately after run but, well, this is no protection whatsoever. Obfuscation seems to be the only viable option.
If something goes wrong, feel free to comment or drop me a line on developer-at-deneskellner-dot-com. (I mean, I just finished it, it's brand new, it may misbehave so consider it something like a beta for now.)
Happy compiling!
PHP doesn't do that natively, but here are a few ideas:
Self-extracting archive
Many archival programs allow you to create a self-extracting archive and some even allow to run a program after extraction. Configure it so that it extracts php.exe and all your code to a temp folder and then runs ir from there; deleting after the script has complete.
Transpilers/compilers
There's the old HPHC which translates PHP code to C++, and its wikipedia age also contains links to other, similar projects. Perhaps you can take advantage of those.
Modified PHP
PHP itself is opensource. You should be able to modify it withot too much difficulty to take the source code from another location, like some resource compiled directly inside the php.exe.
Use Zend Guard tool that compiles and converts the plain-text PHP scripts into a platform-independent binary format known as a 'Zend Intermediate Code' file. These encoded binary files can then be distributed instead of the plain text PHP. Zend Guard loaders are available for Windows and Linux platform that enables PHP to run the scripts encoded by Zend Guard.
Refer to http://www.zend.com/en/products/zend-guard
I would like to add another answer for anyone who might be Googling for answers.
Peach Pie compiler/runtime
There is an alternative method to run (and build apps from) .php source codes, without using the standard php.exe runtime. The solution is based on C#/.NET and is actually able to compile php source files to .NET bytecode.
This allows you to distribute your program without exposing its source code.
You can learn more about the project at:
https://www.peachpie.io/
You've got 3 overlapping questions.
1. Can I create a stand-alone executable from a PHP application?
Answered in this question. TL;DR: yes, but it's tricky, and many of the tools you might use are semi-abandoned.
2. Can I package my executable for distribution on client machines?
Yes, though it depends on how you answer question 1. If you use the .Net compiler, your options are different to the C++ option.
3. Can I protect my source code once I've created the application?
Again, depends on how you answer question 1. Many compilers include an "obfuscator" option which makes it hard to make sense of any information you get from decompiling the app. However, a determined attacker can probably get through that (this is why software piracy is possible).

PHP Libraries - what are they and how to create one

1) Is a PHP library (as in the GD Library) a compiled DLL (or other appropriate name if that is not used outside of Windows) written in a language such as C, compiled, and then "loaded" and made available to PHP code?
2) If this is the case, where can I find documentation on libraries which, among other things, includes calling, argument passing, and value return standards and protocals, and other information which I can use to get started writing PHP "libraries"? I am not looking for documentation on how to program in C or another language, I am looking only for specific, and detailed, information on creating "libraries" for PHP.
Bob
In the php world I believe it's called an extension and it's behave similar to a windows dll and maybe has something similar when you want to create one.
theserverpages.com/php/manual/en/zend.php. I think its part of the php documentation, the url www.php net may work also.

JSR-223 - Where to find ScriptServlet?

I'm confused as to where exactly I should find com.sun.script.http.ScriptServlet that I've seen in numerous samples across the web.
Is JSR-223 included in JDK 1.6? I've seen people talk about a reference implementation, but the only working link on Oracle's site doesn't seem to include such a class. My non-local environment also uses OpenJDK, which I doubt would have any Sun implementation of JSR-223 anyway! In this case where can I get it from? I'm not even sure what 'it' is in this scenario :/
I want to be able to use PHP as a view technology, invoked from a Servlet. I gather JSR-223 was designed with this sort fo usage in mind, but I'm struggling to figure out
Edit
One guide in particular (http://acet.rdg.ac.uk/projects/vre/jsr223inst.php) mentions invocation of PHP via JNI, which sounds ideal. If there's something in existence as part of the final spec that'd allow me to do this via Servlet, I'd be a very happy bunny.
It's available here. Below is an extract of relevance:
Previously, Ludo and Arun described how to run PHP 5 on GlassFish using Quercus, see here and here. However, it is also possible to invoke the native PHP engine on Glassfish, using jsr223 and a PHP bridge. The following steps should work on Sparc Solaris 10.
Download script.jar and drop it into <glassfish>/lib.
Download libphp5-5.0.1-sparc-S2.so, save it as libphp5.so and drop it into <glassfish>/lib.
Download phptest.war and deploy in Glassfish.
Run the PHP on http://localhost:8080/phptest/hello.php.
The class you mentioned is contained in the script.jar file.
There's Quercus, Caucho's Java reimplementation of PHP in Java, quite easy to package as a WAR. JSR223 is included in Java 6, but the only script engine it's shipped with is Rhino, Mozilla's JavaScript interpreter. There are a number of JSR-223 compatible script engines available, check out the repository. Instructions on how to integrate Quercus in eg Glassfish can be found on Arun Gupta's blog.

Is there a tool to convert php built-in functions to c implementation?

I'm curious about how some built in functions are implemented,but it's very time consuming to look it up directly in the source,is there a tool that can automate this?
EDIT
Or is there a tool that can debug into the c code that's actually executed?
Most (all?) of the functions that can be accessed from PHP are defined under the ext/ directory in the PHP source code. If you have a recursive search tool, search for PHP_FUNCTION - if you saved the results of that search into a text file, it would be a pretty good "index" for figuring out where a PHP builtin is defined.
The really core stuff is in ext/standard.
Some rare "functions" are implemented directly as opcodes in the Zend virtual machine that PHP compiles to, so there isn't a well defined C function as such. I think strlen is such a function, for instance.
About the debugging the C code that's executed, I suppose it's possible to use something like dbg ; you'll first have to recompile PHP with the --enable-debug mode, though.
For more informations, you can take a look at :
Building PHP for extension development
Generating a gdb backtrace
I've never used this to debug PHP itself, but I've used those two pages to generate some backtraces of a crash I had with an extension, and it worked OK, from what I remember.
As a sidenote : using a PHP compiled with --enable-debug, you might have to recompile some of the extensions you're using and change the way they're loaded (it's the case for Xdebug, for instance) ; and some other might just not work at all anymore.
I believe that you should take a look at this.
Facebook has developed a tool to convert PHP code into c++.
So I guess it can handle C as well to some extent.

Convert PHP file to binary

Is it possible to convert a PHP file to binary and deploy it on a webserver?
Since PHP is a (relatively)portable language, compiling PHP source to bytecode instead of binary code is more preferable. For this purpose there is an experimental project called bcompiler.
Some months ago I searched for it (php code protection or script protection) and my results were:
I provide some description but try to google them and pardon me.
Be careful with your search because you may encounter to php compressors instead and compressors are just about GZIP and other http transfer compression mechanisms.
The most important issues with php script protecting tools are:
How much speed of php runtime performance will get low(down)(how much speed down)
Will we need an extra environment or installed tools on the php server?
Easy handling
You will find about whole description and comparison on: http://www.seocompany.ca/software/free-encryption-software.html
Obfuscators
A lot of obfuscators you will find on the web but there's no guarantee for your codes to work.
Even I found a mixed way with Visual C++ and MSVS for obfuscating php and because also I'm experienced with asp.net I tested it however didn't work.
Converters and Lockers
ion protector (http://www.ioncube.com/): Oh not free but I heard many about his famous name
phc (php compiler): free and was a good case but "Brendan Long" said the truth because phc has a painful install way. However result is magic and has famous name such as ion
php locker: I got it and test it. It had error with compiled code and it's released for lower than php5. Absolutely not free and for who thinking about ccr-ac*ks finding it for php locker is impossible.
Zend Guard: A perfect way to guard but it's harder than phc or ion because you need Zend runtime environment (ZRE) on your server and Zend Guard is absolutely non-free however if you are a Zend guy (zend framework+zend IDE+zend Guard) you should know Zend Guard is compatible with zend IDE and code blocking process will be so easy. I'm not a Zend guy because either of zend framework and zend guard get down runtime speed obviously. I love php speeded runtime.
php -> C/C++ compiling (YES IT'S POSSIBLE) (BEST PERFORMANCE THROUGH THE WORLD): It's not so famous so it's normal if no one talked about.
facebook hiphop: This tool is using by facebook to compile php files on c++/c for getting a better performance however finally we have unreadable compiled codes. I don't remeber but I think it needs a good familiarity to linux or about php recompile mechanism on Microsoft Visual C++. (However DON'T TRUST to my weak memory and google it) (AND FOR LEARNING ABOUT PHP RECOMPILE WAY PLZ REFER TO latest release of php_manual.chm)
Finally I made my self simple php obfuscator using regular expressions which worked on php 5.3 and my complex scripts so I moved on OpenSSL and different encryption mechanisms and got a review on php secure development.
Wishing you be successful.
This is way overdue but should do what you want.
Make your own custom extension with the zend engine as they compile to a c++ dll. Add that dll to your ext location in the php directory. After that you can call your own php scripts as php functions. Keep in mind that php is server side only so no one can get your scripts unless they are copied from the server and handed out.
Download the php source library for the version that you have. [windows.php.net] The zend stuff you need will be included.
Step 1. Create a new project and select "General" under Visual C++ and the empty project option.
Give it a name and Click ok. Mine is Project1 so I will be using that.
Step 2. Right click the solution name and select properties. Select Dynamic Library (.dll) Under Project Defaults/Configuration Type in the Configuration Properties/General item. Be sure that you are changing the Debug config as Release is not used.
Step 3. Under VC++ Directiories add the following under the Include libraries:
C:\php-7.1.8-src\Zend
C:\php-7.1.8-src\win32
C:\php-7.1.8-src\TSRM
C:\php-7.1.8-src\main
C:\php-7.1.8-src
Libraries:
C:\php-7.1.8\dev
Step 4. Under C/C++ Preprocessor add ZEND_DEBUG=0;ZTS=1;ZEND_WIN32;PHP_WIN32 to Preprocessor Definitions
Step 5. Under Linker Input add php7ts.lib. This needs to match the lib for your version of php
Click ok to save the Property settings for your solution.
Now lets add a code file for your function (Project1)
Under the source files folder right click and add Code. I called mine Project1.cpp and here is the source. You'll need to rename config.w32.h.in to config.w32.h and copy it to the directories where it is needed. Intellisense should tell you where it's looking and config.w32.h.in is in the C:\php-7.1.8-src\win32 directory.
// this needs to match the compiler version that php was compiled with
#define _CRT_SECURE_NO_WARNINGS
#define PHP_COMPILER_ID "VC14"
#pragma once
/* You must include config.w32.h first */
#include "win32/config.w32.h"
#include "php.h"
ZEND_FUNCTION(ReturnString);
zend_function_entry Project1_functions[] =
{
ZEND_FE(ReturnString, NULL)
{
NULL, NULL, NULL
}
};
zend_module_entry Project1_module_entry =
{
STANDARD_MODULE_HEADER,
"Project1 Module",
Project1_functions,
NULL, NULL, NULL, NULL, NULL,
NO_VERSION_YET, STANDARD_MODULE_PROPERTIES
};
ZEND_GET_MODULE(Project1)
ZEND_FUNCTION(ReturnString)
{
zval* value;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) == FAILURE)
{
RETURN_FALSE;
}
convert_to_string(value);
RETURN_STRING(Z_STRVAL_P(value), true);
}
Press F7 to compile and it should create Project1\Debug\Project1.dll. Copy Project1 to your ext directory C:\php-7.1.8\ext and add an extension=Project1.dll to your php.ini and you should be good to go. If it doesn't work double check your properties to make sure you didn't miss something.
The script is quite simple:
<?php
echo ReturnString("The Returning String");
?>
If the web server is Linux based, you can create a package like .deb or .rpm (depending on the Linux distribution) and easily distribute/deploy it.
BR,
Dawid.
It depends on what you mean by "binary".
If you want to compile (or just obfuscate) your PHP code to keep someone else from modifying then use a bytecode compiler. One example are the tools from Zend, among others. (I prefer Zend's tools because they the primary company behind PHP and fully QA all their tools against all the versions of PHP).
If you want to compile your PHP code and link the PHP runtime to it and then deploy it (like C\C++), then no. Maybe in theory that would be possible but it would be a mess. (Not practical or feasible and don't think anyone has put anything together to try and the output would also be tied to a particular architecture).

Categories