Categories
PHP

Calling system() on PHP

PHP is no longer just a scripting language for web automation. It has grown very rapidly and now holds the position of the 3rd most popular programming language worldwide. PHP is now being widely used for CLI programs and even GUIs 😀

While working on a daemon script at Leevio, I was executing a shell script using the shell_exec() function. Rana vai pointed me to the system() function which is quite identical to it’s C equivalent. I was really glad to have found it at last. I was looking for a function that has interactive output like Python’s os.system() call. It was in PHP from PHP4 and I never looked into it! 🙁 Shame on me!

The system() function takes a command, executes it, prints out all the outputs of the command and returns the last line of the output. We can additionally pass a variable as the optional second parameter that will hold the entire return value.

The “ls” command lists all the contents of a directory. The above php script is supposed to print out all the contents of the current working directory aka CWD 😀

Categories
PHP

Running a PHP Script as Daemon

For our ongoing project at Leevio, I had to find a way to run a php script as a daemon. I checked out a few techniques. I didn’t like any of them much. I needed a way to run the intended script and then exit the terminal leaving the script to keep running in the background.

After a bit of hard work, I chose to use the PCNTL functions to achieve my goal. Here’s the code I used:

Note that, in this case, the daemon quits the moment the shell_exec() command is executed. We are executing our intended PHP script as a sub process which has been detached from the terminal. The script has a while loop to keep it running forever. So, we can safely quit the main process while the forked process remains alive with the php script being executed 😀

Categories
Python

Python: Printing without newline or space :)

While coding in Python, I have seen that the Print statement adds a newline to it’s output which is very helpful in most cases. While I have to add a newline character manually in PHP, I have to type less in Python. I used to love this feature until I faced a situation when I have to print out data without any newline character or space. I finally found out the solution 🙂 I have to write the characters of a string manually to stdout using the “sys” module.

Have a look at the following codes:

As you can see, I have defined a function masnun_print() that prints out it’s default argument without space just like the echo statement in PHP. To give a line break between the “Hello World!” and the “1 to 100 series”, we have manually printed out newline character 🙂