|
|
IX. Windows用のCOMサポート関数
COMは、標準化された呼び出し規約及びコンポーネントが保存されている
マシンや実行ファイルが存在するマシンの種類の実装の詳細をAPIの背後
に隠蔽することにより、(あらゆる言語により)あらゆる言語で書かれたコー
ドを再使用することを可能とする技術です。COMは、いくつかの基本的な
オブジェクトルートを有する特別なRemote Procedure Call (RPC)機構と
考えることができる。COMは、実装をインターフェイスから分離します。
COMは、バージョン管理、インターフェイスからの実装の分離、実行ファ
イルの位置や記述される言語のような実装の詳細の隠蔽を推奨します。
COM関数は、Windowsバージョン版のPHPでのみ利用可能です。
これらの関数はPHPコアに含まれるため、使用す
る際にインストールは不要です。
これらの関数の動作は、php.iniの設定により変化します。
表 1. Com 設定ディレクティブ 名前 | デフォルト | 有効/無効の意味 |
---|
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 |
PHP_INI_*定数に関する詳細と定義については、
ini_set()を参照して下さい。
これらの定数は、この拡張モジュールで定義されており、
この拡張モジュールがPHP内部にコンパイルされているか実行時に動的にロー
ドされるかのどちらかの場合のみ使用可能です。
COMに関するより詳細な情報については、またはDon Boxの
を
参照下さい。
add a note
User Contributed Notes
Windows用のCOMサポート関数
Gianluca GIMIGLIANO
13-Mar-2005 05:17
// NOTE: Using COM with windows XP with apache as a service
// - Compact a Microsoft Access Database
// Be careful $sourceFile and $destFile
//cannot be the same and
// $destFile must be unexistent
Function CompactMSAccess($sourceFile,$destFile) {
$com = new COM("JRO.JetEngine");
$com->CompactDatabase("Data Source=$sourceFile",
"Data Source=$destFile");
$com->Release();
$com=null;
return is_file($destFile);
//if $destFile exists it's a compact DB
}
CompactMSAccess('C:\directory\source.mdb',
'C:\directory\compact.mdb');
michael at example dot com
23-Feb-2005 08:42
After alot of trouble with IIS 6/Windows 2003 and PHP 5.0.2 I figured out how to use Imagemagick COM+/OLE interface. Seems you have to recreate the COM object after each convert() otherwise it will sometimes fail with very strange errors, since the PHP COM interface is not as stable as the old ASP one apparently is.
pelegk2 at walla DOT co DOT il
13-Feb-2005 04:49
Printing to a network printer :
read this note for :
// NOTE: Using COM with windows NT/2000/XP with apache as a service
// - Run dcomcnfg.exe
// - Find word application and click properties
// - Click the Security tab
// - Use Custom Access Permissions
// - Add the user who runs the web server service
// - Use Custom Launch permissions
// - Add the user who runs the web server service
THEN
// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";
// bring it to front
$word->Visible = 1;
//this is for example a printer on my network
$word->ActivePrinter = "\\\\192.168.4.201\\printer1";
// Open a word document, or anything else that word
// can read
$input ="c:\\test.html";
$word->Documents->Open($input);
$word->ActiveDocument->PrintOut();
// closing word
$word->Documents[1]->Close(false);
$word->Quit();
// free the object
$word->Release();
$word = null;
unset($word);
its based on :
at last i did it with lot's of thanks too :
cccso at mahidol dot ac dot th
11-Feb-2005 11:13
<?
$dbfile='D:\DB\log.mdb';
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open(DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$dbfile; );
$rs = $conn->Execute("Select * From tb_sql");
$tmp_result=$rs->Fields("count");
$result[$count]=$tmp_result->value;
echo "$count ==> $result[$count] <br>";
$rs->Close();
?>
if use version 4.3.10 with windows 2003 can not run "$conn->Open()"
06-Jan-2005 05:11
if you want to add a new hyperlink with excel :
$cell=$sheet->Range('O'.$j);
$cell->Hyperlinks->Add($cell ,'here_your_file');
I write this note because is very difficult to find
the good method to do that .
Merci beaucoup
sorin dot andrei at mymail dot ro
25-Sep-2004 09:24
[Editor's Note:
Serializing the object, storing it and then (on the next page) unserializing it WILL work.
End Note]
the big problem for PHP is it can't save in session an COM object
an samples code is here. This works just first time, then give the error:
Call to undefined method com::Refresh() on line $mMap->Refresh();
the reson is he can't save the object $mMap in session
<?php
session_start();
if (isset($_SESSION['map'])) {
$mMap = $_SESSION['map'];
}
else
{
$ArcIMSConnector = new COM ("aims.ArcIMSConnector") or die("can not create AIMS message object");
echo "Loaded ArcIMSConnector, <br>";
$ArcIMSConnector->ServerName = "map.sdsu.edu";
$ArcIMSConnector->ServerPort = 5300;
$mMap = new COM ("aims.Map") or die("can not create aims.Map message object");
echo "Loaded aims.Map, <br>";
print "AIMS-ServerName= $ArcIMSConnector->ServerName <br>";
$resultInit= $mMap->InitMap($ArcIMSConnector,"Worldgeography");
$mMap->Width = 400; $mMap->Height = 300; $mMap->BackColor = 15130848;
$_SESSION['map'] = $mMap;
}
$resultRefresh = $mMap->Refresh(); $urlImage = $mMap->GetImageAsUrl();
print "<br>urlImage=$urlImage<br>";
print "<br><IMG SRC='$urlImage'>";
?>
ferozzahid [at] usa [dot] com
24-Aug-2004 07:06
To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it.
As an example, calling a function that retrieves the name of a person will look like:
$Name = new VARIANT;
$comobj = new COM("MyCOMOBj.Component") or die("Couldn't create the COM Component");
if(!$comobj->GetName($Name)) {
echo("Could not retrieve name");
}
else {
echo("The name retrieved is : " . $Name->value);
}
$Name->type will contain the type of the value stored in the VARIANT e.g. VT_BSTR.
Note For PHP 5:
Insted of '$Name->value', we can use only '$Name' for getting the value stored in the VARIANT. To get the type of the value stored in the VARIANT, use 'variant_get_type($Name)'.
Feroz Zahid
Shawn Coppock
11-Aug-2004 08:15
For those of us that are not experts with object models, if you have Microsoft Excel or Microsoft Word available, go into the Visual Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see what you find.
If you select "Word" in the object browser, then the classes and members of that class are displayed below. For example, if you click on "Selection" in the classes column, and then "Font" in the members column, you will then see "Property Font As Font Member of Word.Selection" displayed at the bottom. Click on the "Font" link there.
Click on Word "Selection" again in the classes column, and then "PageSetup" in the members column, you will then see "Property PageSetup As PageSetup Member of word.Selection" displayed at the bottom. Click on the "PageSetup" link there.
Using the above examples, you can now formulate your Word Document from php. Here is a simple example that creates a 1 & 1/2" space for text based on the margin settings & with dark red text and an 8pt Helvetica font face:
$content = "Insert Sample Text Here\n\nThis starts a new paragraph line.";
$word= new COM("word.application") or die("Unable to create Word document");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '3"';
$word->Selection->PageSetup->RightMargin = '4"';
$word->Selection->Font->Name = 'Helvetica';
$word->Selection->Font->Size = 8;
$word->Selection->Font->ColorIndex= 13; //wdDarkRed = 13
$word->Selection->TypeText("$content");
$word->Documents[1]->SaveAs("some_tst.doc");
$word->quit();
echo "done";
This example (and others) worked for me with Microsoft Word 10.0 Object Library (MS Word 2002), Apache & PHP on Windows XP. Experimenting using the Visual Basic editor will yield some amazing documents from PHP as it will help you see the relationships of the objects used and give you an idea as to how to construct your code. But be prepared for an occaisional PHP.exe crash if your code is way off base.
Hope this helps!
Jason Neal
21-Jul-2004 07:48
If you are having issues with the outlook.application locking up when you try to access it, ensure that your apache server is running in the context of a user on the machine instead of the system account.
appleapril04pear at cherrypixelbananapiz dot de
13-Jul-2004 12:36
If you want to use ms indexing server by querying it from ms sql server in a stored procedure with parameters you can do the following:
1.) Create the Catalog named 'myIndexServer' in indexing server
2.) execute addLinkedServer in query analyzer
EXEC sp_addlinkedserver
@server = 'myIndexServer',
@srvproduct = 'Index Server',
@provider = 'MSIDXS',
@datasrc = 'myIndexServer'
GO
in case myIndexServer already exist choose another name or
delete it (be carefull)
EXEC sp_dropserver myIndexServer
GO
3.) Write the following string in query analyzer
declare @sql varchar(1000)
declare @searchFor varchar(400)
set @searchFor = 'phporsomething'
set @sql =' SELECT Path, Filename
FROM OPENQUERY( pmsIndexServer,
''SELECT Path, Filename FROM
pmsProtokollAnhaengeIndex..SCOPE()
WHERE CONTAINS( '''''+@searchFor+''''' )'' ) AS dres' -- end of long sql-string
exec (@sql)
Attention 5 times ' !!!
4.) Execute the string (F5)
5.) Create a simple stored procedure and copy the string from step 3. Make @searchFor an parameter of your sp
6.) You are done, lean back, enjoy and relax
To contact me remove the fruits.
martijn at lico dot nl
21-Jun-2004 12:30
A nice feature you get with COM is the ability to connect to the Windows Management Instrumentation (WMI for short). This allows you to monitor various system statistics (e.g. disk space en cpu usage) of local and remote systems.
Small example:
<?php
$hostname = ".";
$wmi = new COM("WinMgmts:{impersonationLevel=impersonate}
//{$hostname}/root/cimv2");
$cpus = $wmi->ExecQuery("Select * from Win32_Processor");
foreach ($cpus as $cpu)
{
echo trim($cpu->Name)." {$cpu->MaxClockSpeed}MHz {$cpu->LoadPercentage}%\n";
}
?>
will give you this:
Intel Pentium III processor 860MHz 1%
Intel Pentium III processor 860MHz 2%
For more examples, see this post on my weblog:
angelo [at] mandato <dot> com
03-Jun-2004 06:37
Useful PHP MSWord class I created to do some simple file conversions. This class could have a lot more to it but I am not familiar with all the COM MS Word function calls.
<?php
$wdFormatDocument = 0;
$wdFormatTemplate = 1;
$wdFormatText = 2;
$wdFormatTextLineBreaks = 3;
$wdFormatDOSText = 4;
$wdFormatDOSTextLineBreaks = 5;
$wdFormatRTF = 6;
$wdFormatUnicodeText = 7;
$wdFormatHTML=8;
class MSWord
{
var $handle;
function MSWord($Visible = false)
{
$this->handle = new COM("word.application") or die("Unable to instanciate Word");
$this->handle->Visible = $Visible;
}
function Open($File)
{
$this->handle->Documents->Open($File);
}
function NewDocument()
{
$this->handle->Documents->Add();
}
function WriteText( $Text )
{
$this->handle->Selection->Typetext( $Text );
}
function DocumentCount()
{
return $this->handle->Documents->Count;
}
function SaveAs($File, $Format = 0 )
{
$this->handle->ActiveDocument->SaveAs($File, $Format);
}
function Save()
{
$this->handle->ActiveDocument->Save();
}
function Close()
{
$this->handle->ActiveDocument->Close();
}
function GetVersion()
{
return $this->handle->Version;
}
function GetHandle()
{
return $this->handle;
}
function Quit()
{
if( $this->handle )
{
$this->handle->Quit();
$this->handle->Release();
$this->handle = null;
}
}
};
?>
Example 1, opens an html file, writes text to it, then saves it as a document:
<?php
$input = "C:\\test.htm";
$output = "C:\\test.doc";
$Word = new MSWord;
$Word->Open($input);
$Word->WriteText("This is a test ");
$Word->SaveAs($output);
$Word->Quit();
?>
Example 2, opens an html file, then saves it as a rtf file:
<?php
$input = "C:\\test.htm";
$output = "C:\\test.rtf";
$Word = new MSWord;
$Word->Open($input);
$Word->SaveAs($output, $wdFormatRTF);
$Word->Quit();
?>
angelo [at] mandato <dot> com
18-May-2004 11:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
$ADO_NUM = 1;
$ADO_ASSOC = 2;
$ADO_BOTH = 3;
function ado_connect( $dsn )
{
$link = new COM("ADODB.Connection");
$link->Open($dsn);
return $link;
}
function ado_close( $link )
{
$link->Close();
}
function ado_num_fields( $rs )
{
return $rs->Fields->Count;
}
function ado_error($link)
{
return $link->Errors[$link->Errors->Count-1]->Number;
}
function ado_errormsg($link)
{
return $link->Errors[$link->Errors->Count-1]->Description;
}
function ado_fetch_array( $rs, $result_type, $row_number = -1 )
{
global $ADO_NUM, $ADO_ASSOC, $ADO_BOTH;
if( $row_number > -1 ) $rs->Move( $row_number, 1 );
if( $rs->EOF )
return false;
$ToReturn = array();
for( $x = 0; $x < ado_num_fields($rs); $x++ )
{
if( $result_type == $ADO_NUM || $result_type == $ADO_BOTH )
$ToReturn[ $x ] = $rs->Fields[$x]->Value;
if( $result_type == $ADO_ASSOC || $result_type == $ADO_BOTH )
$ToReturn[ $rs->Fields[$x]->Name ] = $rs->Fields[$x]->Value;
}
$rs->MoveNext();
return $ToReturn;
}
function ado_num_rows( $rs )
{
return $rs->RecordCount;
}
function ado_free_result( $rs )
{
$rs->Close();
}
function ado_query( $link, $query )
{
return $link->Execute($query);
}
function ado_fetch_assoc( $rs, $row_number = -1 )
{
global $ADO_ASSOC;
return ado_fetch_array( $rs, $ADO_ASSOC, $row_number);
}
function ado_fetch_row( $rs, $row_number = -1 )
{
global $ADO_NUM;
return ado_fetch_array( $rs, $ADO_NUM, $row_number);
}
function ado_field_len( $rs, $field_number )
{
return $rs->Fields[$field_number]->Precision;
}
function ado_field_name( $rs, $field_number )
{
return $rs->Fields[$field_number]->Name;
}
function ado_field_scale( $rs, $field_number )
{
return $rs->Fields[$field_number]->NumericScale;
}
function ado_field_type( $rs, $field_number )
{
return $rs->Fields[$field_number]->Type;
}
?>
The aod version was a typo.
markshane1 at fuse dot net
10-May-2004 11:41
Here is a COM function that creates an excel spreadsheet with any number of worksheets, containing data from a matching number of SQL queries. Be ware of the upper limit of excel worksheets. This function properly shuts down Excel on the server.
/***************************/
function WriteExcel($strPath,$astrSheetName,$astrSQL){
/* This function takes a file save path, and array of sheet names and a corresponding array */
/* of SQL queries for each sheet and created a multi-worksheet excel spreadsheet*/
$C_NAME=__CLASS__."::".__FUNCTION__;
$dbs=new clsDB;
$exapp = new COM("Excel.Application") or Die ("Did not connect");
$intSheetCount=count($astrSheetName);
$wkb=$exapp->Workbooks->Add();
$exapp->Application->Visible = 1;
for ($int=0;$int<$intSheetCount;$int++){
$sheet=$wkb->Worksheets($int+1);
$sheet->activate;
$sheet->Name=$astrSheetName[$int];
$intRow=1;
$qrySQL=$dbs->GetQry($astrSQL[$int],$C_NAME,__LINE__);
$rstSQL=$qrySQL->fetchRow(DB_FETCHMODE_ASSOC);
$astrKeyNames=array_keys($rstSQL);
$intCols=count($astrKeyNames);
$qrySQL=$dbs->GetQry($astrSQL[$int],$C_NAME,__LINE__);
while($rstSQL=$qrySQL->fetchRow(DB_FETCHMODE_ASSOC)){
$strOut="";//initialize the output string
for ($int2=0;$int2<$intCols;$int2++){//we start at 1 because don't want to output the table's index
if($intRow==1){
$strOut=$astrKeyNames[$int2];
}else{
$strOut=$rstSQL[$astrKeyNames[$int2]];
}
$sheet->activate;
$cell=$sheet->Cells($intRow,($int2+1));//->activate;
$cell->Activate;
$cell->value = $strOut;
}//end of colcount for loop
$intRow++;
}//end while loop
}//end sheetcount for loop
if (file_exists($strPath)) {unlink($strPath);}
$wkb->SaveAs($strPath);
$wkb->Close(false);
unset($sheet);
$exapp->Workbooks->Close(false);
unset($wkb);
$exapp->Quit;
unset($exapp);
unset($dbs);
}//function WriteExcel
Haseldow
05-Apr-2004 12:31
Simple example for creating your own dll's which can be called as COM objects in PHP:
First create your ActiveX dll (Visual Basic):
Name your project as "foo" and class as "bar".
'---start VB code---
Public Function hello() As String
hello = "Hello World!"
End Function
'---end VB code---
Then make the dll and register it with regsvr32.exe
Now create your PHP script:
<?php
$obj = new COM("foo.bar");
$output=$obj->hello(); echo $output; ?>
mark dickens at mindspring dot com
29-Feb-2004 04:03
Just a note to those wanting to use COM to interface to printers under Windows 2000/XP. If it doesn't work or seems to hang, try changing the logon identity under which the Apache (assuming you're using Apache) service is running from the System account to another account. By default most services will install to run under the System account and although the System account has total authority on the computer it is running on, it has no authority outside of that realm as I understand it. Apparently accessing printers is considered "outside the realm". I used this technique to interface a Dymo thermal label printer to my server and it works now.
Awadhaj at hotmail dot com
28-Feb-2004 01:44
Hi php Society!
Using COM function u can run your own simple dlls !
#if u are an ADMINISTRATOR#
first: use the windows regsver32.exe to register ur dll.
second:
<php?
$myDLL=new COM("myDll");
// then u can invoke eny method
$myDLL->DoSomething;
// or get any proerty
$xVar=$myDLL->GetSomeValue
?>
platiumstar at canada dot com
12-Feb-2004 11:08
I didn't found any working examples of PHP using the MSMQ COM object, so I made up one, thought I share it with everybody..it works ok.
You have to create a local Public message queue named "TestQueue" first.
define(MQ_SEND_ACCESS , 2);
define(MQ_DENY_NONE , 0);
$msgQueueInfo = new COM("MSMQ.MSMQQueueInfo") or die("can not create MSMQ Info object");
$msgQueueInfo->PathName = ".\TestQueue";
$msgQueue = new COM("MSMQ.MSMQQueue") or die("can not create MSMQ object");
$msgQueue=$msgQueueInfo->Open(MQ_SEND_ACCESS, MQ_DENY_NONE );
$msgOut = new COM("MSMQ.MSMQMessage") or die("can not create MSMQ message object");
$msgOut->Body = "Hello world!";
$msgOut->Send($msgQueue);
$msgQueue->Close();
unset($msgOut);
unset($msgQueue);
unset($msgQueueInfo);
enjoy
PS
kleontiv -at- combellga -dot- ru
15-Dec-2003 07:47
And here is an example of using ADSI via ADODB. This sample is unique because only ADODB can provide recursive Active directory searching and listing. But ADODB can only READ Active directory. So you can find something by ADODB and then modify that directly by ADSI.
With previos example this help build you PHP coded interface to Menaging and browsing Microsoft Active Directory.
Also ADODB on ADSI helps you sort recordset and search on it.
<?php
$objConnection = new COM ("ADODB.Connection") ;
$objConnection->Open("Provider=ADsDSOObject;user id=DOMAIN\\login;password=your_passowrd;") ;
$objCommand = new COM("ADODB.Command") ;
$objCommand->ActiveConnection = $objConnection ;
$Cmd = "<LDAP://dc=mydomain,dc=com>;" ;
$Cmd .= "(&(objectClass=user)(mail=*)(!cn=SystemMailbox*));" ;
$Cmd .= "name,mail,telephoneNumber;subtree" ;
$objCommand->Properties['Sort On']->Value = "name" ;
$objCommand->CommandText = $Cmd ;
$objRecordSet = $objCommand->Execute() ;
$OrderNumber = 0 ;
while(!$objRecordSet->EOF())
{
$OrderNumber ++ ;
$nn = $objRecordSet->Fields['name']->Value ;
$mm = $objRecordSet->Fields['mail']->Value ;
$ph = $objRecordSet->Fields['telephoneNumber']->Value ;
echo "$OrderNumber: $nn mail: $mm phone: $ph<br>" ;
$objRecordSet->MoveNext() ;
}
Echo "===========================<br>" ;
Echo "All MailBoxes: " ;
Echo $objRecordSet->RecordCount() ;
$objRecordSet->Close() ;
$objCommand->Close() ;
$objConnection->Close() ;
unset($objRecordSet) ;
unset($objCommand) ;
unset($objConnection) ;
?>
kleontiv -at- combellga -dot- ru
15-Dec-2003 05:27
I think some one wants to access to Microsoft Active Directory using ADSI with different credential by PHP. You can also do it via pure LDAP but using ADSI it is more simpler.
On VB, VBS or ASP you can do like folowing (so not trivial):
<%
Set dso = GetObject("LDAP:")
Set DsObj = dso.OpenDSObject( _
"LDAP://DC=mydomain,DC=com", _
"DOMAIN\login", _
"password", _
ADS_SECURE_AUTHENTICATION + ADS_SERVER_BIND + ADS_USE_ENCRYPTION)
for each Obj in DsObj
Response.Write Obj.name & " with class of: " & Obj.class & "<br>"
next
%>
On PHP you can do like that:
<?php
$ADSI = new COM("LDAP:") ;
$DsObj = $ADSI->OpenDsObject("LDAP://DC=mydomain,DC=com",
"DOMAIN\login",
"password",
515) ;
while($Obj = $DsObj->Next())
{
echo $Obj->name.' with class of: '.$Obj->class.'<br>' ;
}
?>
The access type enumeration you can use as ADS_AUTHENTICATION_ENUM.
david at wu-man dot com
06-Dec-2003 10:42
After many hours of trial and error, I have finally discovered how to kill the notorious Word process. I hope my solution works for everyone else.
#1) $word->Quit() is perfectly fine. Don't bother feeding in as parameter those empty variants.
#2) Do NOT have com_load_typelib('Word.Application') anywhere in your script.
#3) Make sure you have the following line before $word->Quit() :
$word->Documents[1]->Close(false);
#4) Add the following lines after $word->Quit() :
$word->Release();
$word = null;
unset($word);
If my solution indeed helped you with your problem, please email me and let me know. I would like to see if the problem was indeed solved.
aldric dot vaseur at sirom dot fr
04-Dec-2003 04:07
Yes !
Finally i found how to kill MsWord Com process...
The next MSWord function does not work if the optional args are empty :
this doesn't work:
$word->Quit();
but this is ok :
$empty = new VARIANT(); //for optional args...
$word->Quit($empty,$empty,$empty);
Hope this usefull.
Aldric
alanraycom at el hogar dot net com
03-Dec-2003 11:50
XSLT transformations using MSXML can be done with this code
function xsltransform1($xslpath,$xmlstring)
{
$xml= new COM("Microsoft.XMLDOM");
$xml->async=false;
// $xmlstring is an xml string
$xml->load($xmlstring);
$xsl = new COM("Microsoft.XMLDOM");
$xsl->async=false;
// $xslpath is path to an xsl file
$xsl->load($xslpath);
$response=$xml->transformNode($xsl);
unset($xml);
unset($xsl);
return $response;
}
// enjoy
//Alan Young
chris at hitcatcher dot com
02-Dec-2003 12:19
Many COM objects don't do well when passing long (win32) filenames as function parameters. You can get the 8.3 name of the folder or file on *most* (some win platforms don't support it, and it can be toggled off in the registry for performance reasons) servers using the following:
<?php
$exFSO = new COM("Scripting.FileSystemObject") or die ("Could not create Scripting.FileSystemObject");
$myDir = "C:\\Program Files\\";
$myFile = "a long file name.txt";
$exDir = $exFSO->GetFolder($myDir);
$exFile = $exFSO->GetFile($myDir . $myFile);
echo $exDir->ShortPath;
echo $exFile->ShortPath;
?>
23-Nov-2003 05:57
Here is an example of reading the custom properties like Author, Keywords, etc. which are stored in MS Office and other Windows files. You must install and register dsofile as described at The .frm file in that distribution lists most of the available properties.
// the file you wish to access
$fn = '/docs/MFA.xls';
$oFilePropReader = new COM('DSOleFile.PropertyReader');
$props = $oFilePropReader->GetDocumentProperties($fn);
// one syntax
$au = com_get($props, 'Author');
print "au: $au \n";
//another syntax
$str = 'LastEditedBy';
$lsb = $props->$str;
var_dump($lsb);
// set a property if you wish
if (!$props->IsReadOnly()) {
$props->Subject = 'tlc';
}
brana
17-Nov-2003 01:17
How to send email via MAPI (works with Windows NT4, apache launched as a service)
#New MAPI session...
$session = new COM("MAPI.Session");
#Login
$strProfileInfo = "exchange_server" . chr(10) . "exchange_user";
$session->Logon("", "", 0, 1, 0, 1, $strProfileInfo);
# New message...
$msg = $session->Outbox->Messages->Add();
$msg->Subject = "Subject";
$msg->Text = "body";
#set recipients...
$rcpts = $msg->Recipients;
$rcpts->AddMultiple("[email protected]", 1); #To...
$rcpts->AddMultiple("[email protected]", 2); #Cc...
$rcpts->AddMultiple("[email protected]", 3); #Bcc...
# Resolve senders
$rcpts->Resolve();
#Send message
$msg->Send();
#Logoff
$session->Logoff();
#Cleanup
if($msg!=null) {
$msg->Release();
$msg = null;
}
if($session!=null) {
$session->Release();
$session = null;
}
ps : NT account launching the service and exchange user must match !
max at netznacht dot de
11-Nov-2003 03:45
Apache 1.3
PHP 4.x
I found the Example from Admin Purplerain usefull but, it wasn't working without this first Line:
com_load_typelib('Outlook.Application');
// after that the code from Purplerain
$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$a=$myItem->Recipients->Add("your adress here");
$myItem->Subject="Subject";
$myItem->Body="This is a Body Section now.....!";
$myItem->Display();
$myItem->Send();
Still have to switch of the Outlook Security Warnings.
11-Nov-2003 01:25
RE: PROBLEM QUITTING MICROSOFT EXCEL
I strongly suspect this is due to excel helpfully asking "Do you want to save the changes you made to 'Book1'?" when Quit is called.
This can be avoided by making sure that you set the 'Saved' property to True on ALL workbooks before exiting.
Assuming you only have the one workbook:
$excel->ActiveWorkbook->Saved = 1
Word suffers a similar problem and you must set the saved property to true on each document.
This demonstrates the pitfalls of scripting Word, Excel and similar applications in a non-interactive environment.
dirk_hahn at westlb-systems dot de
06-Nov-2003 04:07
Hi,
I�ve GOOGLED alot to find out how to use the MS Index Server (which comes with IIS-Webserver) as a search engine. Here is the code that makes a connection via ADO and lists a result for a given searchstring. Hope you'll find it usefull, it will surely prevent you from searching a long time in search engines. If anybody knows how to do it better, feel free to post it here. The following url contains a description for the index server. It also mentions some further features of the index server ( japanese only, sorry).
$searchstring="news";
$INDEXCATALOG="YourCatalogName";
$objIndexServer = new COM("ADODB.Connection") or die("Cannot start ADO");
$objIndexServer->Provider = "msidxs";
$objIndexServer->Open($INDEXCATALOG);
$sql="SELECT DocTitle, VPath, Path, Filename, Access, HitCount, Rank "
."FROM SCOPE('DEEP TRAVERSAL OF \"d:\inetpub\intranet \"') "
."WHERE ((CONTAINS(' \"$searchstring\" ') >0) "
."AND ((Path NOT LIKE '%\_vti%') AND (Path NOT LIKE '%\_private%') "
."AND (Filename NOT LIKE 'search.php'))) ORDER BY Rank DESC";
$objRS = $objIndexServer->Execute("$sql"); # submit the query
while (!$rs->EOF) //create output
{
echo
$objRS->Fields["DOCTITLE"]->value." -- "
.$objRS->Fields["FILENAME"]->value." -- "
.date("d.M.y",$objRS->Fields["ACCESS"]->value)." -- "
.$objRS->Fields["HITCOUNT"]->value." -- "
.($objRS->Fields["RANK"]->value/10)."% ----> "
.$objRS->Fields["VPATH"]->value
."<br>";
$objRS->MoveNext();
}
feelingflash at hotmail dot com
03-Nov-2003 08:13
PROBLEM QUITTING MICROSOFT EXCEL
I have been trying to solve the problem of terminating the excel process when using the COM functionality. I found a few 'supposed fixes' including not using arrays etc but none of them seemed to work. Example:
$excel->application->Quit();
$excel->Quit();
None of these variants properly quit the process - ONLY the visible application. Several hours of using your code would leave thousands of excel processes running invisibly in the background and eating all your ram very quickly.
As I was developing on a solution designed to work on clients running windows, my solution was to install microsofts 'kill.exe' into the windows directory and then run it using:
shell_exec("kill excel.exe");
One problem is because kill.exe is an add on utility, some clients running windows will not have it. The solution is then to use file_exists(filename) to detect for the file and then if not present, let the user download it. Example:
$killApp = "C:\WINDOWS\KILL.EXE";
if (file_exists($killApp)) {
# continue
} else {
# show message and link to kill.exe download
}
superzouz is at hotmail
11-Oct-2003 12:46
-- Catching COM events --
Hello everyone.
Anyone who did VB + COM would know something is missing here: events!
Here's how to catch IE events using some undocumented functions:
----------
class ieSinker {
var $terminated = false;
function TitleChange($text) {
echo("title has changed: $test \n");
}
function OnQuit() {
echo "Quit!\n";
$this->terminated = true;
}
}
$ie = new COM("InternetExplorer.Application");
$ieSink =& new ieSinker();
com_event_sink($ie, $ieSink, "DWebBrowserEvents2");
$ie->navigate(' PATH TO YOUR HTML FILE GOES HERE! ');
$ie->visible = True;
while(!$ieSink->terminated) {
com_message_pump(10);
}
----------
Works perfect for me with php 4.3
You can find more info on the undocumented functions in the YACL documentation.
Note the "DWebBrowserEvents2" interface. You can find more information about these in the microsoft platform SDK documentation, under "web development". Or maybe they have a smaller web development SDK? I wasn't able to use any other interface, so what I do is send messages from IE to the PHP script by changing the title of the html document with JavaScript.
By the way, I cant take credit for the above code, I stole it from some website of which I lost the address.
Thats it... bye...
03-Oct-2003 07:55
Convert Microsoft word document .DOC to adobe acrobat .PS or .PDF files:
Drawback: if any dialog boxes pop up, the conversion will become non-automated.
<?
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 1;
$word->ActivePrinter = "Acrobat Distiller";
$word->Documents->Open($input);
$word->ActiveDocument->PrintOut(0, 0, 0, $output);
$word->Quit();
$word->Release();
$word = null;
?>
court shrock
26-Sep-2003 12:24
took me a while until I found out how to loop through COM objects in PHP.... in ASP, you use something like:
<%
set domainObject = GetObject("WinNT://Domain")
for each obj in domainObject
Response.write obj.Name & "<br>"
next
%>
I finally found a note in a PHP bogus bug report that said you needed to do something like this (this is using ADSI):
<?php
$adsi = new COM("WinNT://Domain");
while($obj = $adsi->Next()) {
echo $obj->Name.'<br>';
}?>
Also, you can access the IIS metabase by doing something like the following:
<?php
$iis = new COM("IIS://localhost/w3svc");
while($obj = $iis->Next()) {
if ($obj->Class == 'IISWebServer') {
$site = new COM("IIS://Localhost/w3svc/".$obj->Name);
echo 'serviceID ('.$obj->Name.'): '.$site->ServerComment.'<br>';
$bindings = $site->ServerBindings;
echo '<ul>';
foreach($bindings as $binding) {
list($ip, $port, $hostHeader) = explode(':', $binding);
echo "<li>$ip:$port -- $hostHeader</li>";
}echo '</ul>';
unset($site);
}}unset($iis);
?>
mkcostello at hotmail dot com
22-Sep-2003 04:35
Took me a while to work this out as there is very little help available. Accessing com variables that are multi arrays can prove tricky.
e.g.
$ex = new COM("application");
$ex->Stock->stSalesBands
is an array A-H [stPrice,stCurrency]
php chucks out an error on this:
$ex->Stock->stSalesBands(C)->stPrice;
so, you have to do this
$tmp = $ex->Stock->stSalesBands(C);
echo $tmp->stPrice;
unset($tmp)
php at dictim dot com
06-Sep-2003 08:17
This took me days to work out how to do so I gotta share it:
How to get the word count from a MS Word Document:
#Instantiate the Word component.
$word = new COM("word.application") or die("Unable to instantiate Word");
$word->Visible = 1;
$word->Documents->Open("c:/anydocument.doc");
$temp = $word->Dialogs->Item(228);
$temp->Execute();
$numwords = $temp->Words();
echo $numwords;
$word->Quit();
Note that this is the only way to get the word count accurately:
$word->ActiveDocument->Words->Count;
Will see all carriage returns and punctuation as words so is wildy innaccurate.
seidenberg at cf-mail dot net
11-Jul-2003 10:36
open PDF Documents with Internet Explorer
$browser = new COM("InternetExplorer.Application");
$browser->Visible = true;
$browser->Navigate("path_to_your_pdf_document");
this works for me with php-gtk
tomas dot pacl at atlas dot cz
16-Jun-2003 01:07
Passing parameters by reference in PHP 4.3.2 (and in a future releases of PHP )
In PHP 4.3.2 allow_call_time_pass_reference option is set to "Off" by default and future versions may not support this option any longer.
Some COM functions has by-reference parameters. VARIANT object must be used to call this functions, but it would be passed without an '&' before variable name.
Example:
$myStringVariant = new VARIANT("over-write me", VT_BSTR);
/* works */
$result = $comobj->DoSomethingTo($myStringVariant );
/* works only with allow_call_time_pass_reference option set to "On" and may not work in a future release of PHP */
$result = $comobj->DoSomethingTo(&$myStringVariant );
The value in the variant can be retrieved by:
$theActualValue = $myStringVariant->value;
php at racinghippo dot co dot uk
23-Mar-2003 01: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.
alex at domini dot net
05-Mar-2003 10:55
To manage the Windows Register at HKEY_LOCAL_MACHINE\SOFTWARE\ use these functions:
<?php
function rtv_registre($aplicacio, $nom)
{
Global $WshShell;
$registre = "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\" . $nom;
$valor = $WshShell->RegRead($registre);
return($valor);
}
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);
}
$WshShell = new COM("WScript.Shell");
?>
richard dot quadling at carval dot co dot uk
26-Feb-2003 01: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
set_time_limit(0);
error_reporting(E_ALL);
$empty = new VARIANT();
com_load_typelib('Word.Application');
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";
$word->Documents->Open('C:/Unfilled.DOC');
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); $word->Selection->TypeText($_GET['YourName']);
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);
$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.
pchason at juno dot com
11-Dec-2002 07: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
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
$i = 0;
$columns = 5;
while (!$rs->EOF){
if($i == 0){
echo "<tr>";
}
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
}
}
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>
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
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);
}
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
$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);
$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.
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.
<?
$dbc = new COM("ADODB.Connection") or die ("connection create fail");
$dbc->Provider = "MSDASQL";
$dbc->Open("FoxDatabase");
$RSet = new COM("ADODB.Recordset");
$cm = new COM("ADODB.Command");
$cm->Activeconnection = $dbc;
$cm->CommandText = "Insert Into testtable ( mycharfield,mymemofield) VALUES (?,?)" ;
$cm->Prepared = TRUE;
$par01 = $cm->CreateParameter('ppar01',129,1,50,'ABCDEFGHIKL');
$cm->Parameters->Append($par01);
$par02 = $cm->CreateParameter('ppar01',129,1,50,'123456789012346789');
$cm->Parameters->Append($par02);
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 '<BR>';
$RSet->movenext();
}
$RSet->close;
$dbc->close;
$cm->close;
$RSet = null;
$dbc = null;
$cm = 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!!!
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;
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();
?>
madon at cma-it dot com
07-Mar-2002 08:59
I thought this excel chart example could be useful.
Note the use of Excel.application vs Excel.sheet.
<pre>
<?php
print "Hi";
$exapp = new COM("Excel.application") or Die ("Did not connect");
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";
$wkb=$exapp->Workbooks->add();
print "we opened workbook<BR>";
$ex->Application->Visible = 1; print "we made excell visible<BR>";
$sheets = $wkb->Worksheets(1); print "selected a sheet<BR>";
$sheets->activate; print "activated sheet<BR>";
$sheets2 = $wkb->Worksheets->add(); print "added a new sheet<BR>";
$sheets2->activate; print "activated sheet<BR>";
$sheets2->name="Report Second page";
$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name<BR>";
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
$cell = $sheets->Cells($i,5) ; $cell->activate; $cell->value = $i*$i; }
$ch = $sheets->chartobjects->add(50, 40, 400, 100); $chartje = $ch->chart; $chartje->activate; $chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); $chartje->setsourcedata($selected); print "set the data the chart uses <BR>";
$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
$wkb->SaveAs($file_name); print "saved<BR>";
$exapp->Quit();
unset($exapp);
?>
</pre>
Alex Madon
darkwings at 263 dot net
28-Feb-2002 05: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."<br>";
$rec->movenext();
}
$rec->close();
$dbconn->close();
but there's still a little question of working with the image field of mssql server.
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.
| |