How to force Excel process to quit after COM automation? - php

In PHP I create an XLS-file using COM-object.
$excel = new COM("Excel.Application") or die("Excel is not installed!");
$excel->WorkBooks->Add();
...
$excel->WorkBooks[1]->SaveAs($path);
$excel->Quit();
$excel->Release();
$excel = null;
After this code has been run, Excel.exe process still be in memory for ~ 6 minutes. How to force this process to quit immediately?

You are using COM objects, so you must be talking about php on Windows. Basically, you can kill tasks using the command line tool taskkill. You can call that using the php command shell_exec, like
shell_exec('taskkill /F /IM "excel.exe"');
If you don't have the rights (but I believe you should because you started this process), run the cmd line using runas.
BUT! You are using php, so if you are running this in a web environment and people are accessing your website simultaneously, you might have multiple instances of Excel running. If that is the case, you'd have to figure out which one you want to kill.

The process sticks around for some time in case another "Excel.Application" object is requested, in which case we can avoid the cost of starting a new process and loading all the DLLs.
I'd just see it as a feature.

There is another way...
Try Uninitializing COMS. Instead of doing it just once, do it 4 times. This was established through trial and error so I do not have a valid reason for it except that it works. However, this does not work all the time. It might just work in your case

Related

Executing a program from PHP hangs APACHE

Hello and thank you in advance for your interest.
During the past two weeks I've been struggling with something that is driving me nuts. I have APACHE (2.2.22) and PHP (5.4.3) installed on my Windows box and I'm trying to call a program from a PHP script which calls another program at the same time. Both programs are written in C/C++ and compiled with MINGW32. Regarding to Windows version, I've tested Windows 2003 Server and Windows 7 Professional and both give me the same problems.
Let me introduce these two programs:
1) mytask.exe: this is a program that is to be executed in background and that periodically populates its status to a file.
2) job.exe: this is the program I want to call from the PHP script. Its goal is to spawn mytask.exe as an independent process (not as a thread).
If I run from a Console window the command below, then job.exe immediately returns and leaves mytask.exe running on the background until it terminates.
> job.exe spawn mytask.exe
jobid=18874111458879FED
Note that job.exe dumps an identifier which is used to manage mytask.exe. For example:
> job.exe status 18874111458879FED
RUNNING
I've checked that if I run the first command from a PHP script, the PHP script randomly blocks forever. If I look to the Windows's task manager, I can see that job.exe is there in a zombie-like state. I can assert that job.exe effectively reaches the usual return 0; statement in its main() routine, so it seems to be something under the wood, in the C runtime.
Furthermore, if I write a simple mytask.exe that simply sleeps for 10 seconds then the PHP script blocks for 10 seconds too (or blocks forever following the random behavior I've just mentioned). In other words, I have no way to make job.exe spawning a process without waiting for it to end, when I call job.exe from a PHP script.
So: there's something I'm doing wrong when spawning mytask.exe and, now, here comes the second part of this digression.
I use the WINAPI function CreateProcess() to spawn the tasks from job.exe. As of the MSDN documentation, I call CreateProcess with bInheritHandles = FALSE, to avoid the child process to yield I/O deadlocks with the PHP script. I also close the process handles returned by CreateProcess() in the PROCESS_INFORMATION structure. The only thing I don't do is waiting for the process to end. On the other hand, regarding to the PHP side, I've tried both exec() and proc_open() PHP functions to call job.exe with no success.
My last observations, though, seem to be in the right way, yet they do not convince me because I don't understand why they work somehow. The fact is that if mytask.exe does fclose(stdout) before sleeping, then the PHP script returns immediately. BUT, HOW??? I told CreateProcess() to not inherit handles, so why am I getting these results? Anyway, I cannot stick with this patch because programs launched by job.exe may not know about who is calling them, so closing stdout from those programs is not a good solution. In UNIX, things are so simple... One just calls fork(), closes standard streams and then calls execve to call the program. In Windows, I've also tried to create a wrapper thread with CreateThread() (to emulate fork()) and then call CreateProcess() from that thread after closing standard streams... but that closed the streams of job.exe too!
All this question could be synthesized in a single one: how can I execute from PHP a program that creates other processes?
I hope somebody could shed some light on this issue... Thank you very much!
I think I've nailed the solution, which is divided in two parts:
1) Regarding the fact the main process stops until the child process ends.
As of MSDN documentation, this is the definition of CreateProcess():
BOOL WINAPI CreateProcess(
_In_opt_ LPCTSTR lpApplicationName,
_Inout_opt_ LPTSTR lpCommandLine,
_In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes,
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ BOOL bInheritHandles,
_In_ DWORD dwCreationFlags,
_In_opt_ LPVOID lpEnvironment,
_In_opt_ LPCTSTR lpCurrentDirectory,
_In_ LPSTARTUPINFO lpStartupInfo,
_Out_ LPPROCESS_INFORMATION lpProcessInformation
);
As I said in my question, I pass FALSE to bInheritHandles, but I was also passing 0 to dwCreationFlags. After a little bit of more research, I found that there's a flag called DETACHED_PROCESS, for which MSDN says:
For console processes, the new process does not inherit its parent's console (the default). The new process can call the AllocConsole function at a later time to create a console. For more information, see Creation of a Console.
Now, job.exe returns immediately despite the fact the child process continues its execution.
2) Regarding the fact the PHP script randomly hangs when calling exec()
It seems to be a bug of PHP. Running exec() family functions in the context of a PHP session may make APACHE to randomly hang, being necessary to restart the server. I found a thread in the Internet in which a user noticed that closing the session (thru session_write_close()) before calling exec() would prevent the script from hanging. The same applies for the proc_open/proc_close functions. So, my script now looks like this:
session_write_close(); //Close the session before proc_open()
$proc = proc_open($cmd,$pipedesc,$pipes);
//do stuff with pipes...
//... and close pipes
$retval = proc_close($proc);
session_start(); //restore session
Hope this helps.

Boost Apache2 up to 4 cores usage, running PHP

READ FURTHER BELOW at CLI, FOR THE CLI QUESTION, WHICH JUST ADDED TO THE CONVERSATION! THX!
I have written a script which processes an xml file of around 160'000 entries with 48.1MB and a text file of 150'000 entries with 31.1MB, including some directory searches for external files, heavy interlinking and recursive checks and the result formatted and all saved into html files.
Surely, I did review the program couple times and ended up with the most efficient code I could think of. This is a local program and the generator doesn't need to run regularly. One could argue that I should use an other language than PHP, but PHP with simplexml, etc. just works the best for me and for this purpose. Also a set_time_limit('70000') doesn't bother me.
Although, here my question, is it possible to make the apache2 on my linux system, use my 4 CPU cores running my PHP script?
Even if I split the process and make several request's simultaneously, the CPU usage can't go above 1 CPU at a time.
I googled this topic but couldn't find a solution, so I may have to just run it over night, even though, I would appreciate some help to boost that thing!!!
ADDED INFO - And here a picture of my processes:
CLI:
I need to call my index.php in the linux terminal to execute. But I also wanna send four post variables ($_POST['example']) to the script. On top of that, I am looking for having my echos presented in some output file. Could anyone help quickly with the terminal command and the php command to track those 4 post variables inside:
if (PHP_SAPI === 'cli')
{
// ...
}
? ...sorry but this is my first php-cli interaction. Thx!
No, a single PHP script will never use multiple threads and thus always run on single core.
Depending on how much the things you do depend on each other you couldn't easily split them on multiple threads anyway.
EDIT: Author's response
This is not a solution but a nice workaround. I clone my virtual machine with the linux/apache2 install to kick in the same process but different parts of the file/process on different vm's, which lets the host system apply one core for each virtual system, that way I could break down the process time by around the factor 4. Thanks for your posts!
===============
If it's local, and you want to run it every now and then, you should probably just invoke it from a cron job. That way, you can spawn a process for each task you are doing. If you really do want to use PHP for it, you can even invoke PHP to do it from the cron line.
None the less, it sounds like you're doing an inherently single-threaded process anyway, and if you want it faster, should probably use something that isn't PHP for this.
Maybe you can use Spork! It's a php lib allowing you to fork the php process into multiple ones.
<?php
use Spork\Deferred\DeferredFactory;
use Spork\ProcessManager;
$manager = new ProcessManager(new DeferredFactory());
$manager->fork(function() {
// do something in another process!
})->then(function($output, $status) {
// do something in the parent process when it's done!
});
https://github.com/kriswallsmith/spork
SOLUTION, THX TO ThiefMaster and Zebediah49 recommending cli and my friend who supported me with the links: http://ch.php.net/manual/en/reserved.variables.argv.php / http://ch.php.net/manual/en/function.getopt.php
and here how I call the php through cli:
//whenRunFromCLI
//callCLI
//php index.php './data/xyfullFile1.xml' './data/xxfullFile2.utf' 0 60000
//php index.php './data/xyfullFile1.xml' './data/xxfullFile2.utf' 60000 120000
//php index.php './data/xyfullFile1.xml' './data/xxfullFile2.utf' 120000 all
if (PHP_SAPI === 'cli'){
$_POST['xml'] = $argv[1];
$_POST['example'] = $argv[2];
#$_POST['rangeFrom'] = $argv[3];
#$_POST['rangeTo'] = $argv[4];
}
and the Result of calling the php file in three terminals:
I know, I must give some more RAM to my virtual machine, lucky that I still have 8GB spare ;-)
Cheers and peace!

How do I run a PHP script continuously on localhost?

I have a script which crawls info using API. What I want is to run this script continuously to grab data and store it on my local machine. I configured machine as localhost and installed phpmyadmin and MySQL.
You probably will want to run it from the command line. Put your code in some kind of loop to always keep it running, or schedule it to run as a cron job / scheduled task.
Wrap your main code, except for functions, classes, etc, in this:
while (true) {
and this:
sleep(2);
}
Then run it from the command line, using:
$ php myscript.php
If using Windows, you manually have to add php to your PATH. I don't know Windows (using a Mac all my life) but I guess you can do this in My Machine's Properties. :)
Read about set_time_limit, or modify max_execution_time value in your php.ini file .
Instead of a php loop, use a batch file loop. .
This gets around any set_time_limit , maximum memory etc problems. If php crashes, no problem, a new instance will be started immediately.
#echo off
:loop
php myScrapeScript.php
goto loop;

How can I troubleshoot why my PHP script won't work in cron when it does from the command line?

I've got a script that calls two functions, A and B, from the same class. A creates an Amazon virtual server and B destroys one, both via shell_exec()'s of Amazon's command line tools. The script, doActions.php, pulls actions from a queue. If the action is "create" it creates an instance; when the action is "destroy" it kills one.
The script works fine to execute both A and B when I execute it from the command line: php script.php.
When I put it on a cron, it runs but only successfully runs the B function. It deletes destroys instances but won't create them.
The point of failure is clearly function B. It chokes at the first and most important shell_exec, returning and echoing nothing.
echo $string = shell_exec('/home/user/public_html/domain.com/private/ec2-api-tools/bin/ec2-run-instances ami-23b6534a -k gsg-keypair -z us-east-1a');
Unless you know something specific about the way Amazon's command line tools work, please suggest to me reasons why a shell_exec might work in one case and not the other.
Another shell_exec in the same place behaves as expected:
echo $string = shell_exec ('echo overflow');
My guess is that it has to do something with permissions. But when I have it run shell_exec('whoami') it return "root," and when I su and run the command it works fine. I'm having a hard time thinking of creative ways to troubleshoot why my PHP script won't work in cron when it does from the command line. Can you suggest some?
When something runs from the command line but refuses to do so within cron, it's often an environment issue (path or some other environment variable that's needed by the code you're running).
For a start you should modify the script to output the current environment (shell_exec('env')?) at the very top and examine the output from the command line and cron.
Hopefully, there will be something obvious such as AMAZON_EC2_VITAL_VAR but, if not, you should move the cron environment towards your command line one, one variable at a time, until it starts working.
A quick test to ascertain this. From your command line, do:
env >/tmp/pax_env.sh
Then run your PHP script from a shell script which first executes:
. /tmp/pax_env.sh
so that the environments are identical.
And keep in mind that su on its own doesn't give you the same environment as you'd get from logging in directly as a specific user (su - does, I think). You may want to check the behaviour for when you log in as root directly.
Re your comment:
Yes, I do believe you've got it. I'm likely going to mark your answer as correct but need you to suffer through a few addendums about your clever solution. First of all, what's the best way to execute the pax_env.sh script? Does shell_exec() work?
Never let it be said I didn't work for my money :-) No. The shell_exec will almost certainly be running a sub-shell so the variables would be set in that sub-shell but would not affect the PHP parent process.
My advice, if you wanted all those variables set, would be to create a shell-script consisting of all the commands in /tmp/pax_env.sh (probably prefixing each with export) followed by the command you currently have running in cron, something along the lines of:
export PATH=.:/usr/bin
export PS1=Urk:
export PS2=MoreUrk:
/home/user/pax/scriptB.php
Then run that script from cron rather than /home/user/pax/scriptB.php directly. That will ensure the environment is set up before your PHP code is called.
Astute readers will have noticed the phrase "if you wanted all those variables set" above. I don't personally think it's a good idea to dump all your command line variables into the shell script for the cron job. I'd prefer to actually find out which ones are needed and only include those. That lessens the pollution your cron job has to run under. For example, it's unlikely that the PS1/PS2 prompt variables will be required for your PHP script.
If it works, you can set all the environment variables - I just prefer the absolute minimum so I don't have to worry too much when things change.
A way of finding out what's needed is to comment out one export at a time until your script breaks again. Then you know that variable is needed. Once it works with the maximum amount of export statements commented out, you can just delete those commented export statements altogether and what remains, however improbable, must be okay (with apologies to Sir Arthur Conan Doyle).

Forking in PHP on Windows

We are running PHP on a Windows server (a source of many problems indeed, but migrating is not an option currently). There are a few points where a user-initiated action will need to kick off a few things that take a while and about which the user doesn't need to know if they succeed or fail, such as sending off an email or making sure some third-party accounts are updated. If I could just fork with pcntl_fork(), this would be very simple, but the PCNTL functions are not available in Windows.
It seems the closest I can get is to do something of this nature:
exec( 'php-cgi.exe somescript.php' );
However, this would be far more complicated. The actions I need to kick off rely on a lot of context that already will exist in the running process; to use the above example, I'd need to figure out the essential data and supply it to the new script in some way. If I could fork, it'd just be a matter of letting the parent process return early, leaving the child to work on a few more things.
I've found a few people talking about their own work in getting various PCNTL functions compiled on Windows, but none seemed to have anything available (broken links, etc).
Despite this question having practically the same name as mine, it seems the problem was more execution timeout than needing to fork. So, is my best option to just refactor a bit to deal with calling php-cgi, or are there other options?
Edit: It seems exec() won't work for this, at least not without me figuring some other aspect of it, as it waits until the call returns. I figured I could use START, sort of like exec( 'start php-cgi.exe somescript.php' );, but it still waits until the other script finishes.
how about installing psexec and use the -d (don't wait) option
exec('psexec -d php-cgi.exe somescript.php');
Get PSExec and run the command:
exec("psexec -d php-cgi.exe myfile.php");
PSTools are a good patch in, but I'll leave this here:
If your server runs windows 10 and it has the latest updates, you can install a Linux subsystem, which has its own Kernel that supports native forking.
This is supported by Microsoft officially.
Here's a good guide on how to do it.
Once you've installed the subsystem itself, you need to install php on the subsystem.
Your windows "c:\" drive can be found under "/mnt/c", so you can run your php from the subsystem, which supports forking (and by extension the subsystem's php can use pcntl_fork).
Example: php /mnt/c/xampp/htdocs/test.php
If you want to run the subsystem's php directly from a windows command line you can simply use the "wsl" command.
Assuming you're running this from under "C:\xampp\htdocs\"
Example: wsl php main.php
The "wsl" command will resolve the path for you, so you don't need to do any dark magic, if you call the command under c:\xampp\htdocs, the subsystem will resolve it as "/mnt/c/xampp/htdocs/".
If you're running your server as an apache server, you don't really need to do anything extra, just stop the windows apache server and start the linux one and you're done.
Obviously you'll need to install all the missing php modules that you need on the subsystem.
You can create a daemon/background process to run the code (e.g. sending emails) and the request would just have to add items to the queue, let the deamon do the heavy lifting.
For example, a file send_emails.bat:
cls
C:\PHP533\php.exe D:\web\server.php
exit
open windows task scheduler, and have the above send_emails.bat run every 30 minutes. Make sure only one instance runs at a time or you might run each task in multiples, or send each email twice. I say 30 minutes in case something breaks temporarily (memory issues, database unavailable, etc), it will re-start every 30 minutes rather than having a never ending process that just stops. The following is a skeleton daemon... not complete or tested I am just typing out an example:
<?php
set_time_limit(60*30); // don't run
$keepgoing = true;
$timeout = time()+ 60*29; // 29 minutes
while(time() < $timeout)
{
// grab emails from database
$result = $db->query('select subject, body, to_email FROM email_queue');
if($result->num_rows == 0)
{
sleep(10); // so we are not taxing the database
}
else
{
while($row = $result->fetch_assoc())
{
// send email
}
}
}
exit;
?>
Finally you just need the request to add the item to the queue in a database, and let the daemon handle the heavy lifting.
$db->query('insert into email_queue(to,subject,body) values ('customer#email.com','important email','<b>html body!</b>');

Categories