Methods

Can be a ProgID, Class ID or Moniker that names the component to load.
A ProgID is typically the application or DLL name, followed by a period,
followed by the object name. e.g: Word.Application.
A Class ID is the UUID that uniquely identifies a given class.
A Moniker is a special form of naming, similar in concept to a URL
scheme, that identifies a resource and specifies how it should be
loaded. As an example, you could load up Word and get an object
representing a word document by specifying the full path to the word
document as the module name, or you can use LDAP: as
a moniker to use the ADSI interface to LDAP.

server_name

The name of the DCOM server on which the component should be loaded and
run. If NULL, the object is run using the default for the
application. The default is typically to run it on the local machine,
although the administrator might have configured the application to
launch on a different machine.
If you specify a non-NULL value for server, PHP will refuse to load
the object unless the configuration option
is set to TRUE.

If server_name is an array, it should contain the
following elements (case sensitive!). Note that they are all optional
(although you need to specify both Username and Password together); if
you omit the Server setting, the default server will be used (as
mentioned above), and the instantiation of the object will not be
affected by the
directive.

DCOM server name

server_name key

type

description

Server

string

The name of the server.

Username

string

The username to connect as.

Password

string

The password for Username.

Flags

integer

One or more of the following constants, logically OR'd together:
CLSCTX_INPROC_SERVER,
CLSCTX_INPROC_HANDLER,
CLSCTX_LOCAL_SERVER,
CLSCTX_REMOTE_SERVER,
CLSCTX_SERVER and
CLSCTX_ALL. The default value if not
specified here is CLSCTX_SERVER if you also
omit Server, or
CLSCTX_REMOTE_SERVER if you do specify a
server. You should consult the Microsoft documentation for
CoCreateInstance for more information on the meaning of these
constants; you will typically never have to use them.

codepage

Specifies the codepage that is used to convert strings to
unicode-strings and vice versa. The conversion is applied whenever a
PHP string is passed as a parameter or returned from a method of this
COM object. The code page is sticky in PHP 5, which means that it will
propagate to objects and variants returned from the object.
Possible values are
CP_ACP (use system default ANSI code page - the
default if this parameter is omitted),
CP_MACCP,
CP_OEMCP, CP_SYMBOL,
CP_THREAD_ACP (use codepage/locale set for the
current executing thread), CP_UTF7
and CP_UTF8. You may also use the number for a
given codepage; consult the Microsoft documentation for more details on
codepages and their numeric values.

Overloaded Methods

The returned object is an overloaded object, which means that PHP does
not see any fixed methods as it does with regular classes; instead, any
property or method accesses are passed through to COM.

Starting with PHP 5, PHP will automatically detect methods that accept
parameters by reference, and will automatically convert regular PHP
variables to a form that can be passed by reference. This means that you
can call the method very naturally; you needn't go to any extra effort in
your code.

Pseudo Methods

In PHP versions prior to 5, a number of not very pleasant hacks meant that
the following method names were not passed through to COM and were handled
directly by PHP. PHP 5 eliminates these things; read the details below to
determine how to fix your scripts. These magic method names are case
insensitive.

voidCOM::AddRef
( void
)

Artificially adds a reference count to the COM object.

Warning

You should never need to use this method. It exists as a logical complement
to the Release() method below.

voidCOM::Release
( void
)

Artificially removes a reference count from the COM object.

Warning

You should never need to use this method. Its existence in PHP is a bug
designed to work around a bug that keeps COM objects running longer than
they should.

Pseudo Methods for Iterating

These pseudo methods are only available if
com_isenum() returns TRUE, in which case, they hide
any methods with the same names that might otherwise be provided by the
COM object. These methods have all been eliminated in PHP 5, and you
should use For Each instead.

Returns a variant representing a SafeArray that has 10 elements;
each element will be an empty/null variant. This function was supposed to
return an array containing all the elements from the iterator, but was
never completed. Do not use.

User Contributed Notes 45 notes

If your frustrated when getting a com-exception like "Error [0x80004002] ..." (with a message nagging you about an unsupported interface), and you're calling a class method through COM that expects a char as an argument, you should NOT call the method with a single-character string.

The correct way of calling a method like this is to use a VARIANT with a type of VT_UI1.

COM enabled method definition:

public bool DoSomething(char arg);

<?php

$com = new COM('Some.Class.Name');

// This will fail$var = 'a';$com->DoSomething($var);

// This works correctly$var = new VARIANT(ord('a'), VT_UI1);$com->DoSomething($var);

After one week of trying to understand what was wrong with my PHP communication with MS Word, i finally got it working...It seems that if you're running IIS, the COM object are invoked with restricted privileges.If you're having permission problems like not being able to opening or saving a document and you're getting errors like:

- This command is not available because no document is openor - Command failed

try this (if you're running IIS):

- Execute "dcomcnfg"- Open Component Services > Computers > My Computer > DCOM Config- Search for Microsoft Office Word 97-2003 Document (it will be something like this translated to your language, so take a while and search for it)- Right-Click on it and open the properties- Choose "Identity" tab- Normally this is set to "the launching user". You have to change this to "the interactive user" or a admin user of your choice.- Apply these new settings and test your COM application. It should work fine now.

All the examples here show<?php $var = new COM('Whatever.Something') or die(); ?>however the 'or die()' bit is redundant as a fatal 'com_exception' exception will be thrown, killing your script. If you want to handle the 'or' condition you need to catch the exception, eg<?phptry {$var = new COM('Whatever.Something');} catch (com_exception $e) {//couldn't load, do something else like registerexec('regsvr32 /s whatever.dll');}?>

Using SetConsoleTitle you can even set the title displayed in the console window.

Color values are 0..7 for dark colors and 8..15 for light colors. Sequence is (black/silver, blue, green, cyan, red, magenta, yellow/brown, white/gray). I also found that if you add 16384 to the value, it should be inverse. 32768 added should get underlined text. But these latter two didn't work for me.

Hi, just wanna share to everyone after tried and tested many many times to create report in PDF format from Crystal Report.Finally I can do it without any error. Here is my system; PHP 5.1.6, MSSQL2005 and Crystal Report Server XI RL2

That's all for me, anyway in Crystal Report I have to check DisCardSavedData, Save data with report and AutoSave (1 min) in Option Tab and also in Report Options I have to check save dat with report, too.

My previous notes about Crystal Reports have vanished away, but anyway I was up to correct them.

The code above connects to COM (beware of the version number! search on the Registry Editor for the correct name to put in $COM_Object), opens a report from a file ($my_report), reload records from database and then exports it to a PDF file ($my_pdf).

* IMPORTANT * this code, when invoked from the browser (I'm using Apache) AND with a report that connects to a ODBC database, does not work (the problem is specificly the line ReadRecords(), but may arise without it too when data is not saved into the report file).

But when you run this code by PHP-CLI (that is, by the command line), it works ok! I bug-reported this, but have no answer till now ( give it a vote, if you thing it's important: http://bugs.php.net/bug.php?id=36959 ).

Under PHP7(.x) 64-bit, there is a documentation error (on the MSDN side, already reported) causing problems if you try to manipulate the registry (StdRegProv) through COM.

Indeed, MSDN reports that the registry hive/root must be reported as a uint32, which means that, in PHP 64-bit, one would create a new Variant($root,VT_UI4).

This would throw a type mismatch error.It seems internally and contrary to what MSDN says (as of now, 2016-12-13), the root parameter must actually be passed as an int32.

So you have to :1. convert your root number to a negative int to avoid out-of-bounds exceptions when creating the variant below (basically the integer being >= 2^31, you have to wrap it around the 32-bit signed integer maximum yourself) ;2. create a new Variant($root,VT_I4) ;3. pass that Variant to your COM API call.

This did not happen before PHP 7.0 as it always used VT_I4 internally before (see https://bugs.php.net/bug.php?id=73605), but now it respects (and is right to do so) the real integer length, so without an explicit conversion, PHP7 would now output a VT_I8 on x64, versus VT_I4 for PHP5.

If you're using COM to create a DSN Less connection to an MS Access 2007 database, you'll find through Googling that you need to use an updated version of Jet, so the connection string I've found looks like this:

However, on my setup (WinVista, Access 2007, PHP526) I found that it always 'dies' with "Cannot start with Jet", even if the connection was successful ($conn->State reads "1").

I figured to just drop the die() command on $conn->Open(). If something catastrophic happens with the ADO connection then it's own error handling engine passes stack traces, etc back to the console/standard output.

Thanks to paul at completewebservices who added a note earlier; I have used his code to solve a particularly difficult issue with the Crystal 9 runtime component. For some reason, VBA/VBS can pass a native Date type as a parameter to a Crystal Report requiring a date, but in PHP I've tried all manner of strings, unix timestamps, COM variant dates etc and all of these resulted in a com_exception.

My solution was to employ VBScript to borrow the CDate function, which works correctly. Not the most elegant of solutions, but this parameterised approach is to be preferred to search-n-replacing the RecordSelectionFormula string. Of course if anyone here has an even better approach, do post it here - I am sure it would be of use.

If your PHP is configured as ISAPI module then the COM object you create in ur php page will use the same memory space as the web server. If your COM object takes too much memory then this may force some COM error as PHP does not handle the memory usage of COM itself. And also Web server doesnt know what do to free COM memory. But if you use PHP as CGI then PHP itself handle the memory usage of COM. Once in a script where i used COM and PHP as ISAPI module i got unknown COM error.But when i used PHP as CGI there was no error. So those who want to use COM object in your application please be careful about it.

If you can get the old "TaskScheduler.dll" and register it, it is quite simple to handle and start Windows tasks from PHP.This is extremely useful when you got things to do which must be run in a different user context. Prepare a task with the user and use PHP & Com to build a webinterface for it.

Getting IE to the foregroundIf you are using a command line (CLI) version of PHP on a Win32 platform (e.g. XP Pro, SP2), you might want to have output directed to IE (perhaps you'll want to work with the output there) when Popup does not suffice (see my earlier post, below).

It's easy enough to get an instance of IE using $ie = new COM("InternetExplorer.Application");. The problem is, you don't necessarily see it in the foreground (especially if you already have one open) and who wants to waste keystrokes getting to it? The code below has been working for me (If you want to do other adjustments (e.g. $ie->Document->ParentWindow->resizeTo(800,500); or $ie->Document->Body->bgColor = "yellow";), doing them before the $ie->Visible = true; line will avoid screen distractions):

Basic Windows IOIf you are using a command line (CLI) version of PHP on a Win32 platform, you might like to have a simple graphical interface to get input and output. The following gives an illustration for both.

This is example is overblown for illustrative purposes. The whole input part collapses if the amount of code used is a single statement. So, this would have sufficed:$code = "InputBox(\"$prompt\", \"$title\", \"$initial\")";$input = $oScript->Eval($code);

This technique exposes quite a bit of scripting power tied into the Windows operating system and VBScript. However, you should have a really specific reason for using it since VBScript tends to be dog slow when compared to PHP in my tests. Simple IO like this is good, however, and the popup size can be quite large. Furthermore, this could be a viable route to go for accessing WinAPI's.

if you ever need to connect to an access database (on the server, using the IIS or APACHE user account), here is code below that can help to ease the process. It is written like this because we have a MySQL as well as an Access database and need to be able to switch back and forth. The runQuery function will return a 2 dimensional array and can use column names or numbers for the index of the internal arrays. External arrays are always integer-indexed. We also have found issues with Access staying open and growing from 7MB to 2.5GB within two hours, so we open and close it each time we run a query. If it is not a select query it will return TRUE. if it fails with errors, it will return false.

There is a showErr flag that we mostly only use for MySQL, since you can output MySQL errors without PHP errors. Access doesn't appear to be that friendly.

VBScript:
Dim obj, iFlags
Set obj = GetObject("IIS://LocalHost")
' Backup to next available version number.
' Set flags to save the metabase first and
' force the backup even if save fails.
iFlags = (MD_BACKUP_SAVE_FIRST or MD_BACKUP_FORCE_BACKUP)
obj.Backup "MyBackups", MD_BACKUP_NEXT_VERSION, iFlags
' Note: The above was copied from Microbucks.
' This is how you would have to do it.
' i.e. use the actual constant's value.
iFlags = (2 or 4)
obj.Backup "MyBackups", &HFFFFFFFF, iFlags

If you want to use a DSN-less connection to a database (access for example) and return the results of a query as a multidimensional array with the fieldnames as identifier try this. Hope it helps someone :-)
--------------------------------------------------------

--------------------------------------------------------
use it like this:
--------------------------------------------------------
<?php
$results = db("SELECT field_a, field_b FROM table");
foreach($result as $i => $item) {
echo $item['field_a'];
echo $item['field_b'];
}
?>
--------------------------------------------------------
You can also use: print_r($result); if you want the structure of the array to be printed.

In order to get the Word exaple running, do the following on the server side.Worked for me...1. Click START-->RUN and enter "dcomcnfg"2. In the "Applications" tab, go down to "Microsoft Word Document"3. Click PROPERTIES button4. Go to the "Security" Tab5. Click "Use custom access permissions", and then click EDIT6. Click ADD and then click SHOW USERS7. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD8. Go back to the "Security" tab by hitting OK 9. Click "Use custom launch permissions", and the click EDIT10. Click ADD and then click SHOW USERS11. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD12. Hit OK, and then hit APPLY.

Also, you should look at the "Identity" tab in the Microsoft Word Document PROPERTIES and see that it is set to "Interactive User"

ALSO, log into the machine AS the IUSR_<machinename> account, start word, and make sure to click through the dialog boxes that Word shows the first time it is run for a certain user. In other words, make sure Word opens cleanly for the IUSR_ user.

Obviously there's plenty of room for refinement in there, but it works and should get you going on the right track. I also found that during testing, the script was hanging before supressing the parameter prompt. Once this had happened, some exports that had been working earlier stopped completely and wouldn't work again untill I restarted Apache. This might be something worth doing if you keep having issues after a script has hung.

First : You need to make word file with including Boolmark(Ms word 2003 , Insert -> Bookmark ->Bookmark Name -> add). ExampleName : add here bookmark This is something like input as a text box. Here I given 5 fields. Name , TODAYDATE , Company ,project , Features

Here I opened a word file, and put data into Bookmark fields using PHP.

Just note : it works in c:/ only. (not sure why), C:/program files may take longer time. (waiting for ...)

<?php

com_load_typelib('Word.Application');

$word = new COM("word.application") or die("Unable to instantiate Word");

I have searched for ways to open and read an excel document and I found some information which I thought that I would document. Information on the object model to help with programming COM objects can be found in your MS Office help files, search for VBA*.chm.Also, here is a script that I used to pull a cell from each worksheet, complete w/ variable for pathnames & worksheets. This script also closes excel completely. The coding might be dirty, but it gets the job done.--------copy from here-----------<pre><?PHP$filename = "c:/spreadhseet/test.xls";$sheet1 = 1;$sheet2 = "sheet2";$excel_app = new COM("Excel.application") or Die ("Did not connect");print "Application name: {$excel_app->Application->value}\n" ; print "Loaded version: {$excel_app->Application->version}\n";$Workbook = $excel_app->Workbooks->Open("$filename") or Die("Did not open $filename$Workbook");$Worksheet = $Workbook->Worksheets($sheet1);$Worksheet->activate;$excel_cell = $Worksheet->Range("C4");$excel_cell->activate;$excel_result = $excel_cell->value;print "$excel_result\n";$Worksheet = $Workbook->Worksheets($sheet2);$Worksheet->activate;$excel_cell = $Worksheet->Range("C4");$excel_cell->activate;$excel_result = $excel_cell->value;print "$excel_result\n";#To close all instances of excel:$Workbook->Close;unset($Worksheet);unset($Workbook);$excel_app->Workbooks->Close();$excel_app->Quit();unset($excel_app);?></pre>----------------------------------

If you wnat to connect to Access MDB Library you can use this small "progy". It works so, that if someone other accesses the library, it waits for so long to access it again because (as i know) MDB librarys can be accessed only once at the same time.

It should be noted that to run anything that needs to interact with the UI (the word example), one needs to ensure that the process that the Web server is running under can access the UI. For Apache, this is an option in the Services control panel.