php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #9852 Header redirect and db connection cause "CGI misbehaved"
Submitted: 2001-03-19 22:41 UTC Modified: 2003-03-14 18:52 UTC
Votes:26
Avg. Score:4.9 ± 0.4
Reproduced:24 of 25 (96.0%)
Same Version:18 (75.0%)
Same OS:23 (95.8%)
From: ron dot baldwin at sourceprose dot com Assigned:
Status: Closed Package: IIS related
PHP Version: 4.2.1 OS: Windows 2000
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: ron dot baldwin at sourceprose dot com
New email:
PHP Version: OS:

 

 [2001-03-19 22:41 UTC] ron dot baldwin at sourceprose dot com
Under the category of "You Can Never Have Too Much Information On A Bug", here is my experience with the "CGI App Misbehaved" bug (related bug reports: #8571 and #8744).

Bug report summary:
A PHP script that sends a 'Location' header directive and makes a database connection causes IIS to intermittently return a 'Gateway Error 502' when the client browser asks for the page specified in the redirect.  The address bar will correctly show the page that should have loaded when the error is displayed, and pressing F5 (refresh) will correctly load the page.  Note that the error is (seemingly) completely random, sometimes you get it, other times the script works correctly.  The error message text is:

   -- Begin --
   CGI Error
   The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
   --  End  --

This error depends on:
1) Using PHP in CGI mode (i.e. using php.exe, the ISAPI dll does not seem to produce this error, although it has it's own problems).
2) A PHP script that connects to a database (tested both mssql_connect and odbc_connect) *and* sends a 'Location:' header.  If the script redirects to something other than a .php file (i.e. .html or .pdf) or does not connect to the database, the error will not occur.
3) A successful db connection.  If the db connect call fails (due to bad password, etc.), the redirect always works.

This error does *not* depend on:
1) A fully qualified 'Location' header.  The following also fails:
   header('Location: http://10.0.0.30/test/done.php');
2) The relative order of the header() and xxx_connect() calls in 'doit.php'.  I wouldn't expect the order to affect the result, but I checked it anyway.

Interesting note: While upgrading the server to SP1 to see if it had any affect on this bug, I continued to test while it was in the process of performing the upgrade.  It was very difficult (I gave up) trying to get the error.  The CPU was at 100% due to the upgrade which (obviously) caused the web server performance to suffer.  Combined with the fact that it occurs randomly anyway, this suggests that it may have something to do with the timings between the request for doit.php, execution of doit.php, and the request for done.php.


Hardware/Software:
   Web server:
      Win2000 Server (with and without SP1)
      IIS 5.0
      PHP 4.0.4pl1 (CGI mode)

   Database server:
      WinNT 4.0 SP6
      MS-SQL 7.0

   Client:
      Win2000 Professional SP1
      IE 5.5 SP1


========================================
Test scripts
========================================
start.php
----------------------------------------
<html><head><title>Test</title></head>
<body>
<a href="doit.php">Do test</a>
</body></html>
----------------------------------------
doit.php
----------------------------------------
<?php
// Either connect line will cause the error
$conn = mssql_connect('host', 'uid, 'pwd') or die("couldn't connect");
//$conn = odbc_connect('dsn', 'uid', 'pwd') or die("couldn't connect");

header('Location: done.php');
?>
----------------------------------------
done.php
----------------------------------------
<html><head><title>Test</title></head>
<body>
Test complete
<p><a href="start.php">Reset test</a>
</body></html>
========================================

Here are actual HTTP headers recorded using a packet sniffer:

========================================
Scenario #1 - CGI Error Occurs
========================================
Client request
----------------------------------------
GET /test/doit.php HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, */*
Referer: http://10.0.0.30/test/start.php
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
Host: 10.0.0.30
Connection: Keep-Alive
----------------------------------------
Server response
----------------------------------------
HTTP/1.1 302 Object Moved
Location: done.php
Server: Microsoft-IIS/5.0
Content-Type: text/html
Connection: close
Content-Length: 131
----------------------------------------
Client request (automatic IE request)
----------------------------------------
GET /test/done.php HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, */*
Referer: http://10.0.0.30/test/start.php
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
Host: 10.0.0.30
Connection: Keep-Alive
----------------------------------------
Server response (Incorrect response)
----------------------------------------
HTTP/1.1 502 Gateway Error
Server: Microsoft-IIS/5.0
Date: Tue, 20 Mar 2001 00:30:10 GMT
Connection: close
Content-Length: 215
Content-Type: text/html
----------------------------------------
Client request (F5 - refresh)
----------------------------------------
GET /test/done.php HTTP/1.1
Accept: */*
Referer: http://10.0.0.30/test/start.php
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
Host: 10.0.0.30
Connection: Keep-Alive
----------------------------------------
Server response
----------------------------------------
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Tue, 20 Mar 2001 00:30:11 GMT
Connection: close
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
========================================


========================================
Scenario #2 - Correct operation
========================================
Client request
----------------------------------------
GET /test/doit.php HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, */*
Referer: http://10.0.0.30/test/start.php
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
Host: 10.0.0.30
Connection: Keep-Alive
----------------------------------------
Server response
----------------------------------------
HTTP/1.1 302 Object Moved
Location: done.php
Server: Microsoft-IIS/5.0
Content-Type: text/html
Connection: close
Content-Length: 131
----------------------------------------
Client request (automatic IE request)
----------------------------------------
GET /test/done.php HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, */*
Referer: http://10.0.0.30/test/start.php
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
Host: 10.0.0.30
Connection: Keep-Alive
----------------------------------------
Server response (Correct response)
----------------------------------------
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Tue, 20 Mar 2001 00:33:02 GMT
Connection: close
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
========================================

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-03-27 13:16 UTC] preston dot bannister at cox dot net
I can reproduce the problem with a simple "bounce" page (used for measuring roundtrip times).  With two active browser windows requesting the same page, I see this error repeat (apparently at random) on one out of 10-40 thousand requests.

This is with PHP 4.1.2 on Windows 2000 Professional w/ IIS 5 and all the current updates from Windows Update.

bounce.php
----------
<html>
<head>
<title>BOUNCE</title> 
<?php 
list($usec, $sec) = explode(" ",microtime()); 
$now = intval(1000*((float)$usec + (float)$sec)); 
$i = (isset($i) ? $i : 0);
$n = (isset($n) ? $n : 10);
$s = (isset($s) ? $s : 0);
$r = (isset($r) ? $r : 0);
?>
<?php if (0 == $i) { ?>
<meta http-equiv="Refresh" content="0; URL=bounce.php?s=<?= $s ?>&r=<?= $r ?>&i=1&t=<?= $now ?>">
<?php } else if ($i < $n) { ?>
<meta http-equiv="Refresh" content="0; URL=bounce.php?s=<?= $s ?>&r=<?= $r ?>&i=<?= 1 + $i ?>&t=<?= $t ?>">
<?php } else { ?>
<?php
$e = $now - $t;
$r = $r + $n;
$s = $s + $e;
?> 
<meta http-equiv="Refresh" content="3; URL=bounce.php?s=<?= $s ?>&r=<?= $r ?>">
<?php } ?>
</head>
<body>

<?php if ($i < $n) { ?>
<h1>BOUNCING</h1>
<?php } else { ?>
<h1>BOUNCE</h1>
<table border=1>
<tr><th>milliseconds</th><th>requests</th></tr>
<tr><td><?= intval($e/$n) ?></td><td><?= $n ?></td><td>latest</td></tr>
<tr><td><?= intval($s/$r) ?></td><td><?= $r ?></td><td>cumulative</td></tr>
</table>
<?php } ?>

</body>
</html>
 [2002-04-22 17:50 UTC] sp at m-me dot dk
It seems to be a timing problem (the PHP script outruns the IIS/MSSQL or something). I came up with a simple solution to this by inserting a short delay before every location header in my scripts.

I successfully made the workaround by using a function from a user comment on the http://www.php.net/manual/en/function.usleep.php page

The function was:
------------------------------
function usleepWindows($usec) {
  $start = gettimeofday();
  do {
    $stop = gettimeofday();
    $timePassed = 1000000 * ($stop['sec'] - $start['sec'])
                  + $stop['usec'] - $start['usec'];
  }
  while($timePassed < $usec);
}
------------------------------

Every header call should then look like this:
------------------------------
usleepWindows(200000);
header("Location: http://www.myserver.dk/mypage.php");
exit;
------------------------------

/watson
 [2002-05-28 06:10 UTC] scott at datalink dot net dot au
I have the same problem, but I have some more interesting facts to add...

I can reproduce it with mssql or odbc drivers, and intererstingly I can get it breaking without using a header redirect.

I have an application that uses a frameset, and it appears that sometimes (2 out of 3 times) it will give me the CGI error in multiple frames, even though I've switched from header redirects to javascript redirects.   The URL changes at the browser, and it's the target page that fails to load - not the page with the redirect code.

I have also had it failing on another page that used the IIS custom error page functionality (i.e. replacing a 404 error with a nice custom page)...again, a "fast redirect" issue, just like the original bug reporter.

I do believe it is a timing problem - for me it only fails on a fast dual-processor production server, but works fine on my slower single-processor development server.

It also works fine if I shift the production server to a MySQL database.

Note that I tried using the slowdown function above, but it didn't work for me - perhaps multiple simultaneous page loads from the frameset also breaks it?

By the way, mine fails on version 4.2.1 (released May 2002), so obviously this little bug hasn't been caught for over a year.

I read above that the ISAPI version doesn't seem to do it, so I'll look at implementing ISAPI for this job.   However, that could mean that it's to do with the persistant database connection, as the ISAPI module remains loaded between page views.
 [2002-05-28 08:30 UTC] scott at datalink dot net dot au
I tried the ISAPI module, but that died in *lots* of other ways - I get the impression I should stay with CGI :(

I've since tried playing with the mssql parameters in php.ini (thought persistent connections may be the problem) with no success.

I think I may try that slowdown script, but against all queries - it didn't work for me before the redirect - I don't always have a redirect :(

Any other suggestions welcome...
 [2002-05-28 09:16 UTC] scott at datalink dot net dot au
Some further info on the problem:

I applied the slowdown script after each query (in the simpleQuery method of PEAR's mssql driver) but I still got the occasional CGI Error (and it was awfully slow, too).

I then applied the slowdown script at the start of each script, but still to no avail.

What I did notice was that it did help the problem, but not eliminate it.    My problem was still there when I refreshed my entire frameset (which caused 6 scripts to run mssql db commands simultaneously).   Often 2 or 3 of these scripts failed with CGI errors.
 [2002-06-02 17:09 UTC] theo dot schoeberl at tssystems dot de
We have the same problem (see Bug #11788).

Loading the page outside the local network (over the internet) works in 99%.

Within the local network the problem occurs on nearly ever 2nd load. After a relaod request of the individual frame (context menu - right mouse buttom) it works fine!

It seems that the problem depends from the line speed and not the machines speed.
 [2002-06-02 20:16 UTC] scott at datalink dot net dot au
Another observation - when my script runs correctly, it takes a second to execute.   When the CGI error occurs, it returns very quickly.

This indicates that it fails on or around the first db statement (I'm guessing around the mssql_connect() statement).

It's also consistent with the other users' comments on redirecting seeming to fail with a CGI error, but the location bar of the browser changing.   The redirect *is* working, but it's the second page that fails (probably around reconnecting to the database).
 [2002-06-04 10:35 UTC] michael dot lidgren at journalistgruppen dot se
My uneducated guess would be that two database connections in rapid succession produces the error. Just for fun, I tried:

$aconn = mssql_pconnect($db_servername, $login, $passwd);
$bconn = mssql_pconnect($db_servername, $login, $passwd);

... and got this interesting error:
<B>Warning: Unknown persistent list entry type in module shutdown (22) in Unknown on line 0</B>

--Michael
 [2002-06-04 10:45 UTC] michael dot lidgren at journalistgruppen dot se
This is from the mailing list; i think it might be relevant to this bug:

<snip>

Hi,
	
we've a lot of trouble using PHP on IIS5/Win2000sp2-Server.

The machine is a 2xPIII(1,3Ghz), 1280MB RAM, really fast.
The problem is that sometimes the IIS doesn't execute the php.exe, instead it shows a "CGI Application error - wrong or incomplete header data...." This problem only occurs on this fast server and only with a website that uses frames.
I suppose that the IIS launches different threads to render the frames and isn't able to do the IO to the php.exe for every thread.
To test this we wrote a little script wich shows 12 Frames, filled with a little PHP-Skript that only shows one line of text.
On the slow machine theres no problem. On the fast machine, same software, we get the cgi-error in round about every 50th or 60th frame (refresh..)

Regards,

Jan Schmitz

</snip>

--Michael
 [2002-06-04 16:04 UTC] theo dot schoeberl at tssystems dot de
We have tested usleepWindows(200000) and it works for us.

It also works within frames on a virtual site!
 [2002-06-18 23:07 UTC] scott at datalink dot net dot au
Kai, when you mentioned 'under 2MBit' were you meaning 2 Mbit/s or 2 MB/s?    IIS prompts for KB/s, so I assumed for your solution you limited it to 2,048 KB/s?

For our machine, we can limit it to < 350 KB/s and it appears to solve the problem, but I haven't stress-tested the server yet.   This is good news for us - we can get paid for our project.   But this bug will likely re-appear as server equipment gets faster.

In other news we've pulled down the PHP source and did some further debugging... we found:

1.  The error occurs on the first 'dbexec' command run in the mssql driver.   For example, in PHP it will not happen on a mssql_connect(), but on the *next* mssql command issued in that script (say a mssql_select_db() or a mssql_query()).    Our test script will run fine if we connect to mssql but don't use it in any way after that.

2.  We laced the PHP source with some fwrite()'s to stout to watch the flow of the code - when PHP failed, we didn't get any of these, not even the ones placed *before* the mssql_connect() function definition.   This may indicate that PHP is not crashing, but IIS may not even be loading it in the first place! (strangely seems to conflict with point 1).

3.  We can reproduce it quite freely under varying bandwidth and on fast and slow computers (happens more frequently on faster machines).   Limiting the bandwidth on IIS does seem to fix the problem (under single user situations)

4.  We have ported the same script to ASP without reproducing this bug.   ASP seems to run fine.

5.  We can reproduce it under ISAPI and CGI using our test script (below) - the ISAPI script fails less often than the CGI version, but it still fails.

6.  It breaks under ODBC, too.

IMHO, I believe that it is critical to the ongoing success of PHP to have it working with Windows 2000 and/or MSSQL.    Simply blaming it on Microsoft and closing the bug is unacceptable, especially as this bug seems to occur more often with faster servers.  This bug will hurt more and more people into the near future, and damage the reputation of this fine product (PHP, that is).

Our investigations do suggest that the bug is likely in IIS, but nevertheless it will hurt PHP more than Microsoft as the bug affects more people.    

With regards to your suggestion on PERL/ASP exhibiting the same problem, I haven't been able to reproduce it with them (if you supply your ASP test script, I'll test it with my config here).

I'd appreciate you marking this bug 'open' rather than 'bogus', as it needs to be solved regardless of who is to blame.

Best regards,
Scott

NB:  My company is working on the problem to try to solve it - I will post our findings or workarounds to this bug page.   If anyone knows of other related bugs I would appreciate it if you can post them here.

NB2: Has anyone had success with a Cygwin-compliled PHP?

---------- Test Harness Follows --------------

index.php:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>MSSQL Test</title>
	<script>
		var count = 0;
	</script>
</head>

<!-- frames -->
<frameset cols="20%,20%,20%,20%,20%">
    <frame name="frame1" src="mssql_test.php?j=<?php echo ++$j; ?>">
    <frame name="frame2" src="mssql_test.php?j=<?php echo ++$j; ?>">
    <frame name="frame3" src="mssql_test.php?j=<?php echo ++$j; ?>">
    <frame name="frame4" src="mssql_test.php?j=<?php echo ++$j; ?>">
    <frame name="frame5" src="mssql_test.php?j=<?php echo ++$j; ?>">
</frameset>

</html>

mssql_test.php:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
	<title>MSSQL Test</title>
	<script>
		top.count++;
	</script>
</head>
<body>
<?php
print "<h1>$j</h1>\n";
$dbConn = mssql_connect("localhost", "sa", "<password>");
mssql_select_db("cogs", $dbConn);
$result = mssql_query("SELECT * FROM site", $dbConn);

while ($array = mssql_fetch_row($result)) {
	print "<pre>";
	print_r($array);
	print "</pre>";
}

?>

<script>
	if (top.count == 5) {
		top.location = 'frameset.php?j=<?php echo $j ?>';
	}
</script>

</body>
</html>

---------- End test harness ----------
 [2002-06-21 03:10 UTC] davidr at gronks dot com
I have found that by removing anonymous IUSR permissions on the web site and then logging into the web site using an administrators creditonals that the error will not occur.

The error will also not occur if the web sites anonymous user is set to run as a user that has local Administrator privledges.
 [2002-06-26 18:54 UTC] davidr at gronks dot com
I did find that upgrading the VBScripting engine and MDAC to 2.7RTM seemed to resolve the problem.  Well, not sure about resolving but the error hasn't occured since.
 [2002-07-10 12:42 UTC] wrichard at mail dot com
How can this possibly be closed? The bug is *still* there even in the latest snap that was supposed to fix it...

The arrogance astounds me.... This is a very annoying problem
that needs to go away, regardless of M$ or not.
 [2002-07-15 11:31 UTC] ottawasixtyseven at hotmail dot com
Just wondering if the PHP dudes read the comments in the "closed" bugs. I agree that this bug should NOT be closed! Servers are getting faster and faster and this bug seems to happen more often on faster machines. It's going to become a real nightmare soon. Too bad the ISAPI module is so buggy that we're forced to use CGI mode. Maybe we should re-open this bug. How do you do that?
 [2002-07-15 11:48 UTC] rasmus@php.net
There is really nothing solid to go on here.  Everything points to an IIS issue, and as mentioned upgrading MDAC seems to fix it, so unless there is some real evidence that this is something we can fix at the PHP level, I see no reason for this to be an open bug in the PHP bug database.
 [2002-08-04 22:48 UTC] scott at datalink dot net dot au
Here's a reason to open this bug:   If PHP worked properly with enterprise products we would consider using it for enterprise solutions.

How can you state that there is nothing solid to go on, considering the opening bugnote begins with: "Under the category of 'You Can Never Have Too Much Information On A Bug'", and this bug has over 600 lines of descriptive information, including step-by-step procedures and scripts to reproduce it!

Regardless of who is to blame (IIS, MSSQL, PHP, Solar Flares), the bug exists anyway, and it is in the interest of PHP to track it.   

By closing this bug because somebody claimed that a MDAC upgrade *may* solve the problem is wrong.   If all bugs were handled using hearsay I would not feel comfortable about the quality of PHP in general.    How about having someone who can replicate this bug become responsible for it, and only when they are happy should the bug be closed.

I am happy to become this person, to help improve the quality of the PHP codebase and the support team.

In the meantime, please re-open this bug.
 [2002-08-05 00:39 UTC] scott at datalink dot net dot au
I applied the MDAC 2.7 Refresh patch from Microsoft to our troublesome server, and unfortunately this did not solve the problem.

On our new notebook (1.6Ghz P4, WinXP) the problem does not occur at all.   XP uses MDAC 2.7, too...   Could be that the notebook is slower (the production machine is dual processor P3 1Ghz).

Still searching for an answer... By the way, has anyone tried using the ADO COM object?

Scott
 [2002-08-05 02:14 UTC] scott at datalink dot net dot au
Further to my other posts, some more constructive data to add to the debug efforts:

1.   I now can replicate this on my XP notebook, by setting performance options to 'background services' rather than the default 'foreground applications'.   It seems that MDAC 2.7 has no effect on the problem occurring as it's bundled with WinXP.

2.   It seems I can prevent the problem from occurring on the production box by setting it to 'foreground applications' rather than 'background services'.

This is the most successful workaround to date (for me).   It also confirms that the problem is related to processor speed or timing.    

Scott
 [2002-08-28 02:28 UTC] scott at datalink dot net dot au
Hi all,

As a followup a few weeks later, I can confirm that setting the server performance to optimise for 'Forground Applications' solves the CGI Error problem completely.

My guess is that PHP is launched as a CGI in user space (owned by IUSR_*), so tuning the server this way gives it more processing time.    I guess the MSSQL module likes it this way.

I have also had emails from others asking for assistance on this, and have had positive feedback from them that it fixed their problem, too.

Scott.
 [2002-08-28 13:52 UTC] ottawasixtyseven at hotmail dot com
I agree with Scott. PHP should be made to work with enterprise products. Even if the problem is not PHP's fault we still need to know exactly what causes it.

It's very interesting that when Scott sets Performance Options to forground it solves his CGI error completely. It's even more interesting that MDAC 2.7 doesn't help him. 

This is our latest experience with a client who just installed our PHP application.

Client System Configuration:
1.4 GIG processor, M$ 2000 Server, IIS, PHP, M$ SQL Server.

Client installed our application. CGI errors out the ying-yang (this error happens more frequently on a machine with a fast processor). Told Client to install MDAC 2.7 RTM. Unfortunately (or fortunately depending on how you look at it), the client also decided to install this patch at the same time:
http://www.microsoft.com/technet/treeview/default.asp?url=/technet/security/bulletin/MS02-009.asp

So, we've found some new, interesting information from Micro$oft:
"Incorrect VBScript Handling in IE can Allow Web Pages to Read Local Files"

Micro$oft also talks about third party scripting languages:
"... Microsoft has become aware of a handful of third-party applications that depend on unforeseen behavior in VBScript that this patch disables."

So good news and bad news. Bad news: We don't know if MDAC 2.7 fixed our clients CGI erros or if the MS02-009 fixed it.
Good news: we've found yet another possible solution (MS02-009)

If anyone has a really fast machine out there maybe they can test this MS02-009 fix. Please post your findings here.

Ottawa
 [2002-08-28 13:59 UTC] ottawasixtyseven at hotmail dot com
A few notes to add to the above comment. Our client does not have the Performance Option set to foreground. The CGI error doesn't happen any more thanks to either MDAC 2.7 or MS02-009. Wish I knew which of the two fixed the CGI errors
 [2002-09-24 20:05 UTC] davidr at gronks dot com
After some further testing on this PHP bug, I'll have to claim my previous comment about upgrading MDAC to be a bit of a Red Herring.

However, my comment about running the IIS slot as an Administrator is still valid, it seems that when the scripts are being executed as an administrator (either by setting the anonymous IUSR to be an administrator or removing anonymous access and authenticating with an administrator account), this bug didn't occur in the 200 or so requests that I made to the server yet when I drop the slot back to being run as the IUSR it fails immediately.

The bug now seems to be not related to a Header redirect since I can replicate it almost every time without fail by browsing to one of my plain HTML pages which loads approximately 30 images by using a PHP script to produce the image.  A database connection is created in that image script as it lookups the image's ID (a random 15 character string) which maps it to the physical location of the image.

I have tried to throttle the bandwidth setting as mentioned earlier but with no success.

I have also been seeing these "Application Popup Errors" at the same time that the PHP script returns its CGI Header error.  This popups occur on the console and are exactly the same each time, they consist of;

---
Title Bar: php.exe - Application Error

The application failed to initialize properly (0xc0000142).  Click OK to terminate the application
---

Server Information:
P3-1Ghz
512Mb RAM
Win2000 Server (SP3), IIS5
Hotfixes:
   Q326830
   Q295688
   Q147222
IIS is configured to run as a host header server.

Unfortunately in my circumstances, it prevents the company I work for the ability to allow our clients to use PHP on our live web servers until this bug is fixed up.  If this bug can be re-opened and looked into, I'm sure we would all be very grateful for it.

Cheers
 [2002-09-24 20:46 UTC] davidr at gronks dot com
Hi All,
I installed the patch for Q318089 (MS02-009) and the error still occurs.

It's also interesting to note that after running IRIS (network packet sniffer) it seems that IIS is not even launching PHP since the header "X-Powered-By: PHP/4.2.3" does not show up.

I can only guess in that something with IIS/PHP/MSSQL connectivity, the PHP executable (child handles/threads) are being locked in use which prevents PHP from launching, however a local administrator on the box has sufficient priviledges to over-ride these locks and PHP is launched.

-- Packet from IRIS --
GET /image_viewer.php?strPhotoID=99cBiFieBDiBaHBHcBac&strThumb=1 HTTP/1.1
Accept: */*
Referer: http://website/test.php
Accept-Language: en-au
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)
Host: website
Connection: Keep-Alive
Cookie: PHPSESSID=b3cfba912345ad3043a08bd6d6faf16d

HTTP/1.1 502 Gateway Error
Server: Microsoft-IIS/5.0
Date: Wed, 25 Sep 2002 01:18:12 GMT
Connection: close
Content-Length: 215
Content-Type: text/html

<head><title>Error in CGI Application</title></head>
<body><h1>CGI Error</h1>The specified CGI application misbehaved by not returning a complete set of HTTP headers.  The headers it did return are:<p><p><pre></pre>
---

Regards
David
 [2002-10-10 13:15 UTC] ottawasixtyseven at hotmail dot com
Follow up: (VERY INTERESTING)

As previously posted, a client of ours installed our PHP application and had CGI errors like crazy. They installed MDAC 2.7 and MS02-009 and fixed the problem.

We recently were able to convince them to try a test for us (because their machine is three times faster than anything we have!).

We had them change their Performance Options from "Background services" to "Application"
RESULT: CGI misbehaved ERRORS ALL OVER THE PLACE!

Set back the Performance Options to "Background services". RESULT: NO CGI ERRORS!

Scott is really onto something here. There is no question these errors are directly related to Performance Options and the priviledges associated with this setting. It's very interesting that IIS doesn't even get to the point of launching PHP in Scott's tests.

I want to do some testing with running the IIS slot as an Administrator. I will post my findings.

Ottawa
 [2002-10-25 03:42 UTC] ewald dot murgg at fh-joanneum dot at
We have the same problem and the same configuration
Web server:
      Win2000 Server 
      IIS 5.0
      PHP 4.2.2  (CGI mode)

   Database server:
      WinNT 4.0 SP6
      MS-SQL 7.0

   Client:
      Win2000 Professional SP1
      IE 5.5 SP1

The CGI Error is apperaing now and then.
Tried all patches (MDAC 2.7 ...) and "Check File exists.."
but nothing really worked..
I would love to try to change these perfomance options as Ottawa posted, but unfortunately I don't know where in IIS to set them! Could somebody give me a helping hand on that ??
I will then test and post the results!

Thanks
Ewald
 [2002-10-25 10:15 UTC] dmendez at artech dot com dot uy
Ewald, this setting is applicable to windows not to IIS.
Go to start button, control panel, system, advanced tab then performance option.

good luck.
dmendez
 [2002-10-28 04:35 UTC] ewald dot murgg at fh-joanneum dot at
Thanx for the quick answer dmendez,

I now switched to Background Application,
there are no CGI Errors, but i just could not stress test the server.
But it seems as if that solved the problem.
 [2002-10-28 08:41 UTC] sethm at gladstone dot uoregon dot edu
On our servers, we were recieving this cgi error a lot. I haven't installed the specific patch or updated MDAC. (web server - w2k sp3 iis 5, fast; mssql server - w2k sp3 mssql 2000, fast; all on a 1gb private net). My web server was set to background by default. I changed to APPLICATION and things have been working well. It seems that folks are using the background setting after the updates and patches. Don't know if this is of any use, but I thought I'd let people know. Also, I only recieve the CGI error on the IE browser. I have yet to recieve it on Mozilla.

Thanks
Seth
 [2002-10-28 18:59 UTC] gootch at antipopular dot com
I was having major problems with this just as everyone else was so I changed my setting from being optimized for background processes to applications and everything seems to be working smoothly.  

That said, I am very disappointed with PHP, and I really hope that the developers learn from their mistakes... especially this one. This type of error cannot be tolerated, especially when it's been present for this long.  Version after version... nobody seems to be paying attention to it. I'm sorry, but I think I will be moving to asp.net if php cannot handle the speed of our servers.  I understand that bringing up asp.net in a PHP forum is not a good idea, however I'm just stating the facts.

Farewell PHP, I might be back, but in the mean time I choose not to put my reputation into the hands of ignorant programmers.
 [2002-10-28 19:35 UTC] rasmus@php.net
We fix what we can fix given our resources and the environment we are working in.  In many ways M$ does not provide us with a level playing-field and as such you will find that PHP is much much stronger on non-M$ platforms where we are not hampered by closed-source, vague and often quite buggy apis.  But thank you for your amazingly constructive comments.
 [2002-10-29 14:00 UTC] ottawasixtyseven at hotmail dot com
I'm happy to hear that most people are able to solve their CGI errors by changing the Windows Performance Options. We have Scott to thank for this little trick!

Rasmus,  I think what people are upset about is that this bug was closed. It's obviously a Micro$haft problem (big surprise) but even so, it's quite frustrating to feel like y'all don't give a dern  :-(  This is obviously not the case but closing the bug makes people think that you're not interested in finding a solution. Even if the problem is not the fault of PHP. 

On an unrelated note I'm *extremely happy* to see that you've included the php_zip.dll extension in php-4.3.0pre2-Win32.zip. SWEEEEEEEEEEEET!

Now all we need is a solid php4isapi.dll  ;-)

Ottawa
 [2002-11-14 06:36 UTC] ulysses at mail dot fitan dot com dot tw
Just for your information:
Don't blame PHP. ASP.net ALSO SHOWS LOTS OF "CGI ERROR". I 
solve this problem by slowing down connection -- do not put 
src='xxx.php/asp' in your frame tag. use onload() handler 
to load page into frames with javascript AFTER the frame 
page is loaded.
 [2002-12-27 07:00 UTC] nicolas at colbert dot ws
Good Afternoon,

I have seen many comments regarding PHP should be compliant with enterprise software.  I would suggest that it is - UNIX and Apache are enterprise level solutions and PHP is a ROCK star on those platforms.  Just because we are no forcing it to do things on an AXX Backward platform like MS W2k and XP is not a reason to complain.  

I have run into the issue, because I am having to rewrite our authentication scripts because the IIS CGI cannont handle a simple authentication redirect.  Before you blame PHP, try looking at all the garbage hoops that IIS puts you through.

Nicolas
 [2003-01-07 17:29 UTC] vincent at sunlight dot tmfweb dot nl
Just an idea: does it help to close the database connection right before calling the header('Location: URL') function? I understand that putting in a timer helps (most of the time), but I think that's a bit of an ugly solution. I mean: how long should you wait? The ideal number of microseconds to sleep depends on the server, the load on the server, and so on. As the problem occurs when there is a database connection, I wonder if it goes away if this connection is closed, before doing the real redirecting. Sadly enough I can't test this myself, because I don't have access to a server that's fast enough. Anyone?
 [2003-01-12 15:16 UTC] theo dot schoeberl at tssystems dot de
We have chanced our PHP-Script from using ODBC to native MSSQL (using the MSSQL library). The same error (incl. 502 Bad Gateway).

The next try was to change the server name to its IP address within the connect statement - and it works!!!!!

No error since the change, running now over 14 days!

May be there is a problem (known under Windows systems) resolving the server name?

Hope this helps a lot of PHP developers running Windows systems!

Theo
 [2003-01-28 05:11 UTC] mlaukast1 at hotmail dot com
There's an interesting solution to 502 CGI Error in bug report #21681 by dipsy_9001@yahoo.fr. Altough I wasn't able to get rid of the error entirely, the solution dramatically reduced the appearance of it.
 [2003-03-03 17:23 UTC] gkasten at filnet dot fr
http://support.microsoft.com/default.aspx?scid=kb;en-us;151825
http://bugs.php.net/bug.php?id=9852


Hello bugbrowsers (same comment as 12700, but this thread is better),

I tried too unsuccessfully : -background perf -mdac -admin and various other commented things above, on IIS w2kSrv & NT4 , php 4.*<=4.3.1 :-(

I had the problem on /phpmyadmin subdir, protected by ACLs.
And only with far-tracerouted client machines.

* I SUCCEEDED with unchecking "directory-security / allow-anonymous-access" (which is theorically useless because there is no IUSR_* in the acls of php pages below).

I hope it can help desperate hostmasters, and php-dev-community to track this @#%! bug.

Guy Kastenbaum - Paris
 [2003-03-05 20:32 UTC] frankielam at ucr dot com dot hk
I can reproduce the error with the php script below(a simple script that do nothing but keeps refreshing itself with a different value of parameter passed into it as GET, REMEMBER to open serveral instances to run it.). IMHO, this is not a database problem(neither mysql nor mssql), and this might be a problem that IIS cannot handle sucha high frequent call to `php.exe', and it does assume that php.exe returns nothing!! (Am I right? :-D)

doit.php
8<-----------------------------------------------
<?
echo "<html><head><title>testing</title>";
if (isset($_GET["times"]))
	$times = ($_GET["times"]) + 1;
else
	$times = 0;

//SEE??? even i comment the statement out, infamous cgi error occurs, STILL!
//$conn = mssql_connect('127.0.0.1', 'sa', '') or die("couldn't connect");
echo "<meta http-equiv=\"Refresh\" content=\"0; URL=doit.php?times=" . $times . "\"></head></html>";
echo "Trying CGI";
echo "<BR>$times";
//header("doit.php");
?>
8<-----------------------------------------------

My config.:
Windows 2000 Advanced Server with SP3
PHP 4.3.1 / 4.2.3 (both tested to have CGI problem)
MSSQL Server 2000
 [2003-03-14 12:53 UTC] ottawasixtyseven at hotmail dot com
frankielam,

You've hit the nail on the head. It's a problem with IIS. This DOES NOT HAPPEN *EVER* with Apache. IIS is not able to handle multiple simultaneous calls to php.exe.

The question is now ... how the hell do we get Micro$haft to fix this? They are about as responsive to bugs likes this ... as a brick wall! I wish this was a PHP error because the lads at PHP are usually quite responsive to bugs.

Anybody have any suggestions on how to get Bill to listen? I've tried calling support, posting messages, no luck. We have switched all our servers over to RedHat and the ones that MUST remain Windoze are running Apache Web server.

It still should be noted that changing the Performance options can greatly reduce the occurence of the CGI error. Unfortunately, it does not eliminate it. 

Ottawa
 [2003-03-14 18:52 UTC] sniper@php.net
Friendly suggestion: Stick to OpenSource solutions. :)

 [2003-03-17 07:15 UTC] lewid at nc dot rr dot com
I am at a loss here - I am a developer for a large company and do not have a choice as to which web platform I can use -  IIS is the tool I have to work with.

I have been using php on IIS but this growing percentage of CGI errors on my applications is forcing me to consider using a different application server, as it does not appear at this time that it will be resolvable.

Is there ANY hope, or should I just switch to a different application server, as I do not feel that it is acceptable for my applications to recieve a significant % of errors.

If anyone has any suggestions please email me - ps - switching to an open source web server is not an option I can entertain at this time :(
 [2003-03-17 17:49 UTC] ottawasixtyseven at hotmail dot com
Lewid,

Have you considered trying php4isapi.dll? PHP admits that it's *STILL* not production quality (how many years has it been ???)  but some people have had great success with it.

I think I may have finally figured out why PHP.EXE spits out those CGI errors. And why on faster machines it happens more often ... IT'S NOT THREAD-SAFE !!!

I don't know why this didn't dawn on me earlier. It makes total sense. The problem occurs when IIS tries to make simultaneous calls to PHP.EXE. With php4isapi.dll, instead of loading PHP.EXE for each request, ISAPI uses the thread-safe DLL that's loaded only once. Apache must handle CGI differently because you NEVER get the CGI error.

We can't use php4isapi.dll with our application because for some reason it blows up all over the place with server 500 errors. We continue to pray that the PHP gods will deliver us a rock solid php4isapi.dll. Until then we deal with the CGI errors and blame it on Bill.

Again, for some reason changing your Performance Options to either Background services or Applications seems to really make a difference. Even with this option change frankielam has proven that when opening multiple instances of his script (see above doit.php) you can generate CGI errors at will. Try this at home and impress your friends :-)

Please let us know if running php4isapi.dll works for you.

Ottawa
 [2003-03-20 12:30 UTC] ottawasixtyseven at hotmail dot com
I have PROVEN beyond a shadow of a doubt that IIS can't handle multiple simultaneous connections to ANY CGI  !!!! It's not the fault of PHP.EXE

I've compiled the C code that's listed below and put it in C:\Inetpub\Scripts. If you would like a copy of the compiled exe drop me a line.

For the sake of simplicity, this program is designed to be initially called with no parameters as in http://localhost/Scripts/breakiis.exe       
Also, for simplicity, I don't bother following the conventional name=value&name=value format of the URL string parameters but simply pass a number. This code is perfectly  safe in that it will start the count at 1 if no parms are passed and if a QUERY_STRING that is non-numeric is passed, atof will return 0.0 so that is also safe. This program fully complies with the rules of CGI programming via the GET method in that it receives the URL string parameters via QUERY_STRING and sends back output via cout 
with a valid header. You will see that running one instance of this in the browser will work fine. Run multiple instances and you will break IIS. This program is designed to do nothing more than prove that there is a flaw in the way that IIS handles CGI processes and that the bug is in fact with IIS and not PHP. 

You *CANNOT* break Apache with multiple instances of this CGI code:
______________________________________________________

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
char *data;
double count;
int main(void)
{
  data = getenv("QUERY_STRING");
  if(data == NULL) 
    count=1;
  else
    count = atof(data);
  printf("Content-Type:text/html\n\n");
  printf("Loading page with value %f\n",floor(count));
  count++;
  printf("<script>location.href='breakiis.exe?%f'</script>",count);
  return 0;
}
_______________________________________________________

I have launched yet another campaign to try and get Microsoft to fix this problem but honestly I think we'd have better luck just working out the bugs in php4isapi.dll. Maybe in the year 2025 Microsoft will get around to fixing this problem.

Ottawa
 [2003-03-20 15:28 UTC] lewid at nc dot rr dot com
What bugs are there in php4isapi.dll (referring to above comment)? I am using an isapi filter pointing to php4isapi.dll and it seems to have fixed the cgi issue completely in my development environment.
 [2003-03-20 17:10 UTC] ottawasixtyseven at hotmail dot com
Lewid,

php4isapi.dll works perfectly for some people. We are part of the unfortunate group that experiences lots of server 500 errors. Here is an excerpt from the latest PHP INSTALL text file:
_________________________________________________
PHP 4 for Windows comes in two flavours - a CGI executable (php.exe), and several SAPI modules (for exapmle php4isapi.dll). The latter form is new to PHP 4, and provides significantly improved performance and some new functionality. However, please note that the SAPI modules are *NOT* yet considered to be production quality. In particular, with the ISAPI module, you are likely to encounter serious reliability problems especially on platforms older than W2K - you may witness a lot of server 500 errors and suffer from other server modules such as ASP also failing. You have been warned!

The reason for this is that the PHP SAPI modules are using the thread-safe version of the PHP code, which is new to PHP 4, and has not yet been tested and pounded enough to be considered completely stable, and there are actually a few known bugs. On the other hand, some people have reported very good results with the SAPI modules, and there a few reports of problems with the Apache module version. In short - your mileage may vary;  If you need absolute stability, trade the performance of the SAPI modules with the stability of the CGI executable.
_________________________________________________

Hopefully you can be part of the increasing numbers that are actually able to give php4isapi.dll a good pounding. Please make sure to report any problems you have with it.

Ottawa
 [2003-03-21 07:31 UTC] lewid at nc dot rr dot com
Thank you very much for all you comments, Ottawa67!
I have implemented ISAPI using php4isapi.dll in our production environment now and it appears to work perfectly and has solved the problem we were having.
I will contribute any bugs I encounter but so far it is working ... perfectly!
 [2003-04-08 04:14 UTC] jitse dot groen at grib dot nl
Dear all,

I'm probably not as experienced in PHP as all of you but I found a solution that *seems* to work fine for our sites. I base this on tests with doit.php by frankielam. 

I should also mention running iisreset once in a while decreased the number of CGI errors per day. It takes about 1-2 weeks for the bug to become noticable to us. It is present before that time but will not show that often.

Changing performance to optimize for applications I really cannot consider. How can reducing the speed of our servers be a solution? 

A possible solution though: After increasing the paging file size (virtual memory) I cannot reproduce the bug however often I try. I'm not absolutely convinced that this will do the trick, but for now, it works. I would be anxious to hear your experiences with this solution.

With kind regards,
Jitse Groen,
The Netherlands
 [2003-04-17 20:43 UTC] ottawasixtyseven at hotmail dot com
Parsnip, it's an IIS bug. Have you tried php4isapi.dll? It completely fixes this problem. I can send you my breakiis.exe so you can prove to your managers that IIS can't handle multiple simultaneous to any CGI. The trick is to get away from CGI.

This is right off the Microsoft site:

"The Internet Server Application Programming Interface (ISAPI) model was developed as a higher-performing alternative to the Common Gateway Interface (CGI). ISAPI provides a number of advantages over CGI, including low overhead, fast loading, and better scalability."

"The chief difference between the CGI and ISAPI programming models is the way processing is handled. With CGI, the system creates a unique process for every request. Each time an HTTP server receives a request, it initiates a new process. Because the operating system must maintain all these processes, CGI is resource-intensive. This inherent limitation makes it difficult to develop responsive Internet applications with CGI."

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/iisref/htm/ISAPIExtensions.asp

Ottawa
 [2003-05-12 07:27 UTC] pedro at fundacaounimed dot com dot br
I think I find the solution for this problem (at least on version 4.3.1)...
Just put this line "cgi.rfc2616_headers = 1" on php.ini.
Please, send us a message if it works. I had this problem during much
time and looking for solution, I saw that many others have it too.

PS.: sorry if there is some english error.
 [2003-05-22 13:21 UTC] phpbugs at spudland dot com
This is not just an IIS bug.

I receive this bug on a production Win2K server that uses Apache 2.0.x and PHP as a CGI. The PHP script in question does not use re-directs, however it does add header information.

When I comment out the MS-SQL commands, the error disappears. With MS-SQL commands uncommented, it serves up a storm of these errors.

I will try the RFC option mentioned above my comment! Again, this bug appears to NOT be related to just IIS but rather the MS-SQL support.
 [2003-05-28 08:50 UTC] wharrison at pro dot ie
I am trying Pedro's cgi.rfc2616_headers = 1 tip. We noticed this problem a few times a day on an WinNT, IIS, PHP 4.3, MSSQL 2000 setup. I could also reproduce this with the bounce.php suggested a while ago. I was cosidering switching to Apache untill I read the post above.
 [2003-06-11 09:52 UTC] wharrison at pro dot ie
To follow up I set cgi.rfc2616_headers = 1 as Pedro suggested and have had no problems reported since. So I suggest trying this to anyone with these problems.
 [2003-09-15 16:40 UTC] bobberz03 at hotmail dot com
Was pulling my hair out with this!! Installing ISAPI module did it for me, none of the other fixes worked (did NOT try slowing anything down to get it working or messed with Background/foreground settings as this defeats the object..and some time in the future will reoccur neway!! I have created other appz using the CGI interpretor but havent tested them with the ISAPI module as yet, this is the first app I'm creating using MSSQL2000. I know its been stated above that it is IIS but I have never had this problem b4 until switching to MSSQL2000 (previously MySQL). Cheers for all the help chaps.

BoB
 [2004-02-10 19:14 UTC] willy at vuboys dot nl
I also have experienced this problem. The PHP_ISAPI seems to fix it.

It seems this problem is related to a mssql connection. A solution might be to add a header() at the beginning of the script (before the mssql_connect). Is there a header of some kind which won't interfear with the other headers the application might produce? Any thoughts/comments on this?
 [2004-02-26 05:41 UTC] stuart at gnqs dot org
I'm not sure why the PHP group haven't already done this themselves (I will ask Wez when I see him next week ;-), but anyway.  I have bug# SRQ040206601696 open with Microsoft about this problem.

From the analysis I've done so far (net trace of HTTP packets between IE and IIS, ISAPI filter to do what tracing I can inside IIS, tracing code added to PHP 4.3.5-rc1), the evidence comes down to this.  When this error occurs, there's no evidence of php.exe being executed - for the repeatable test case that I have.  What I can't *prove* (which is partly why I've opened the bug w/ Microsoft) is whether IIS actually tries to call php.exe or not.

Best regards,
Stu
 [2004-06-23 18:36 UTC] php at squeg dot net
A temporary fix to this issue would be to create a custom 502 error page that automatically refreshes the page (typically under c:\WINNT\Help\issHelp\common - but don't forget that you also have to set the options in Internet Services Manager... Go to Start, Programs, Administrative Tools, Internet Services Manager. Click on your host, then right click your website and select Properties. Then click the "Custom Errors" tab. Find 502 in the list and ensure that it is set to "File" and that it is pointing to your custom page).

The only problem with this approach is if the user was submitting a form, they will be presented with a dialog box asking if they want to "Retry" or "Cancel", so you should mention somewhere on your custom page that they should click "Retry". Here's the custom page I hacked together out of the default 502.htm for my university:

------------ BEGIN ------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html dir=ltr>

<head>
<style>
a:link			{font:8pt/11pt verdana; color:FF0000}
a:visited		{font:8pt/11pt verdana; color:#4e4e4e}
</style>

<META NAME="ROBOTS" CONTENT="NOINDEX">

<title>The page cannot be displayed</title>

<META HTTP-EQUIV="Content-Type" Content="text-html; charset=Windows-1252">
</head>

<body bgcolor="FFFFFF" onload="setTimeout( "location.reload();", 50 );">

<h1>502: CGI Error</h1>
	If it asks whether to Retry or Cancel, click <b>Retry</b>.
</body>
</html>
------------ END ------------

The reason I used setTimeout was because if I just used location.reload(), MSIE doesn't display any text from the page, it just reloads. So I figured a really small timeout value should make it display the page first (just in case the user gets presented with that "Retry/Cancel" box).
 [2004-06-23 18:42 UTC] php at squeg dot net
And, of course, I made a typo in my sample 502 page... The body tag should be:

<body bgcolor="FFFFFF" onload="setTimeout( 'location.reload();', 50 );">

Note that I had double quotes around location.reload(); originally... that certainly didn't work as expected =) Change the double quotes to single quotes and all is well.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 16:01:29 2024 UTC