PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<ccvs_voidcom>
view the version of this page
Last updated: Sat, 19 Apr 2003

VIII. COM Support Funktionen f�r Windows

Einf�hrung

Das Component Object Model (COM) ist eine Technologie, welche die Wiederverwendung von Code erlaubt, egal in welcher Sprache dieser geschrieben wurde. Die Komponenten stellen Schnittstellen bereit, welche die verf�gbaren Funktionen, aber nicht deren Implementierung bekanntgeben (z.B. auf welcher Maschine die Komponente gespeichert ist und die Executable, die sie enth�lt). Anwendungen k�nnen �ber die COM-API beliebige Schnittstellen erzeugen. Man sich das wie einen super Remote Procedure Call (RPC) Mechanismus mit einigen grundlegenden Objekten vorstellen. Es trennt die Implementation von der Schnittstelle.

COM unterst�tzt Versioning, die Trennung von Implementation und Schnittstelle, sowie das Verstecken von Implementierungsdetails, wie z.B. Position der Executable und die Sprache, in welcher die Komponente geschrieben wurde.

Anforderungen

Die COM Funktionen sind nur in der Windowsversion von PHP verf�gbar.

Installation

F�r diese Funktionen ist keine Installation erforderlich, diese geh�ren zum Grundbestand von PHP.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Laufzeit Konfiguration

Das Verhalten dieser Funktionen wird von Einstellungen in der php.ini bestimmt.

Tabelle 1. Com Konfigurationsoptionen

NameStandardwert�nderbar
com.allow_dcom"0"PHP_INI_SYSTEM
com.autoregister_typelib"0"PHP_INI_SYSTEM
com.autoregister_verbose"0"PHP_INI_SYSTEM
com.autoregister_casesensitive"1"PHP_INI_SYSTEM
com.typelib_file""PHP_INI_SYSTEM
Weitere Details und Definitionen der PHP_INI_* Konstanten finden Sie bei der Funktion ini_set().

Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verf�gung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)

Siehe auch

Weitere Informationen zu COM finden Sie in der , oder in Don Box's .

Inhaltsverzeichnis
com -- COM Klasse
VARIANT -- VARIANT Klasse
com_addref --  Erh�ht den Referenzz�hler der Komponente
com_get --  Liefert den Wert der Eigenschaft einer COM Komponente
com_invoke --  Ruft eine Methode einer COM Komponente auf
com_isenum -- Holt eine IEnumVariant
com_load_typelib -- L�dt eine Typelib
com_load --  Erstellt eine neue Referenz auf eine COM Komponente
com_propget --  Liefert den Wert der Eigenschaft einer COM Komponente
com_propput --  Weist einer Eigenschaft einer COM Komponente einen Wert zu
com_propset --  Weist einer Eigenschaft einer COM Komponente einen Wert zu
com_release --  Reduziert den Referenzz�hler der Komponente
com_set --  Weist einer Eigenschaft einer COM Komponente einen Wert zu.


User Contributed Notes
COM Support Funktionen f�r Windows
add a note
kevin at vcconcepts dot com
01-Apr-2001 12:37

I thought i'd share with those of you unfamiliar with one of the cool things
about developing php on win32 systems..



This is a good article, but i don't think the author hit the nail on the
head showing how useful this can be.

Now, checkout this article:


Notice how he describes 1) how to build a com object & 2) how to call and
use the com object from ASP.

In php, this is how you would call the same object:

<?
$instance = new COM("Checkyear.LeapYear");
$isleapyear = $instance->IsLeapYear($year);
$instance->close();
if($isleapyear) {
echo "The <b>$year</b> is a leap year";
}
else {
echo "The <b>$year</b> is not a leap year";
}
?>

I hope this helps someone.. you can contact me at [email protected] if
you would like to discuss this further.

darkwings at 263 dot net
28-Feb-2002 04:11

now in PHP >=4.0.6
programming in window can use the
ADO through the COM like this:
$dbconn=new COM ("ADODB.Connection") or die ("connection create fail");
$dbconn->Open("Provider=sqloledb;Data Source=ndht;Initial Catalog=printers;User Id=printers;Password=printers;");
$rec=new COM("ADODB.Recordset") or die ("create Recordset error");
while (!$rec->EOF)
{
echo $rec->fields["fieldname"]->value."
";
$rec->movenext();
}
$rec->close();
$dbconn->close();

but there's still a little question of working with the image field of mssql server.

madon at cma-it dot com
07-Mar-2002 07:59

I thought this excel chart example could be useful.

Note the use of Excel.application vs Excel.sheet.

<pre>
<?php
  print "Hi";
#Instantiate the spreadsheet component.
#   $ex = new COM("Excel.sheet") or Die ("Did not connect");
$exapp = new COM("Excel.application") or Die ("Did not connect");

#Get the application name and version    
print "Application name:{$ex->Application->value}
" ;
print "Loaded version: {$ex->Application->version}
";

$wkb=$exapp->Workbooks->add();
#$wkb = $ex->Application->ActiveWorkbook or Die ("Did not open workbook");
print "we opened workbook
";

$ex->Application->Visible = 1; #Make Excel visible.
print "we made excell visible
";

$sheets = $wkb->Worksheets(1); #Select the sheet
print "selected a sheet
";
$sheets->activate; #Activate it
print "activated sheet
";

#This is a new sheet
$sheets2 = $wkb->Worksheets->add(); #Add a sheet
print "added a new sheet
";
$sheets2->activate; #Activate it
print "activated sheet
";

$sheets2->name="Report Second page";

$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name
";

# fills a columns
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
   $cell = $sheets->Cells($i,5) ; #Select the cell (Row Column number)
   $cell->activate; #Activate the cell
   $cell->value = $i*$i; #Change it to 15000
}

$ch = $sheets->chartobjects->add(50, 40, 400, 100); # make a chartobject

$chartje = $ch->chart; # place a chart in the chart object
$chartje->activate; #activate chartobject
$chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); # set the data the chart uses
$chartje->setsourcedata($selected); # set the data the chart uses
print "set the data the chart uses
";

$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
#$ex->Application->ActiveWorkbook->SaveAs($file_name); # saves sheet as final.xls
$wkb->SaveAs($file_name); # saves sheet as final.xls
print "saved
";

#$ex->Application->ActiveWorkbook->Close("False");  
$exapp->Quit();
unset($exapp);
?>

</pre>

Alex Madon

admin at purplerain dot org
02-Apr-2002 11:01

An easy way to send e-mail using your default Outlook account:
<?
$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$a=$myItem->Recipients->Add("[email protected]");
$myItem->Subject="Subject";
$myItem->Body="This is a Body Section now.....!";
$myItem->Display();
$myItem->Send();
?>

admin at purplerain dot org
19-Apr-2002 11:34

an easy way to convert your file from .doc to .html

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

// if you want see thw World interface the value must be '1' else '0'
$word->Visible = 1;

//doc file location
$word->Documents->Open("E:\\first.doc");

//html file location  '8' mean HTML format
$word->Documents[1]->SaveAs("E:\\test_doc.html",8);

//closing word
$word->Quit();

//free the object from the memory
$word->Release();
$word = null;

paulo at Ihatespam dot com
28-Jun-2002 05:48

Complementing Alex's Excell Example, let's print the SpreadSheet to a PDF file using Acrobat Distiller:

$wkb->PrintOut(NULL, NULL, NULL, NULL, "Acrobat Distiller");

There you go!!!

nospam at bol dot com dot br
21-Aug-2002 10:30

This is a sample to make a parametrized query using ADO via COM, this sample was used with Foxpro but will work's with most ADO complient databases. This was tested on IIS with WIN XP pro.

<?
// Create the main connection
$dbc = new COM("ADODB.Connection") or die ("connection create fail");
$dbc->Provider = "MSDASQL";
$dbc->Open("FoxDatabase");
// Creates a temporary record set
$RSet = new COM("ADODB.Recordset");
// Create one ADO command
$cm   = new COM("ADODB.Command");
$cm->Activeconnection = $dbc;
// the ? inside values will be the parameters $par01 and $par02
$cm->CommandText =  "Insert Into testtable ( mycharfield,mymemofield) VALUES (?,?)" ;
$cm->Prepared = TRUE;
// Creates and append 2 parameters
$par01 = $cm->CreateParameter('ppar01',129,1,50,'ABCDEFGHIKL');
$cm->Parameters->Append($par01);
$par02 = $cm->CreateParameter('ppar01',129,1,50,'123456789012346789');
$cm->Parameters->Append($par02);
// Call 10 times the exec comand to show 10 different queries
for ($i = 1; $i <= 10; $i++) {
 $par01->Value = 'Count '.$i;
$par02->Value = 'Passing here'.$i.' times';
 $RSet = $cm->Execute;
}
$RSet = $dbc->Execute("select * from testtable");
while (!$RSet->EOF){
 echo $RSet->fields["mycharfield"]->value.' ' ;
 echo $RSet->fields["mymemofield"]->value ;
 echo '
';
$RSet->movenext();
}
$RSet->close;
$dbc->close;
$cm->close;
$RSet = null;
$dbc = null;
$cm = null;
?>

dwt at myrealbox dot com
27-Aug-2002 10:31

When first writing applications instancing COM objects I always faced the problem of the instanced program not terminating correctly although everything else worked fine. In fact the process had to be killed manually by using the task manager. When experimenting a bit I was able to isolate the cause for this peculiar behaviour to be illustrated by the sample code below:

<?php

//Accessing arrays by retrieving elements via function ArrayName(Index) works, but certainly is neither efficient nor good style
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$book=$excel->Workbooks(1);
$sheet=$book->Worksheets(1);

$sheet->Name="Debug-Test";
$book->saveas("C:\\debug.xls");

$book->Close(false);
unset($sheet);
unset($book);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

//Accessing arrays as usual (using the [] operator) works, buts leads to the application not being able to terminate by itself
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$excel->Workbooks[1]->Worksheets[1]->Name="Debug-Test";
$excel->Workbooks[1]->saveas("C:\\debug.xls");

$excel->Workbooks[1]->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

?>

The sample code performs the same action twice and each time the file is properly created. Yet for some mysterious reason the instanced excel process won't terminate once you've accessed an array the way most programmers (especially those who do a lot of oop in c++) do! Therefore until the PHP developers become aware of this problem we'll have to use the inefficient coding style illustrated in the first example.

tedknightusa at hotmail dot com
26-Sep-2002 04:29

A Notes example:

$session = new COM "Lotus.NotesSession" );
$session->Initialize($password);

$someDB = "C:\Lotus\Notes\Data\somedb.nsf";
$db = $session->GetDatabase("", $someDB) or die("Cannot get someDB.nsf");
$view = $db->GetView("some_view") or die("Some View not found");

$doc = $view->GetFirstDocument() or die("Unable to get Initial Some Document");

// loop through
while($doc){
 $col_vals = $doc->ColumnValues();
 echo $col_vals[0];
 $doc = $view->GetNextDocument($doc);
}

daveNO at SPAMovumdesign dot com
27-Sep-2002 04:52

The documentation for this feature is a bit redundant. It mentions that COM performs and encourages information hiding (a.k.a. encapsulation) three times. Perhaps instead it could expand a bit on what COM is useful for, and particularly why combining it with PHP can be beneficial.

The contributed examples above do a nice job of illustrating the benefits of PHP+COM. In a nutshell, many Windows applications (especially office suites and databases) expose useful functionality through the COM interface.

For example, Microsoft Word can read RTF files and (of course) write Word Documents. You could use PHP to generate RTF and then use Microsoft Word via PHP's COM interface to convert the RTF to a DOC. The amazing thing about this is that you can actually insert PHP (or template) code into Word itself, because RTF files are text-based like HTML. Throw Distiller into the mix and you've got a web-based, template-driven, maybe even database-driven PDF generator!

Have fun,
Dave

pchason at juno dot com
11-Dec-2002 06:23

Searched for days on how to set up a multi-column html output grid that didn't use an array when creating an ADODB connection. Couldn't find one so I figured it out myself. Pretty simple. Wish I would have tried it myself sooner. Commented code with database connection is below...

<html>
<body>
<table>
<?php
//create the database connection
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
//pull the data through SQL string
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
//start the multicolumn data output
$i = 0;
$columns = 5;
while (!$rs->EOF){
//if $i equals 0, start a row
if($i == 0){
echo "<tr>";
}
//then start writing the cells in the row, increase $i by one, and move to the next record
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
//once $i increments to equal $columns, end the row,
//and start the process over by setting $i to 0
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
}
}
//end multicolumn data output

//close the ADO connections and release resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>

richard dot quadling at carval dot co dot uk
26-Feb-2003 12:51

With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.

alex at domini dot net
05-Mar-2003 09:55

To manage the Windows Register at HKEY_LOCAL_MACHINE\SOFTWARE\ use these functions:

<?php

/**
* @return string
* @param aplicacio string
* @param nom string
* @desc Retorna el valor del registre HKEY_LOCAL_MACHINE\SOFTWARE\aplicacio\nom
*/
function rtv_registre($aplicacio, $nom)
{
Global $WshShell;
$registre = "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\"  . $nom;
$valor = $WshShell->RegRead($registre);
  return($valor);
   
   
}

/**
* @return string
* @param aplicacio string
* @param nom string
* @param valor string
* @param tipus string
* @desc Actualitza el valor del registre HKEY_LOCAL_MACHINE\SOFTWARE\aplicacio\nom
*/
function put_registre($aplicacio, $nom, $valor, $tipus="REG_SZ")
{
Global $WshShell;
$registre = "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\"  . $nom;
$retorn = $WshShell->RegWrite($registre, $valor, $tipus);
  return($retorn);
   
   
}

//
// Creem una inst�ncia del COM que ens serveix per
// accedir al registre de Windows, i la mantenim.
// D'aquesta manera millorem el rendiment.
$WshShell = new COM("WScript.Shell");
?>

php at racinghippo dot co dot uk
23-Mar-2003 12:47

PASSING/RETURNING PARAMETERS BY REFERENCE
=========================================

Some COM functions not only return values through the return value, but also act upon a variable passed to it as a parameter *By Reference*:

RetVal = DoSomethingTo (myVariable)

Simply sticking an '&' in front of myVariable doesn't work - you need to pass it a variant of the correct type, as follows:

 $myStringVariant = new VARIANT("over-write me", VT_BSTR);
 $result = $comobj->DoSomethingTo( &$myStringVariant );

The value in the variant can then be retrieved by:

 $theActualValue = $myStringVariant->value;

Other types of variant can be created as your needs demand - see the preceding section on the VARIANT type.

add a note

<ccvs_voidcom>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST