Building custom PHP extension (.so) - php

I own a high traffic website that does business in the USA and Canada. We have lots of servers but I want to make sure it's 100% available with no latency whatsoever.
I've learned about creating custom extensions (I know a little C) and I want to create custom validation/files (since php extensions runs faster).
I don't want to ask for all new extensions from you guys but I want to know the general idea on how to build it (I am using CentOS).
Example:
One section of our site is the shipping tracking and this require a postal code.
For the USA I have:
function check_usa_postal_code($pc) {
return is_numeric($pc);
}
But for Canada, I would like to build in PHP a custom function like:
check_canada_postal_code($pc)
This function should return 1 or 0.
Thanks

I recommend to read this article:
Extension Writing Part I: Introduction to PHP and Zend
and here's how to compile:
UNIX: Compiling PHP Extensions
Build PHP extensions with SWIG
(I recommend SWIG like mario said)
Read more on Canadian zip codes at Postal codes in Canada since not all letters are being used.

Rather than try and build an extension in C you should consider compiling your source code using HipHop instead. This will be much simpiler and run your code pretty fast.

You should also consider using Zephir. Its syntax is very similar to PHP. It is specially designed to create PHP extensions and compiles into an extension.
There are even several converters from regular PHP to Zephir. They do not take into account all the peculiarities, so some minor code changes will be needed before compiling. I use sandrokeil/php-to-zephir.

Related

Minify PHP in Visual Studio 2015

Is there any way to minify (or remove comments) in PHP using Visual Studio 2015? I use PHP Tools and when i release php scripts to public server, i would like at least remove all comments from code. I know, is there way to remove comments with content menu, but i wish to have comments in my project and no comments (or minimal and unread code) in publish scripts (some like Bundler & Minifier tool, but for php). Thanks
There is basically no point in minifying Php since there is no performance gain in doing so. Although if you insist, there are a few ways to remove comments/whitespaces from source. (and these are not limited to just VisualStudio) -
Use Gulp.
Use Command line options: php -w file.php => generates file without comments & whitespaces. Equivalent to php_strip_whitespace()
Use Regular Expression in Find-Replace Function of your IDE. You can use the following inside Find FieldBox. (and keep Replace fieldbox empty)
//.* or /.
Use a Library/tool like Php-Minify
Hope that helps!
Why aren't you going to use online tool to do it?
There are many online tools you can use instead of VS 2015.
Here is one tool for you.
http://beta.phpformatter.com/
Hope it helps you and check this answer as solved if it helps you.
Thanks!
You can check Comment Remover tool to remove all the comments from a file with a single button click. It also remove #regions and preserve XML Doc comments.
I think there is no tool for visual studio to do this. But you may use external tools to do the job. It's a common task to do this in build system like jenkins. The build system e. g. is able to react on many version control events.
But I also think that you want to make php code unreadable (like compiling). There are only a few options to hide your php code to other people. You could use ionCube for encrypting php files. But then you have to make sure, that the ionCube extension is also installed on the public web server. Also, ionCube is currently not available for php 7.2, only up to 7.1. Another option is to compile php code using HipHop, a PHP to C++ compiler engine: https://de.wikipedia.org/wiki/HipHop

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.

How to call winapi functions from 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.

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).

php c++ communication

hi i am new in php,i made the whole code in c++ and want to use this code in php.so i made dll to my code for using it.but i am not able to use this dll in php ,can anybody send me the complete code to use php,c++ extensions.
There's a whole section about some php internals and how to write/build a php extension in the online manual at http://php.net/internals2, and I especially want to point out the description of the ext_skel script there as it helps you to set up a new "empty" extension project.
And there are alos tools like SWIG that help you to wrap existing libraries into extensions for numerous languages including PHP.
I made a PHP extension in C++ using SWIG. The PHP specific documentation can be found here.
Since very few online documentation is avaible on using the Zend API I also recommend the book Extending and Embedding PHP.

Categories