Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[TUT] PHP Shell Scripting
#1
Tutorial brought to you by, SF Mentors.


Requirements
You need to know what Shell Scripting is, even though I'll explain it a bit.
Understanding of PHP...

Intro
PHP, a language designed for creation of Dynamic Websites, but PHP it self can also be used as a Shell Scripting language, well better say, executed as a Shell Script.
A Shell Script, is a script that is written for mostly for small tasks, so a user doesn't need to execute all the functions on his own.
Shell Script can be useful when you need to do something fast, or automatically on System boot.
In this tutorial I'll show you how to run PHP as a Shell Script, and we'll write a script that checks if a Website is online or offline.

Notice
Linux Systems, have only one PHP "executable", while Windows has 3, these are...
php.exe (CLI Version), php-cgi.exe (CGI Version) and php-win.exe (CLI).
The difference between php.exe and php-win.exe is, php-win.exe executes a script without popping up an CLI window, php.exe displays an window.

Start
The difference between PHP Shell scripts and Website scripts is not big, when writing shell scripts with PHP, you can use all the functions and all your scripts without any worries. One important thing to know is, what streams PHP has to offer.
As any Shell script, PHP has access to STDIN, STDOUT and STDERR streams, these are used for user input and message output.
STDOUT and STDERR are not really as useful as STDIN, an echo or print statement sends the string you want to display to STDOUT, so opening STDOUT stream is not needed, but you still can do it.
STDERR, obviously is used to display errors.
These streams act as files, and can also be accessed as one.

Now let us look at a simple Input/Output shell written in PHP.
PHP Code:
<?php

echo "Hello Shell\nType Something: ";
$stdin fopen("php://stdin""r")
$input fgets($stdinstrlen($stdin));
fclose($stdin);
echo 
"You have typed: "$input"\n";

?>

This Script first sends "Hello Shell to the output stream, then opens a stream for input, the script is now on hold until the user hasn't pressed the ENTER button.
Once the ENTER button was pressed, we use the function "fgets" to read the content in our input stream. Same as every time we access a file, we use "fclose", to close the stream and free the memory.
The last line simply displays what the user has typed.

You can also open up stream for writing, "php://stdout" or "php://stderr", but as you can see "echo" is enough, no need for opening a stream for that, still I'll show you how to...

PHP Code:
<?php

$stdin 
fopen("php://stdout""w")
fputs($stdin"Hello Shell");
fclose($stdin);

?>
The above function does exactly the same thing as "echo" or "print".
Well, as you can see, using echo is simply faster to type.

PHP has also defined constant that are actually pointers to each stream, so instead of actually opening "php://stdin", you can use the constant STDIN. (Thanks Sly)
Example of the first script, accessing the streams with the defined constants.

PHP Code:
<?php

$input 
fgets(STDIN);
echo 
$input;

?>

The difference now is, that we don't have to open and/or close the stream, PHP does that for us.
However, executing the above script with "php.cgi.exe" will generate FATAL ERROR, since "php-cgi.exe" hasn't the constant defined, if you are using "php-cgi.exe" to run your PHP Shell scripts, you will need to open the stream by your self, "php.exe" has the constants STDIN, STDOT and STDERR defined.

Well that is it, not really, but that's actually everything you need to start coding and learning by yourself.

Now, on Windows systems you will need to setup an Environment variable, to get easy access to PHP. Tutorials for that are being linked to at the end of this tutorial.

Let us write something useful, a shell script that will check if a Website is online or offline.

PHP Code:
<?php

while(true)
{
   
$site fgets(STDIN)
   if(
$site == "exit" || $site == "e")
   {
         break;
   }
   elseif(!(
$tmp = @file_get_contents($site)))
   {
       echo 
"{$site} is currently offline. Please check back later!\n";
   }
   else
   {
        echo 
"{$site} is online.\n";
   }
}
?>

This script needs to be executed with "php.exe" on Windows and on linux, well, I think you get it, since linux has only one php "exe"...

We have an "while" block which will run endlessly, "while(true)" and true is always true, lol.
We use the STDIN stream (constant), to give the user the ability to input desired address, or "exit"/"e" to quit/kill the script.
If the user has typed "exit" or "e", we break our "while" loop and the script is finished executing.
Otherwise the script will prompt the user for an address, and try to get it's contents with the function file_get_contents(), the "@" in front of the function is used to suppress errors.

If the function fails, we tell the user that the site is offline, otherwise this site is online.

Also, on Linux systems, the first line of your PHP file needs to declare a "shebang".
Code:
#!path/to/php
// something like
#!usr/bin/php

Example
PHP Code:
#!usr/bin/php
<?php

$input 
fgets(STDIN);
echo 
$input;

?>

That's it.... I have never tested an PHP shell script on *nix systems, so I can't tell much about it.

Sly has improved this Shell a bit more, take a look at the code and learn from it.

PHP Code:
<?php

# Function written by Sly, now go and thank him, gooooooo!!!
function getSite()
{
    
$site null;
    while(empty(
$site))
    {
        echo 
"\nWebsite: ";
        
$tmp trim(fgets(STDIN));
          if(
$tmp == "exit" || $tmp == "e")
          {
               return 
$tmp;
          }
        elseif(
preg_match("/(https*:\/\/)*(.+)*(\..+)$/"$tmp$tmp))
        {
            unset(
$tmp[0]);
            if(empty(
$tmp[1]))
            {
                
$tmp[1] = "http://";
            }
            
            
$site join(""$tmp);
        }
        else
        {
            echo 
"Invalid site. Try again.\n";
        }
    }
    
    return 
$site;
}

echo <<<S
#### SF Mentors #####################################################
# PHP Shell Script - Website down check                             #
# ----------------------------------------------------------------- #
# Written by Gaijin :: Optimized by Sly                             #
# Usage: Simply type in an address, to end type "exit" or "e"       #
#####################################################################

S;

while(
true)
{
   
$site getSite();
   if(
$site == "exit" || $site == "e")
   {
         break;
   }
   elseif(!(
$tmp = @file_get_contents($site)))
   {
       echo 
"{$site} is currently offline. Please check back later!\n";
   }
   else
   {
        echo 
"{$site} is online.\n";
   }
}

?>

Shell script in use
[Image: aufzeichnenf.png]

http://php.net/manual/en/faq.installation.php
http://php.net/manual/en/install.windows.php
Reply
#2
This was very informative. I didn't know PHP had this capability.
Reply
#3
(05-18-2011, 12:25 PM)KoBE Wrote: This was very informative. I didn't know PHP had this capability.

Not only that is HAS, it is really useful.
Let's say, in case your Server has access to a Shell you can write scripts that will make your life easier. For example, you could write a Script that makes backups of all or single files every X seconds/minutes.... etc...
But you're also not only limited to your Server, as you can see it can be executed from your own System and do the same thing.

I was working on a Script, which I will post it as soon as I can access the files on my HDD.
The script has functions to check a site for broken links, keywords, on/offline, site validation and some security testing functions, SQL Injection for example....

I'm glad you like it... There is more to tell about this subject, but I'm still checking it out....
This tutorial is just to give people a feeling of what PHP is capable of....
Reply
#4
Well this is a nice tutorial Gaijin Well me too I never knew that PHP can do this / has a capability like this Smile thanks for the share mate , this will help many of us in here.
Reply
#5
(05-20-2011, 02:55 AM)stephen5565 Wrote: Well this is a nice tutorial Gaijin Well me too I never knew that PHP can do this / has a capability like this Smile thanks for the share mate , this will help many of us in here.

Thx....
I did now about the Shell possibilities with PHP, but never actually written any code. I took a time too look at it, in cease you run own server, this can become useful.
Reply
#6
Thats a pretty nice idea for a tutorial actually I like it.

Thanks for the information I will add this to my collection of things to read properly when I learn PHP over the summer Smile
Reply
#7
Not going to lie, I actually learned something. And here I've been using ncurses. D'oh!
[Image: TYzKF.png]
Reply
#8
I only scanned it, but it looks really nice. Great job, Gaijin.
Reply
#9
Looks quite nice, well done.

I may look a bit further into this later on!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PHP Framework List: An Ultimate Guide to 102 PHP Frameworks for Web Developers tk-hassan 0 943 07-27-2020, 11:26 PM
Last Post: tk-hassan
  PHP Video Tutorials (PHP For Beginners) Eleqtriq 4 3,671 10-10-2011, 01:00 PM
Last Post: Greyersting
  [TUT] PHP Password Protected Page PurpleHaze 23 6,994 05-20-2011, 02:56 AM
Last Post: stephen5565
  [TUT] Pagination using PHP Gaijin 7 4,970 11-01-2010, 09:01 AM
Last Post: Arеs
  PHP Tut 4 Minus-Zero 1 929 07-21-2010, 09:39 PM
Last Post: `P R O D I G Y™

Forum Jump:


Users browsing this thread: 1 Guest(s)