User: Pass: | Sign Up | Help

data-driven
college admission predictions






php « MyChances.net

Posts Tagged ‘php’

Forking Daemons in PHP

by James
Thursday, April 30th, 2009
No Gravatar

Note: this is from http://bipinb.com/making-php-program-as-daemon.htm . It has been intermittently offline, so I’m archiving it here for future reference.


<?php
include_once('createdb.php');
declare(ticks=1);
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
exit(); // we are the parent
} else {
// we are the child
}
// detatch from the controlling terminal
if (posix_setsid() == -1) {
die("could not detach from terminal");
}
$posid=posix_getpid();
$fp = fopen("/var/run/process.pid", "w");
fwrite($fp, $posid);
fclose($fp);
// setup signal handlers
 pcntl_signal(SIGTERM, "sig_handler");
 pcntl_signal(SIGHUP, "sig_handler");
// loop forever performing tasks
 $dbobject = new DB();
 $dbobject->getCon();
 while (1) {
// do something interesting here, here i have called a function from other flile called "createdb.php"
$dbobject->CopyCallFiles();
}
 fclose($fp);
 function sig_handler($signo)
 {
switch ($signo) {
 case SIGTERM:
 // handle shutdown tasks
 exit;
 break;
 case SIGHUP:
 // handle restart tasks
 break;
 default:
 // handle all other signals
 }
}
?>
  • Share/Save/Bookmark

Recursive str_replace in PHP

by James
Thursday, March 20th, 2008
No Gravatar

I was looking for a recursive str_replace in php tonight and I couldn’t find any, so I wrote one. This takes the exact same parameters as str_replace, in the same order. It recursively searches the $subject, replacing $search with $replace, while keeping track of how many times ($count) it has replaced the $subject.


Example:

$count=0;
$string = "; ; I; am; ; ; ; ; become; ; ; ; ; ; ; ; ;";
string = str_replace_recursive('; ;',';',$string,$count);

echo $string;
echo $count;

Outputs:
string --> I; am; become;
count --> 12

(Note that this is not the best code to use for this situation; can you write a faster solution to this example using only plain vanilla str_replace?)

  • Share/Save/Bookmark