[Tutorial] Running several processes with php

Example of PHP code.

Moderator: Moderators

[Tutorial] Running several processes with php

Postby PostBot on Wed May 11, 2005 9:06 pm

This is a simple tutorial for advanced users that explains how to open extra process using php (aka pseudo-cron).

It is very useful if you have some very long operation but don't want user to wait for it to end before loading page, so you start another process and exit current script. Or you can use this if you need to run a cron, but don't have access to server so you can't add cron jobs.

Here is code that starts another process:
Code: Select all
<?php
$server = 'localhost';
$get = '/path_to_script.php';
$fp = fsockopen($server, 80);
fputs($fp, "GET {$get} HTTP/1.1\r\n");
fputs($fp, "Host: {$server}\r\n");
fputs($fp, "Connection: Close\r\n\r\n");
fclose($fp);
?>


Then your another script that will be opened in that process:
Code: Select all
<?php
set_time_limit(0); // remove script timeout
ignore_user_abort(false); // make sure script works even if connection is closed

/// ... and then do your stuff

?>
Do NOT pm me, I don't visit this forum anymore, don't own it, don't provide any support and don't moderate.
User avatar
PostBot
Moderator
Moderator
 
Posts: 10659
Joined: Sat Aug 02, 2003 3:52 pm
Location: Mars

Postby PostBot on Wed May 11, 2005 9:10 pm

One more addition: if you want to make it more secure so users using usual browser wouldn't be able to use your script even if they know url then you can use extra http headers to send data.

First file would look like this:[code highlight="7,8"]<?php
$server = 'localhost';
$get = '/path_to_script.php';
$fp = fsockopen($server, 80);
fputs($fp, "GET {$get} HTTP/1.1\r\n");
fputs($fp, "Host: {$server}\r\n");
fputs($fp, "X-Header1: blah\r\n");
fputs($fp, "X-Header2: blah2\r\n");
fputs($fp, "Connection: Close\r\n\r\n");
fclose($fp);
?>[/code]
And second file would look like this:[code highlight="5-8"]<?php
set_time_limit(0); // remove script timeout
ignore_user_abort(false); // make sure script works even if connection is closed

if(empty($_SERVER['HTTP_X_HEADER1']))
{
die('Permission denied.');
}

/// ... and then do your stuff

?>[/code]
Do NOT pm me, I don't visit this forum anymore, don't own it, don't provide any support and don't moderate.
User avatar
PostBot
Moderator
Moderator
 
Posts: 10659
Joined: Sat Aug 02, 2003 3:52 pm
Location: Mars


Return to PHP Tutorials

Who is online

Users browsing this forum: No registered users and 2 guests

cron