I’ve implemented a web service for work which allows you to queue a job, and also to retrieve the job. I also implemented a simple login header which looks after your session through the database. The long term issue that we’ve had in the past is that Safari drops the session (thus losing all global session variables) and also Safari dropping the ability to kill the session in PHP. So I’ve made a simple module which is included on all PHP pages and it sorts out the authentication for you.

The problem came when I tried to introduce this login header to the top of my webpage which “GET”‘s the job. The normal process of forcing a user to download the contents is to use the following code:

<\?php
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=test.txt");
     header("Content-Type: text/plain");
     echo($streamOfText);
     //or
     //readfile("test");
?>

The problem with doing that is if you have other text sitting on that page (or just include ‘login.php’;), since the header forces ALL content to be saved into the file test.txt, and not just $streamOfText.

What I ended up doing to get around this issue, might be a long way to solve the issue, but it works just fine. I created a file in the same disc space and filled it in with the header information as well as reading in another file on the disc. I created the other file with the contents of $streamOfText. At the end of the first file, I unlink the content file as well as itself. The original GET file does a simple header redirect. This leaves no traces of those files ever being created or existing.

JobHandler
	$fp = fopen($JobID . ".php", 'w');
	fwrite($fp, "<\?php " . "\n");
	fwrite($fp, 'header("Cache-Control: public");' . "\n");
	...
	fwrite($fp, "\$filename='" . $JobID . "';" . "\n");
	fwrite($fp, "readfile(\$filename);" . "\n");
	fwrite($fp, "unlink(\$filename);" . "\n");
	fwrite($fp, "unlink(\$JobID . '.php');" . "\n");
	fwrite($fp, "?>" . "\n");
	fclose($fp);

	header('Location:'.$JobID . ".php");

Note: Just clicked on “preformatted” as a markup in MarsEdit and it lets me write code! Very handy, since I tried doing it last time, with all sorts of funny things happening!

Written by Milton Lai

Leave a Comment

Your email address will not be published. Required fields are marked *