PHP & Web Development Blogs

Showing 41 to 45 of 53 blog articles.
7270 views · 3 years ago

![Creating a PHP Daemon Service](

# What is a Daemon?

The term daemon was coined by the programmers of Project MAC at MIT. It is inspired on Maxwell's demon in charge of sorting molecules in the background. The UNIX systems adopted this terminology for daemon programs.

It also refers to a character from Greek mythology that performs the tasks for which the gods do not want to take. As stated in the "Reference System Administrator UNIX", in ancient Greece, the concept of "personal daemon" was, in part, comparable to the modern concept of "guardian angel." BSD family of operating systems use the image as a demon's logo.

Daemons are usually started at machine boot time. In the technical sense, a demon is considered a process that does not have a controlling terminal, and accordingly there is no user interface. Most often, the ancestor process of the deamon is init - process root on UNIX, although many daemons run from special rcd scripts started from a terminal console.

Richard Stevenson describes the following steps for writing daemons:

1. Resetting the file mode creation mask to 0 function umask(), to mask some bits of access rights from the starting process.

2. Cause fork() and finish the parent process. This is done so that if the process was launched as a group, the shell believes that the group finished at the same time, the child inherits the process group ID of the parent and gets its own process ID. This ensures that it will not become process group leader.

3. Create a new session by calling setsid(). The process becomes a leader of the new session, the leader of a new group of processes and loses the control of the terminal.

4. Make the root directory of the current working directory as the current directory will be mounted.

5. Close all file descriptors.

6. Make redirect descriptors 0,1 and 2 (STDIN, STDOUT and STDERR) to /dev/null or files /var/log/project_name.out because some standard library functions use these descriptors.

7. Record the pid (process ID number) in the pid-file: /var/run/

8. Correctly process the signals and SigTerm SigHup: end with the destruction of all child processes and pid - files and / or re-configuration.

# How to Create Daemons in PHP

To create demons in PHP you need to use the extensions pcntl and posix. To implement the fast communication withing daemon scripts it is recommended to use the extension libevent for asynchronous I/O.

Lets take a closer look at the code to start a daemon:


umask(0); / / § 1

$pid = pcntl_fork(); / / § 2

if ($pid < 0) {

print('fork failed');

exit 1;



After a fork, the execution of the program works as if there are two branches of the code, one for the parent process and the second for the child process. What distinguishes these two processes is the result value returned the fork() function call. The parent process ID receives the newly created process number and the child process receives a 0.


if ($pid > 0) {/ / the parent process

echo "daemon process started


exit; / / Exit


/ / (pid = 0) child process

$sid = posix_setsid();/ / § 3

if ($sid < 0) {

exit 2;


chdir('/'); / / § 4

file_put_contents($pidFilename, getmypid() ); / / § 6

run_process(); / / cycle start data


The implementation of step 5 "to close all file descriptors" can be done in two ways. Well, closing all file descriptors is difficult to implement in PHP. You just need to open any file descriptors before fork(). Second, you can override the standard output to an error log file using init_set() or use buffering using ob_start() to a variable and store it in log file:


ob_start(); / / slightly modified, § 5.

var_dump($some_object); / /some conclusions

$content = ob_get_clean(); / / takes part of the output buffer and clears it

fwrite($fd_log, $content); / / retains some of the data output to the log.


Typically, ob_start() is the start of the daemon life cycle and ob_get_clean() and fwrite() calls are the end. However, you can directly override STDIN, STDOUT and STDERR:


ini_set('error_log', $logDir.'/error.log'); / / set log file

/ / $logDir - /var/log/mydaemon

/ / Closes an open file descriptors system STDIN, STDOUT, STDERR




/ / redirect stdin to /dev/null

$STDIN = fopen('/dev/null', 'r');

/ / redirect stdout to a log file

$STDOUT = fopen($logDir.'/application.log', 'ab');

/ / redirect stderr to a log file

$STDERR = fopen($logDir.'/application.error.log', 'ab');


Now, our process is disconnected from the terminal and the standard output is redirected to a log file.

# Handling Signals

Signal processing is carried out with the handlers that you can use either via the library pcntl (pcntl_signal_dispatch()), or by using libevent. In the first case, you must define a signal handler:


/ / signal handler

function sig_handler($signo)


global $fd_log;

switch ($signo) {


/ / actions SIGTERM signal processing

fclose($fd_log); / / close the log-file

unlink($pidfile); / / destroy pid-file



case SIGHUP:

/ / actions SIGHUP handling

init_data();/ / reread the configuration file and initialize the data again



/ / Other signals, information about errors



/ / setting a signal handler

pcntl_signal(SIGTERM, "sig_handler");

pcntl_signal(SIGHUP, "sig_handler");


Note that signals are only processed when the process is in an active mode. Signals received when the process is waiting for input or in sleep mode will not be processed. Use the wait function pcntl_signal_dispatch(). We can ignore the signal using flag SIG_IGN: pcntl_signal(SIGHUP, SIG_IGN); Or, if necessary, restore the signal handler using the flag SIG_DFL, which was previously installed by default: pcntl_signal(SIGHUP, SIG_DFL);

# Asynchronous I/O with Libevent

In the case you use blocking input / output signal processing is not applied. It is recommended to use the library libevent which provides non-blocking as input / output, processing signals, and timers. Libevent library provides a simple mechanism to start the callback functions for events on file descriptor: Write, Read, Timeout, Signal.

Initially, you have to declare one or more events with an handler (callback function) and attach them to the basic context of the events:


$base = event_base_new(); / / create a context for monitoring basic events

/ / create a context of current events, one context for each type of events

$event = event_new();

$errno = 0;

$errstr = '';

/ / the observed object (handle)

$socket = stream_socket_server("tcp:/ /$IP:$port", $errno, $errstr);

stream_set_blocking($socket, 0); / / set to non-blocking mode

/ / set handler to handle

event_set($event, $socket, EV_READ | EV_PERSIST, 'onAccept', $base);


Function handlers 'onRead', 'onWrite', 'onError' must implement the processing logic. Data is written into the buffer, which is obtained in the non-blocking mode:


function onRead($buffer, $id)


/ / reading from the buffer to 256 characters or EOF

while($read = event_buffer_read($buffer, 256)) {





The main event loop runs with the function event_base_loop($base);. With a few lines of code, you can exit the handler only by calling: event_base_loobreak(); or after the specified time (timeout) event_loop_exit();.

Error handling deals with failure Events:


function onError($buffer, $error, $id)


/ / declare global variables as an option - class variables

global $id, $buffers, $ctx_connections;

/ / deactivate buffer

event_buffer_disable($buffers[$id], EV_READ | EV_WRITE);

/ / free, context buffer


/ / close the necessary file / socketed destkriptory


/ / frees the memory occupied by the buffer

unset($buffers[$id], $ctx_connections[$id]);



It should be noted the following subtlety: Working with timers is only possible through the file descriptor. The example of official the documentation does not work. Here is an example of processing that runs at regular intervals.


$event2 = event_new();

/ / use as an event arbitrary file descriptor of the temporary file

$tmpfile = tmpfile();

event_set($event2, $tmpfile, 0, 'onTimer', $interval);

$res = event_base_set($event2, $base);

event_add($event2, 1000000 * $interval);


With this code we can have a working timer finishes only once. If we need a "permanent" Timer, using the function onTimer we need create a new event each time, and reassign it to process through a "period of time":


function onTimer($tmpfile, $flag, $interval)


$global $base, $event2;

if ($event2) {





$event2 = event_new();

event_set($event2, $tmpfile, 0, 'onTimer', $interval);

$res = event_base_set($event2, $base);

event_add($event2, 1000000 * $interval);



At the end of the daemon we must release all previously allocated resources:


/ / delete the context of specific events from the database monitoring is performed for each event


/ / free the context of a particular event is executed for each event


/ / free the context of basic events monitoring


/ / bind event to the base context

event_base_set($event, $base);

/ / add/activate event monitoring



Also it should be noted that for the signal processing handler is set the flag EV_SIGNAL: event_set($event, SIGHUP, EV_SIGNAL, 'onSignal', $base);

If needed constant signal processing, it is necessary to set a flag EV_PERSIST. Here follows a handler for the event onAccept, which occurs when a new connection is a accepted on a file descriptor:


/ / function handler to the emergence of a new connection

function onAccept($socket, $flag, $base) {

global $id, $buffers, $ctx_connections;


$connection = stream_socket_accept($socket);

stream_set_blocking($connection, 0);

/ / create a new buffer and tying handlers read / write access to the buffer or illustrations of error.

$buffer = event_buffer_new($connection, 'onRead', NULL, 'onError', $id);

/ / attach a buffer to the base context

event_buffer_base_set($buffer, $base);

/ / exhibiting a timeout if there is no signal from the source

event_buffer_timeout_set($buffer, 30, 30);

event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff); / / flag is set

event_buffer_priority_set($buffer, 10); / / set priority

event_buffer_enable($buffer, EV_READ | EV_PERSIST); / / flag is set

$ctx_connections[$id] = $connection;

$buffers[$id] = $buffer;



# Monitoring a Daemon

It is good practice to develop the application so that it was possible to monitor the daemon process. Key indicators for monitoring are the number of items processed / requests in the time interval, the speed of processing with queries, the average time to process a single request or downtime.

With the help of these metrics can be understood workload of our demon, and if it does not cope with the load it gets, you can run another process in parallel, or for running multiple child processes.

To determine these variables need to check these features at regular intervals, such as once per second. For example downtime is calculated as the difference between the measurement interval and total time daemon.

Typically downtime is determined as a percentage of a measurement interval. For example, if in one second were executed 10 cycles with a total processing time of 50ms, the time will be 950ms or 95%.

Query performance wile be 10rps (request per second). Average processing time of one request: the ratio of the total time spent on processing requests to the number of requests processed, will be 5ms.

These characteristics, as well as additional features such as memory stack size queue, number of transactions, the average time to access the database, and so on.

An external monitor can be obtain data through a TCP connection or unix socket, usually in the format of Nagios or zabbix, depending on the monitoring system. To do this, the demon should use an additional system port.

As mentioned above, if one worker process can not handle the load, usually we run in parallel multiple processes. Starting a parallel process should be done by the parent master process that uses fork() to launch a series of child processes.

Why not run processes using exec() or system()? Because, as a rule, you must have direct control over the master and child processes. In this case, we can handle it via interaction signals. If you use the exec command or system, then launch the initial interpreter, and it has already started processes that are not direct descendants of the parent process.

Also, there is a misconception that you can make a demon process through command nohup. Yes, it is possible to issue a command: nohup php mydaemon.php -master >> /var/log/daemon.log 2 >> /var/log/daemon.error.log &

But, in this case, would be difficult to perform log rotation, as nohup "captures" file descriptors for STDOUT / STDERR and release them only at the end of the command, which may overload of the process or the entire server. Overload demon process may affect the integrity of data processing and possibly cause partial loss of some data.

# Starting a Daemon

Starting the daemon must happen either automatically at boot time, or with the help of a "boot script."

All startup scripts are usually in the directory /etc/rc.d. The startup script in the directory service is made /etc/init.d/ . Run command start service myapp or start group /etc/init.d/myapp depending on the type of OS.

Here is a sample script text:


#! /bin/sh


$appdir = /usr/share/myapp/app.php

$parms = --master –proc=8 --daemon

export $appdir

export $parms

if [ ! -x appdir ]; then

exit 1


if [ -x /etc/rc.d/init.d/functions ]; then

. /etc/rc.d/init.d/functions



start () {

echo "Starting app"

daemon /usr/bin/php $appdir $parms


[ $RETVAL -eq 0 ] && touch /var/lock/subsys/mydaemon


return $RETVAL


stop () {

echo -n "Stopping $prog: "

killproc /usr/bin/fetchmail


[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/mydaemon


return $RETVAL


case $1 in












status /usr/bin/mydaemon



echo "Usage: $0 {start|stop|restart|status}"



exit $RETVAL


# Distributing Your PHP Daemon

To distribute a daemon it is better to pack it in a single phar archive module. The assembled module should include all the necessary PHP and .ini files.

Below is a sample build script:


if (is_file('app.phar')) {



$phar = new Phar('app.phar', 0, 'app.phar');


$phar->setSignatureAlgorithm (Phar::SHA1);

$files = array();

$files['bootstrap.php'] = './bootstrap.php';

$rd = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));

foreach($rd as $file){

if ($file->getFilename() != '..' && $file->getFilename() != '.' && $file->getFilename() != __FILE__) {

if ( $file->getPath() != './log'&& $file->getPath() != './script'&& $file->getPath() != '.')

$files[substr($file->getPath().DIRECTORY_SEPARATOR.$file->getFilename(),2)] =




if (isset($opt['version'])) {

$version = $opt['version'];

$file = "buildFromIterator(new ArrayIterator($files));


$phar = null;



Additionally, it may be advisable to make a PEAR package as a standard unix-console utility that when run with no arguments prints its own usage instruction:


#php app.phar

myDaemon version 0.1 Debug


--daemon – run as daemon

--debug – run in debug mode

--settings – print settings

--nofork – not run child processes

--check – check dependency modules

--master – run as master

--proc=[8] – run child processes


# Conclusion

Creating daemons in PHP it is not hard but to make them run correctly it is important to follow the steps described in this article.

Post a comment here if you have questions or comments on how to create daemon services in PHP.

4720 views · 3 years ago

![Underclocking a Website](

For those of you not familiar with the concept of underclocking: it's the opposite of overclocking, that is, you don't speed up CPU but instead slow it down..

### What for?

Ask the underclockers, I'm totally not sure. Actually, hanging around the Web these days leaves a feeling that nearly every website out there must have been underclocked, but most of the time it's about tons of unnecessary images, megabytes of javascript (of which hardly a hundred kilobytes gets actually executed), and all that. In this post I will, however, tell you about a server-side approach to underclocking, with a help of our good old friend - the MySQL Database Server.

Today I had a nice chat in my client's development telegram channel. The two other devs, R** and V**, were making a switch of the old image API app to a new MySQL server. A couple of days before that, we have discussed a plan, it was as dumb as possible, just as I like it. Super-simple clear steps that a five-year-old can make. Switch to readonly mode (stop uploads), dump DB, restore the dump on the new server, update database connection details, turn off readonly mode. What could possibly go wrong?

Nothing. Except that it did go wrong. The app that I'm talking about, is a really ancient piece of what is gently called "legacy". Once the app was back to normal again, we noticed a significant slowdown on every page that made use of images. Before that point, I never got to that app and/or its database. I logged in to the MySQL console, and started investigating, at the same point chatting with colleagues.


Me: Is that really important that the tables are MyISAM? It's 2018, you know.. There are dozens of queries in queue waiting for table-level locks.

R**: Are they MyISAM? Really?

Me: Yes.. Any objection against converting them to InnoDB? With the current state of the website, with all those tons of Gateway Timeouts, it's not going to make it worse if I do it right now..


10 minutes later:


Me: Nah, it didn't help a lot.. But, looking at the SHOW PROCESSLIST output, I see something weird. What, do you think, this query does? SELECT LAST_INSERT_ID() FROM images?

R**: ehh... Gets you the last AUTO_INCREMENT id from images table?

Me: Let's play another good news bad news joke.. Good news: you're right, it gets you the last AUTO_INCREMENT id. Bad news: it's not for table, it's for the session. Worse news: this query gets you the last AUTO_INCREMENT id and does it exactly as many times as there are rows in the images table. how many are there?

R**: about 8mln. #@%&! It's sending 8mln rows on every image upload, through the network!

Me: Bingo! 8mln rows, with one and the same integer value in all of them.

R**: Ouch... Aaaand... Before today, it was not an issue. Because the database was on the same server as the application..

Me: Exactly, it used the loopback interface, and now it's using ehternet, which, apparently, doesn't have a super good bandwidth. We don't have a gigabit channel between servers, do we?

R**: No, it's 100 Mbit

Me: Are you fixing the query, BTW?

R**: yeah, man, deploying it...


Another 10 minutes later, problem is gone, performance is back to normal.

### What conclusions can one make from this story?

I can think of two at least:

**First: never underestimate legacy code.** The ways it can move to bite you in the ass, are mysterious.

**Second: if you're working with MySQL or another RDBMS, learn SQL**, learn the specific SQL dialect you're using and learn how to trouble shoot issues. In this case, I did not need to look in the PHP code at all in order to help my fellow colleagues out. You can also generalize this principle as "you have to know the tools you're using".

Happy optimizing, folks! Comments appreciated!

2638 views · 3 years ago

![Happy Thanksgiving](

A brief (by Mike's standards) note

> As we express our gratitude, we must never forget that the highest appreciation is not to utter words, but to live by them. - John F. Kennedy

I wanted to take a brief moment to express my gratitude this holiday season. First and foremost, a huge thank you to the beautiful Tanja Hoefler who has put in countless hours behind the scenes of Nomad PHP, ranging from finding the best articles and tweeting them out, to tracking down great speakers, to countless hours of video editing (including fixing all my mistakes from the live broadcast).

### Thank you to our Founders

I also need to thank Cal and Kathy Evans, an amazing husband and wife team who have done so much for the community over many, many years - including founding and being an invaluable source as Tanja and I took over Nomad PHP. They are truly an inspiration for Tanja and myself, and I hope some day we can do as much for the community as they have.

### Thank you to our Speakers

And I need to express my gratitude to our amazing speakers who spend countless hours preparing their presentations, and even stay up all night practicing or get up at 5am to be ready to share their knowledge with the community.

### Thank you to our Advisors

Another special shout out goes to Eric Poe, Eric Hogue, and Andrew Caya who have all been tremendous advocates of Nomad PHP, as well as the foundation of our meetings. Their feedback, along with our amazing Advisory Board has helped shake the direction of Nomad PHP, and the many great things we hope to do in the future.

### Thank you to our Sponsors

Which brings me to our sponsors. As we try to grow and expand Nomad PHP, as well as bring in more resources and make it more valuable (and affordable), we have done so at a fairly significant loss. That's ok, as that was the plan for 2018, but companies like **[RingCentral](**, **[Twilio](**, **[Auth0](**, and **[OSMI](** have played a critical role in letting us move forward and keeping that loss manageable. Without them, I'm not sure we would be able to be offering the service we do, or have the plans we do for 2019!

*On a side note, if you're not familiar with OSMI, they're a GREAT non-profit who has done so much good in the tech space raising awareness about mental health, and educating employers - I highly recommend supporting this great non-profit organization.*

### Thank you to our Family and Friends

Of course, I need to thank my family, my friends, and all those who have supported myself, Tanja, and Nomad PHP over the years.

### Thank YOU

Least, but certainly not last - in fact perhaps most important of all - I want to thank the tremendous Nomad PHP community - over 3,000 members strong - that make Nomad PHP what it is. Without you, Nomad PHP wouldn't exist - it wouldn't need to. And **without you, and the greater PHP community, I wouldn't be here today, doing what I love to do**.

For those that do not know my story, I grew up in medicine - becoming a first responder and pursuing a career as a lifeflight paramedic (helicopter ambulance) before realizing two things... ok three: I had a tremedous fear of heights, I hated needles, and I loved programming.

Leaving the nursing program left me unsure of what to do next, so I did what I loved - programming - where the number of mistakes I made I'm sure outnumbered the lines of good code. If it wasn't for the community being so patient, so encouraging, and helping me grow - I'm not sure what I would be doing today, but it certainly wouldn't involve PHP, Developer Relations, Nomad PHP, or the community.

So for that I want to say one final thank you - a thank you for giving me the gift to do what I love, and the opportunity to hopefully pay this forward, and give back to the community, helping others do the same.

Next year will be an amazing one for Nomad PHP, but I can't thank you all for how incredible and amazing these few short months in 2018 have been - because without you, there would be no 2019.

Have a very wonderful Thanksgiving,


***PS - want to support our 2019 initiatives and be recognized on Nomad PHP in the process? [Become a Supporter](***

10137 views · 3 years ago

![Creating a Virus with PHP](

In his talk, “[Writing Viruses for Fun, Not Profit](,” **[Ben Dechrai](** (after making the viewer take a pledge to only use this knowledge for good and not evil) walks through how many viruses operate, and just how easy it is to build your own self-replicating virus in PHP.

The danger of many of these viruses according to Ben is that the most dangerous viruses often escape detection by not looking like a virus. Instead they encrypt their code to hide their true intent, while also constantly adapting and evolving.

Perhaps even more dangerously, they act like they’re benign and don’t actually do anything - often times laying dormant until called upon by the malicious actor.

### Creating the Virus

What’s scary is just how simple it was for Ben to create such a virus, one that mutated ever so slightly as it infected every other file on the server. Opening up unlimited possibilities from scraping customer data, to DDOS attacks, to simply hijacking your domain.


But those attacks are just the start as Ben demonstrated how easy it is to write new files, delete files, `eval()` and execute foreign code - which could even be extended to accessing the underlying server itself if `shell_exec()` is enabled.

To add to the problem, Ben shares how challenging it can be to identify malicious code on your server as many of these attacks are far more sophisticated than the the virus he created in a matter of minutes - hiding themselves and often appearing as if they are part of the original source code.

### Deploying the Virus

To drive his point home, Ben demonstrates how even seemingly secure systems can be vulnerable - as all it takes is one tiny misstep within your application.

He highlights this by building what should be a secure photo gallery - one that checks the extension and mime-type of the image - and even stores it outside of the public directory. He goes even farther by adding additional sanity checks with a PHP script that then renders the image.

After walking through the code and it’s security features, he then downloads a simple image from the internet. Opening his editor he quickly injects the virus (written in PHP) into the image and uploads it, passing all of the server checks.

Surely, since it passed these checks the system is secure, right? Ben loads the gallery to proudly show off the image - which is just that… an image, with nothing special or out of the ordinary.

Except that when he opens the image gallery files, each has been infected with the malicious code.

The culprit that allowed for Ben to hijack an entire system and execute foreign code, create new files, and even hijack the entire site? When displaying the image the file was included using PHP’s `include()` function, instead of pulling in the data using `file_get_contents()` and echoing it out.

Such a simple mistake provided Ben, if he was a malicious hacker, complete access to all of the files on the system.

### Protecting Yourself

Security always exists in layers - and this could have been prevented by including a few more layers, such as using an open source library to rewrite the image, reviewing the image source before pulling it in, or again not giving it executable access by using the PHP `include()` function.

But what’s terrifying is how simple it is to hijack a site, how easy it is to get access to your system and private data, and how easy it is to overlook security vulnerabilities - especially with open source tooling and those that take plugins.

As Ben explains, sometimes the core code itself is really secure, but then you get two different plugins that when used together accidentally create a security vulnerability. That by itself is one of the most challenging as you can audit each plugin individually, and still not know you’re opening up your system to malicious actors.

This is why it's not just important to stay up to date on the latest [security measures and best practices](, but to be constantly thinking like a hacker and testing your code for vulnerabilities.

### Learn More

You can watch the **[full video](** to learn more how viruses operate, how to quickly build your own PHP virus (but you must promise to use it for good), and what to watch for in order to protect yourself, your customers, and your architecture.

4843 views · 3 years ago

Hey there! This reading is not going to be a technical one. Instead, it's just a little portion of information that you might have not known before. I once worked for a project that did currency exchanges. As you probably know, currencies have 3-letter codes (ISO 4217), and I asked myself if there's a currency with code "PHP".

[PHP: Philippine peso](! In Philippines you can code PHP for PHP!

![Philippine Pesos](

But there's more to it.. "PHP: Prvi Hrvatski Pištolj" stands for "first Croatian pistol". Next time someone tells me that it's too easy to shoot your own leg with PHP, I'll definitely agree.

__If you don't believe me - checkout these [10 most common mistakes PHP programmers make]( from Toptal!__

Or checkout [Eric Wastl's list]( of things in PHP that make him sad. Or these [three weird facts]( about PHP that you might not have known. The thing is PHP is a great programming language for building web applications, but... it's not without it's quirks.

___What else does PHP stand for???___

[Project Honey Pot]( - system targeted at spammers and email harversters.

[Pigeonhole principle]( - if `n` items are put into `m` containers, with `n > m`, then at least one container must contain more than one item. Mathematicians can be even more weird then programmers, can't they? And remember, programmers can right something like `if (true == false)...`

PHP has even more meanings, see [this wikipedia page]( for reference and have _PHun!_