Использовать DLL в PHP?
Я не собираюсь врать. Я не совсем знаком с объектами Windows и COM. Вот почему я здесь. Во-первых, возможно ли получить доступ к DLL из PHP-скрипта, запущенного Apache? В моем путешествии по интернетам я считаю, что у меня есть 2 варианта:
- скомпилируйте dll как расширение для PHP. (я не сделал эту dll)
- доступ к DLL как COM-объект, который является тем, что он предназначен для любого пути.
Поэтому я беру подход COM.
try< $com = new COM('WHAT_GOES_HERE'); > catch(Exception $e)< echo 'error: ' . $e->getMessage(), "\n"; >
Как мне узнать, что будет в строку инициализации? есть ли программа типа com viewer, которую я мог / должен был использовать, чтобы узнать это? документация, связанная с этой DLL, похоже, не указывает, какие строки я должен использовать для инициализации, но очень подробно разбираюсь в том, какие потоки доступны, и всевозможные забавные вещи. просто должен пройти этот начальный горб. Пожалуйста помоги!
WHAT_GOES_HERE – это идентификатор ProgID, Class ID или Moniker, зарегистрированный в операционной системе.
Каждый из них может изменяться для той же DLL, зарегистрированной на разных машинах. Существует несколько способов найти, что такое ProgID / CLSID / Moniker зарегистрированной dll. Вы можете искать в Интернете «dll debugger», «dll export», «dll inspect», и вы увидите несколько решений, а также способы показать, какие функции экспортируют dll, чтобы вы могли их использовать.
Проще всего, вы можете просто зарегистрировать dll с помощью Regsvr32.exe и найти регистр Window в regedit.exe для имени dll, вам может потребоваться выполнить поиск несколько раз, пока не найдете ключ в \HKEY_CLASSES_ROOT\ , который является ProgID.
Команда dcomcnfg.exe показывает много информации о COM-объектах.
Если у вас есть Visual Studio, может оказаться полезным OLE / COM Object Viewer (oleview.exe).
Вы можете запускать dll-функции (из dll, которые не являются расширениями php) с winbinder. http://winbinder.org/ Использование просто. Вам нужно скачать php_winbinder.dll и включить его в php.ini в качестве расширения. В скрипте php вы должны использовать что-то похожее:
function callDll($func, $param = "") < static $dll = null; static $funcAddr = null; if ($dll === null) < $dll = wb_load_library(); > $funcAddr = wb_get_function_address($func, $dll); if ($param != "") < return wb_call_function($funcAddr,array(mb_convert_encoding($param,"UTF-16LE"))); >else < return wb_call_function($funcAddr); >>
Вы можете просто создать оболочку вокруг вашей основной DLL и использовать эту оболочку как расширение в вашем PHP. Некоторые бесплатные инструменты, такие как SWIG, могут автоматически создавать эту оболочку, получая заголовок ваших функций dll. Я сам использую этот подход, и это было легко и надежно.
Load dll into php
On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.
To load an extension, you need to have it available as a «.dll» file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).
To compile an extension into PHP, please refer to building from source documentation.
To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.
Where to find an extension?
PHP extensions are usually called «php_*.dll» (where the star represents the name of the extension) and they are located under the «PHP\ext» folder.
PHP ships with the extensions most useful to the majority of developers. They are called «core» extensions.
However, if you need functionality not provided by any core extension, you may still be able to find one in » PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.
If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read » PECL submit.
Which extension to download?
- Different version numbers (at least the first two numbers should match)
- Different thread safety settings
- Different processor architecture (x86, x64, . )
- Different debugging settings
- etc.
You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:
Example #1 phpinfo() call
Or from the command line, run:
Calling a DLL with PHP
So here’s a quick post on calling dll’s in Windows using php. I have a dll that encrypts data in a certain format that we need for another process. So I need to pass the dll a string and it returns the encrypted string back.
I tried calling the dll using the COM class in code and was having issues until I realized I have to register the dll in windows first before I can call it using the COM class. To register a dll in windows you do the following in your command line:
Now that the dll is registered you can do the following to start accessing the dll:
$my_dll = new COM('MyStuff.Functions');
MyStuff is the dll name an/or id and Functions is the object inside the dll that we want to use. Now I call the method I need and pass the parameters:
$encrypted_text = null; $input = 'This needs to be encrypted.'; $my_dll->EncryptString($input, $encrypted_text );
This is pretty much it. We instantiate the COM class with the dll and function I want. Then I call the method in the dll passing my text and it returns into my $encrypted_text var the encrypted text. I can now do my next process with the encrypted text like:
19 thoughts on “Calling a DLL with PHP”
i am a newbie on php, i wanted to ask if this sample could access the dll installed in the client machine or the server
Hi Alfred, PHP can only access what is in the server and not the client so if you would need to make sure the dll is available to PHP on the server side where the PHP code relies.
This is possible to do without register the dll?
Is possible to do without using the COM class? Thank you.
Hey Eric, when I tried this I had to register the dll. To be honest, I don’t remember how much time I spent trying without registering but it was how I was able to get it to work. I don’t remember what the documentation says but I would assume as long as you pass a correct path to the file it should have worked. I don’t know if this helps you but there seems to be a .net class object that may help you but it also uses com I believe: http://us.php.net/manual/en/class.dotnet.php
Hi, I was wondering if you can do the following: I have the dll of an application, this application reads two-dimensional bar codes using a webcam and decodes them to show a result, when I download the dll that came with examples of its use in vb.net, c++ y c #, but not in php . Now I need to use this application and return me the number that stores the bar code. Hope some advisement from you… the application is QuickMark
Jenny, I’m not sure I’ll be much help. If I remember correctly, this only worked with some dll’s I tried and not all but I could have done something wrong. Also, I think if the dll couldn’t get registered with the system then I was not able to use them in PHP.
Move all the dll files from the application installation folder to wherever you are calling the COM object.( In my case it is c:\\Xampp\htdocs\My_project). Then register the dll files as said above. If you are using 64 bit operating system, then navigate to c:\\windows\SysWOW64 in cmd and run regsvr32 command. Hope it helps.
iam trying to call c++ dll in php.
while creating a COM object iam getting error,can’t create COM object..like this… Is it mandatory to register the dll into system to use that dll in php.
and how to write wrapper for that dll to use those functions in php..
if anybody knows ,please clarify this.
Thanks..
I think we have to rememer that all DLLs cannot be registered or use .NET. I’m just now looking to do the same. I’ve called dlls from other scripting languages in the past. I’m sure I’ll find an answer. I just wanted to mention that when working with third party dlls that all cannot be registered and developers should either code a wrapper that can be registered of document how they can be used otherwise.
We are developing a LMS using PHP and we need to integrate a USB Hardware lock to for security, can anybody tell how to use / call a dll file to check whether the valid lock is there or not on usb port Thanks in advance
sir do you have a tutorials creating .net dll in visual studio coz im not familiar with .net only in php.. thank bcoz we are we integrating biometric to php…
I’m trying real hard to learn about COM objects and calling them from PHP; this example was one of the first I came upon when I started looking for information. From what I’ve read I gather that the DLL must contain an interface in order to be used as a COM object – not just any DLL will do; is this correct?
Hey Bo, when I was playing around with this a few years back only certain types of DLL’s would work. Unfortunately I don’t remember why some worked and others didn’t but you are correct – not just any DLL will do.
Hi Joey/All Anyone have any feedback on whether using a DLL in a PHP website would be scalable? I presume it loads an instance of the DLL for each call so was thinking on a busy site that used the DLL for all its database access this might end up being slow. I’m being asked to use a Delphi DLL within a new site inplace of accessing the database directly.
Andy, I think you have destruct COM objects carefully after use. It solves your problem? It doesnot solve situation, when there are a significant numner of quazi-simultaneous calls, but is a rare case.
Hi Joey, I am going to try this method to access DLL in which I need to pass 2 values. But can you tell me if I need to configure any other thing as well. I checked in phpinfo that COM and DCOM are enabled but .Net says “not present in this build”. Would it be effect?
Hi All, I wanted to call a function inside .NET dll from PHP. Have enabled php_com_dotnet extension. Can anyone please help me how to proceed further?