{"id":337,"date":"2018-05-25T17:04:58","date_gmt":"2018-05-25T17:04:58","guid":{"rendered":"https:\/\/blog.hassler.ec\/wp\/?p=337"},"modified":"2018-05-25T17:10:03","modified_gmt":"2018-05-25T17:10:03","slug":"maintaining-your-server-with-command-line-php","status":"publish","type":"post","link":"https:\/\/blog.hassler.ec\/wp\/2018\/05\/25\/maintaining-your-server-with-command-line-php\/","title":{"rendered":"Maintaining your Server with Command Line PHP"},"content":{"rendered":"<p>More and more in the Information Technology field are we asked to put on various hats and fill multiple roles in our daily jobs. Not only are many of us given the task to create and maintain a web site, but also to maintain the server its hosted on. Usually when maintaining a server you need to know how to write scripts and small programs to automate tasks. A lot of these scripts are written in Perl, Bash, or some other scripting language. Now I\u2019m not against learning new programming languages at all, but did you know that not only can you use PHP to write great web applications, but you can use PHP from the command line as well? You can use the PHP that you already know and love to keep that server running great, all from the command line!<\/p>\n<p>In this article we\u2019ll look at the advantages of using PHP CLI. I\u2019ll show you how to test PHP\u2019s Command Line Interface \/ Interpreter (CLI) on your server, and then we\u2019ll look at some of the options available for PHP CLI including the interactive shell and how to create executable scripts. Finally, I\u2019ll give you a couple of examples of scripts to use to maintain your server written in PHP.<\/p>\n<p>One of the biggest advantages of using PHP CLI instead of some other scripting language is the ability to reuse code from previous projects in your script. Whether it be a database class or a function that you created or maybe a file parsing program, with PHP CLI you don\u2019t have to rewrite any of your code.<\/p>\n<div id=\"maestro-682\" class=\"widget maestro maestro-content-type-html hide-for-mobile-SP\">\n<div>\n<div id=\"aniBox\">\n<div id=\"aniplayer_aniviewJS\">\n<div id=\"aniplayer_aniviewJSgui\">\n<div id=\"av-container\" class=\" desktop hide-controls\">\n<div id=\"av-inner\">\n<div id=\"slot\">\n<div id=\"imgpreloader\"><\/div>\n<div id=\"preloader\"><\/div>\n<div id=\"videoslot\" class=\"loaded\"><\/div>\n<\/div>\n<div id=\"gui\">\n<div id=\"aniview-credit\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"anibid\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>You can also automate many tasks written with PHP CLI with CRON. If you have never used CRON before, it\u2019s a daemon program that runs specified scripts at specific times on your server. Need to generate a report for the sales department on Mondays, Wednesdays, and Fridays? Write a PHP script to do it, throw it into a CRON job, and sit back and relax while PHP and CRON do the work for you.<\/p>\n<h2>Running PHP CLI Scripts<\/h2>\n<p>If you are running a recent version of PHP, chances are you already have PHP CLI installed on your system. If the examples in this article don\u2019t work for you, then you\u2019ll probably need to recompile PHP with the\u00a0<code class=\" language-undefined\">--enable-cli<\/code>\u00a0option or reinstall a PHP package that contains that option. The easiest way to test to see if everything is working is to open up a new terminal window or SSH session to your server or computer and from the command line type in\u00a0<code class=\" language-undefined\">php -v<\/code>.<\/p>\n<pre>Stephens-Laptop:~ <strong>sthorpe$ php -v<\/strong>\r\nPHP 5.3.8 (cli) (built: Dec  5 2011 21:24:09)\r\nCopyright (c) 1997-2011 The PHP Group\r\nZend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies<\/pre>\n<p>Let\u2019s try a quick example where we will run an actual PHP file from the command line. Create a file called\u00a0<code class=\" language-undefined\">test.php<\/code>\u00a0with the following code using your favorite editor:<\/p>\n<pre class=\" language-php\"><code class=\" language-php\"><span class=\"token delimiter\">&lt;?php<\/span>\r\n<span class=\"token variable\">$str<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"SitePoint is the best!\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">echo<\/span> <span class=\"token variable\">$str<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token string\">\"n\"<\/span><span class=\"token punctuation\">;<\/span><\/code><\/pre>\n<p>To execute the script, all you have to do is type in\u00a0<code class=\" language-undefined\">php test.php<\/code>\u00a0and you\u2019ll see the output on the command line.<\/p>\n<pre>Stephens-Laptop:~ sthorpe$ php test.php\r\nSitePoint is the best!<\/pre>\n<p>A more preferred method of running PHP scripts on the command-line is to change the permissions mode of the script and place\u00a0<code class=\" language-undefined\">#!\/usr\/bin\/php<\/code>\u00a0at the top of the file before the opening\u00a0<code class=\" language-undefined\">&lt;?php<\/code>\u00a0tag (your path to PHP may be different depending on your system\u2019s configuration). To accomplish this, you\u2019ll use the\u00a0<code class=\" language-undefined\">chmod<\/code>\u00a0command on UNIX-based systems.<\/p>\n<pre class=\" language-php\"><code class=\" language-php\"><span class=\"token shell-comment comment\">#!\/usr\/bin\/php<\/span>\r\n<span class=\"token delimiter\">&lt;?php<\/span>\r\n<span class=\"token variable\">$filepath<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">exec<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"pwd\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">echo<\/span> <span class=\"token string\">\"You are in the $filepath directory.n\"<\/span><span class=\"token punctuation\">;<\/span><\/code><\/pre>\n<pre>Stephens-Laptop:~ sthorpe$ <strong>chmod +x pwd.php<\/strong>\r\nStephens-Laptop:~ sthorpe$ <strong>.\/pwd.php<\/strong>\r\nYou are in the ~ directory.<\/pre>\n<h2>CLI Options and the Interactive Shell<\/h2>\n<p>I\u2019ve already shown you one of PHP\u2019s command-line options earlier,\u00a0<code class=\" language-undefined\">-v<\/code>\u00a0which gives you the version number of PHP installed on your system, but there are more options available. For example, if you wanted to share the code from a script you wrote with someone as web page and have it syntax highlighted for better readability, you can use the\u00a0<code class=\" language-undefined\">-s<\/code>\u00a0option. PHP will output the appropriate HTML code.<\/p>\n<pre>Stephens-Laptop:~ sthorpe$ <strong>php -s test.php &lt; test.html<\/strong><\/pre>\n<p>When viewed in a web browser, the resulting\u00a0<code class=\" language-undefined\">test.html<\/code>\u00a0presents the highlighted code:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-2264\" title=\"cli-php-thorpe01\" src=\"https:\/\/dab1nmslvvntp.cloudfront.net\/wp-content\/uploads\/2012\/04\/cli-php-thorpe01.png\" alt=\"\" width=\"430\" height=\"279\" \/><\/p>\n<p>Another helpful option is\u00a0<code class=\" language-undefined\">-l<\/code>\u00a0to check your scripts for any syntax errors. If no errors are found in the file, PHP will report back there were no syntax errors. Otherwise PHP will report the error it found and on which line it occurred.<\/p>\n<pre>Stephens-Laptop:~ sthorpe$ <strong>php -l broken.php<\/strong>\r\nPHP Parse error:  syntax error, unexpected T_VARIABLE in broken.php on line 3\r\nErrors parsing broken.php<\/pre>\n<p>In addition to the numerous options available, with PHP CLI you can test out ideas in PHP code right from the shell without having to create any files at all! This is useful when you want to see what the results of a function might be. To run PHP\u2019s interactive shell use\u00a0<code class=\" language-undefined\">-a<\/code>. PHP will report back \u201cInteractive shell\u201d and the prompt will change to\u00a0<code class=\" language-undefined\">php &gt;<\/code>. From this point forward you can just type your code and PHP will execute it immediately. To exit the shell, you can either press CTRL + D or call\u00a0<code class=\" language-undefined\">exit<\/code>.<\/p>\n<pre>Stephens-Laptop:~ sthorpe$ <strong>php -a<\/strong>\r\nInteractive shell\r\n\r\nphp &gt; <strong>echo 2 + 2;<\/strong>\r\n4\r\nphp &gt; <strong>exit;<\/strong><\/pre>\n<h2>Getting Input<\/h2>\n<p>With CLI programming, you have two options for input functionality. The first option is to pass arguments to your script directly from the command line. The second option is reading the input from the keyboard (standard input) from the user running the script.<\/p>\n<p>To accept arguments into your script, you\u2019ll use the predefined superglobal variables\u00a0<code class=\" language-undefined\">$_SERVER[\"argc\"]<\/code>\u00a0and\u00a0<code class=\" language-undefined\">$_SERVER[\"arvc\"]<\/code>. Create a file called\u00a0<code class=\" language-undefined\">arguments.php<\/code>containing the code below:<\/p>\n<pre class=\" language-php\"><code class=\" language-php\"><span class=\"token shell-comment comment\">#!\/usr\/bin\/php<\/span>\r\n<span class=\"token delimiter\">&lt;?php<\/span>\r\n<span class=\"token keyword\">echo<\/span> <span class=\"token string\">\"There are \"<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token global\">$_SERVER<\/span><span class=\"token punctuation\">[<\/span><span class=\"token string\">\"argc\"<\/span><span class=\"token punctuation\">]<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token string\">\" arguments:n\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">foreach<\/span><span class=\"token punctuation\">(<\/span><span class=\"token global\">$_SERVER<\/span><span class=\"token punctuation\">[<\/span><span class=\"token string\">\"argv\"<\/span><span class=\"token punctuation\">]<\/span> <span class=\"token variable\">$arv<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n   <span class=\"token keyword\">echo<\/span> <span class=\"token string\">\"t\"<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token variable\">$arv<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token string\">\"n\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span><\/code><\/pre>\n<p><code class=\" language-undefined\">$_SERVER[\"argc\"]<\/code>\u00a0contains the number of arguments that were passed to the script, and\u00a0<code class=\" language-undefined\">$_SERVER[\"argv\"]<\/code>\u00a0is an array containing all the values of those arguments. You will always have at least one argument since the file name itself is considered the first argument.<\/p>\n<p>Make the file executable and pass in a few arguments with a space in between each one. The script will display the total number of arguments and list each one.<\/p>\n<pre>Stephens-Laptop:~ sthorpe$ <strong>php arguments.php SitePoint Rocks<\/strong>\r\nThere are 3 arguments\r\n   arguments.php\r\n   SitePoint\r\n   Rocks<\/pre>\n<p>Accepting input from standard input lets you create interactive scripts which can prompt for specific information. Create a file called\u00a0<code class=\" language-undefined\">keyboard.php<\/code>\u00a0with the following code:<\/p>\n<pre class=\" language-php\"><code class=\" language-php\"><span class=\"token shell-comment comment\">#!\/usr\/bin\/php<\/span>\r\n<span class=\"token delimiter\">&lt;?php<\/span>\r\n<span class=\"token keyword\">echo<\/span> <span class=\"token string\">\"Hi There! what is your favorite web site?n\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$site<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">fread<\/span><span class=\"token punctuation\">(<\/span><span class=\"token constant\">STDIN<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token number\">80<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$site<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">trim<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$site<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$site<\/span> <span class=\"token operator\">!=<\/span> <span class=\"token string\">\"SitePoint\"<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n   <span class=\"token keyword\">echo<\/span> <span class=\"token string\">\"Are you sure that one is your favorite?n\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n<span class=\"token keyword\">else<\/span> <span class=\"token punctuation\">{<\/span>\r\n   <span class=\"token keyword\">echo<\/span> <span class=\"token string\">\"I knew it! Me too!n\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span><\/code><\/pre>\n<p>In this example we are using the\u00a0<code class=\" language-undefined\">fread()<\/code>\u00a0function just as we would to read in a file, but in this case the handle is the PHP predefined constant\u00a0<code class=\" language-undefined\">STDIN<\/code>. Once again make the file executable and run the file; hopefully your output will be the same as mine.<\/p>\n<pre>Stephens-Laptop:~ sthorpe$ <strong>php keyboard.php<\/strong>\r\nHi There! what is your favorite web site?\r\nSitePoint\r\nI knew it! Me too!<\/pre>\n<h2>Some PHP CLI Examples<\/h2>\n<p>When monitoring a server, one thing worth keeping track of is your available disk space. These days hard drives are so huge that you wouldn\u2019t think that there was a way you could possibly fill up all that space, but trust me\u2026 it can happen when you least expect it. Maybe your log rotation process broke and you didn\u2019t realize it, or your temp directory grew out of control. Here\u2019s an example you can use to keep an eye on your server\u2019s disk space:<\/p>\n<pre class=\" language-php\"><code class=\" language-php\"><span class=\"token shell-comment comment\">#!\/usr\/bin\/php<\/span>\r\n<span class=\"token delimiter\">&lt;?php<\/span>\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ config options<\/span>\r\n<span class=\"token variable\">$disk<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"\/dev\/disk0s2\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$threshold<\/span> <span class=\"token operator\">=<\/span> <span class=\"token number\">90<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$emailAddr<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"you@example.com\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$emailName<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"Your Name Here\"<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token function\">exec<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"df -h \"<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token variable\">$disk<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token variable\">$output<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">foreach<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$output<\/span> <span class=\"token keyword\">as<\/span> <span class=\"token variable\">$line<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token variable\">$info<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">strstr<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$line<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token variable\">$disk<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$info<\/span> <span class=\"token operator\">!=<\/span> <span class=\"token string\">\"\"<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n        <span class=\"token keyword\">break<\/span><span class=\"token punctuation\">;<\/span>\r\n    <span class=\"token punctuation\">}<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n<span class=\"token variable\">$pos<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">stripos<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$info<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"%\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$pos<\/span> <span class=\"token operator\">=<\/span> <span class=\"token variable\">$pos<\/span> <span class=\"token operator\">-<\/span> <span class=\"token number\">3<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$used<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">substr<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$info<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token variable\">$pos<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token number\">3<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$used<\/span> <span class=\"token operator\">&gt;=<\/span> <span class=\"token variable\">$threshold<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">mail<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$emailAddr<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"System HD Notification\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"Main disk is at \"<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token variable\">$used<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token string\">\"%\"<\/span> <span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"From: $emailName\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span><\/code><\/pre>\n<p>The function\u00a0<code class=\" language-undefined\">exec()<\/code>\u00a0executes a command in the command line and accepts two parameters: the first is the actual command (in this case\u00a0<code class=\" language-undefined\">df<\/code>\u00a0which displays disk space information), and the second is an array reference that is filled with the command\u2019s output. The\u00a0<code class=\" language-undefined\">$disk<\/code>\u00a0variable holds the path of the disk you want to monitor (in my case it\u2019s\u00a0<code class=\" language-undefined\">\/dev\/disk0s2<\/code>). The\u00a0<code class=\" language-undefined\">df<\/code>\u00a0command outputs various other data than just disk space used, so we\u2019ll only be looking for specific information from the\u00a0<code class=\" language-undefined\">$output<\/code>\u00a0array.<\/p>\n<p>The code continues by looping through the array and using the\u00a0<code class=\" language-undefined\">strstr()<\/code>\u00a0function to find the desired disk and break out of the loop once it\u2019s been found. I strip out the part of the string that contains the percentage of disk space left with using\u00a0<code class=\" language-undefined\">substr()<\/code>\u00a0and compare it to a predetermined value, in this case if the hard drive usage reaches 90% or more. If so, the script sends an email alerting me with the information.<\/p>\n<p>You could have this quick script run as a cron job every 30 minutes or so and it should give you some peace of mind.<\/p>\n<p>Another common task when maintaining a server is to insure that you have a constant backup of files and folders. If some sort of version control of back-up service isn\u2019t available for whatever reason, this next script can be used to back up some folders and a database and send them to an off-site SFTP server.<\/p>\n<pre class=\" language-php\"><code class=\" language-php\"><span class=\"token shell-comment comment\">#!\/usr\/bin\/php<\/span>\r\n<span class=\"token delimiter\">&lt;?php<\/span>\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ remote SFTP connection credentials<\/span>\r\n<span class=\"token variable\">$sftpServerIP<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"10.0.0.1\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$sftpUsername<\/span>  <span class=\"token operator\">=<\/span> <span class=\"token string\">\"sftpuser\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$sftpPassword<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"hushhush\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$sftpTarget<\/span>   <span class=\"token operator\">=<\/span> <span class=\"token string\">\"\/home\/sftpuser\"<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ mail notification config<\/span>\r\n<span class=\"token variable\">$emailAddr<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"you@example.com\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$emailName<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"Your Name Here\"<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ MySQL database connection credentials<\/span>\r\n<span class=\"token variable\">$mysqlUsername<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"dbuser\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$mysqlPassword<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"secret\"<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$mysqlDatabase<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"myDatabase\"<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ list of directories and files to back up<\/span>\r\n<span class=\"token variable\">$files<\/span> <span class=\"token operator\">=<\/span> <span class=\"token keyword\">array<\/span><span class=\"token punctuation\">(<\/span>\r\n    <span class=\"token string\">\"\/home\/username\/important-file.txt\"<\/span><span class=\"token punctuation\">,<\/span>\r\n    <span class=\"token string\">\"\/home\/username\/special-folder\"<\/span><span class=\"token punctuation\">,<\/span>\r\n    <span class=\"token string\">\"\/var\/spool\/another-folder\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ create temporary directory and copy files\/directories to it<\/span>\r\n<span class=\"token variable\">$tmpFolder<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">\"\/tmp\/\"<\/span> <span class=\"token punctuation\">.<\/span> <span class=\"token function\">uniqid<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token function\">mkdir<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$tmpFolder<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token number\">0700<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">foreach<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$files<\/span> <span class=\"token keyword\">as<\/span> <span class=\"token variable\">$f<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">exec<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"cp -r $f $tmpFolder\/\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ dump the database content<\/span>\r\n<span class=\"token function\">exec<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"mysqldump -u $mysqlUsername -p$mysqlPassword $mysqlDatabase &gt; $tmpFolder\/backup.sql\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ compress the backup<\/span>\r\n<span class=\"token function\">exec<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"tar -czf $tmpFolder.tgz $tmpFolder\/*\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ establish the sftp connection<\/span>\r\n<span class=\"token variable\">$session<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">ssh2_connect<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$sftpServerIP<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token number\">22<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$session<\/span> <span class=\"token operator\">===<\/span> <span class=\"token boolean\">false<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">mail<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$emailAddr<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"System Backup\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"Could not connect to SFTP server\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"From: $emailName\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n    exit<span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n<span class=\"token variable\">$result<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">ssh2_auth_password<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$session<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token variable\">$sftpUsername<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token variable\">$sftpPassword<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$result<\/span> <span class=\"token operator\">===<\/span> <span class=\"token boolean\">false<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">mail<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$emailAddr<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"System Backup\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"Could not authenticate to SFTP server\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"From: $emailName\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n    exit<span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n<span class=\"token variable\">$sftp<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">ssh2_sftp<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$session<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$sftp<\/span> <span class=\"token operator\">===<\/span> <span class=\"token boolean\">false<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">mail<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$emailAddr<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"System Backup\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"Could not initialize SFTP subsystem\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"From: $emailName\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n    exit<span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ transfer the backup file<\/span>\r\n<span class=\"token variable\">$date<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">date<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"D\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token variable\">$upload<\/span> <span class=\"token operator\">=<\/span> <span class=\"token function\">file_put_contents<\/span><span class=\"token punctuation\">(<\/span>\r\n    \"ssh2<span class=\"token punctuation\">.<\/span>sftp<span class=\"token punctuation\">:<\/span><span class=\"token comment\" spellcheck=\"true\">\/\/\" . $sftp . $sftpTargetDir . \"\/backup-$date.tgz\", <\/span>\r\n    <span class=\"token function\">file_get_contents<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"$tmpFolder.tgz\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n\r\n<span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token variable\">$upload<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">mail<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$emailAddr<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"System Backup\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"Your files has been backed up successfully\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"From: $emailName\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n<span class=\"token keyword\">else<\/span> <span class=\"token punctuation\">{<\/span>\r\n    <span class=\"token function\">mail<\/span><span class=\"token punctuation\">(<\/span><span class=\"token variable\">$emailAddr<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"System Backup\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"Something went wrong with the upload of the backup\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\"From: $emailName\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\r\n<span class=\"token punctuation\">}<\/span>\r\n\r\n<span class=\"token comment\" spellcheck=\"true\">\/\/ clean up the local temp backups<\/span>\r\n<span class=\"token function\">exec<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"rm -r $tmpFolder $tmpFolder.tgz\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span><\/code><\/pre>\n<p>Again we use the\u00a0<code class=\" language-undefined\">exec()<\/code>\u00a0function to execute other programs and commands from within our PHP script, such as\u00a0<code class=\" language-undefined\">mysqldump<\/code>\u00a0to dump the database content and\u00a0<code class=\" language-undefined\">tar<\/code>\u00a0to compress the backup folder into an archive. into the variable we defined before. Connecting to the SFTP server uses PHP\u2019s\u00a0<a href=\"http:\/\/www.php.net\/manual\/en\/book.ssh2.php\">SSH2 extension<\/a>, so you\u2019ll need to have that extension installed. A good write up can be found in\u00a0<a href=\"http:\/\/kevin.vanzonneveld.net\/techblog\/article\/make_ssh_connections_with_php\/\">Kevin van Zonneveld\u2019s blog<\/a>. The code shouldn\u2019t be too difficult to modify if you want to use a pure solution like\u00a0<a href=\"http:\/\/phpseclib.sourceforge.net\/\">phpseclib<\/a>\u00a0or even an older (and insecure) protocol like FTP. Regardless of your approach, the sample highlights some of the benefits of scripting such tasks with PHP.<\/p>\n<h2>Summary<\/h2>\n<p>In this article we explored using PHP from the command line to write server maintenance scripts. I talked about the advantages of using PHP CLI, including the ability to automate your scripts. We went over some neat options available, like the ability to test your scripts for syntax errors and using interactive mode. We also learned about the different input functionality available, including accepting input straight from the keyboard. I then gave you two real world examples of scripts to use to maintain your own servers which included a hard drive monitoring script and a backup script.<\/p>\n<p>I hope this article has given you some ideas and knowledge that will help you in the future when you are given the task to maintain that server, and I hope you can also use these CLI example scripts as a bases to create your own maintenance scripts.<\/p>\n<p><small>Image via\u00a0<a href=\"http:\/\/www.shutterstock.com\/gallery-676222p1.html\">Chengyuan Yang<\/a>\u00a0\/\u00a0<a href=\"http:\/\/www.shutterstock.com\/\">Shutterstock<\/a><\/small><\/p>\n<div class=\"Article_authorBio l-mv4 t-bg-white m-border l-pa3\">\n<div class=\"l-d-f l-pt3\">\n<p><a class=\"l-s5 l-pa0 l-mr3 l-round l-o-h\" href=\"https:\/\/www.sitepoint.com\/author\/sthorpe\/\"><img loading=\"lazy\" decoding=\"async\" class=\"avatar avatar-96 wp-user-avatar wp-user-avatar-96 photo avatar-default\" src=\"https:\/\/secure.gravatar.com\/avatar\/4ca928b1ea9d145db42f357366477f71?s=96&amp;d=mm&amp;r=g\" alt=\"\" width=\"96\" height=\"96\" \/><\/a><\/p>\n<div class=\"f-lh-title\">\n<div class=\"f-c-grey-300\">Meet the author<\/div>\n<div class=\"f-large\"><a class=\"f-bold f-c-grey-500\" href=\"https:\/\/www.sitepoint.com\/author\/sthorpe\/\">Stephen Thorpe<\/a><\/div>\n<\/div>\n<\/div>\n<div class=\"f-light f-lh-copy l-mt3\">Stephen Thorpe is originally from London but now living in Tennessee. He works at an Internet and Telephone company as an applications developer primarily using PHP and MySQL.<\/div>\n<div><\/div>\n<\/div>\n<div><strong>Tomado de\u00a0\u00a0<\/strong><\/div>\n<div><strong><a href=\"https:\/\/www.sitepoint.com\/\"><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-338 alignnone\" src=\"https:\/\/blog.hassler.ec\/wp\/wp-content\/uploads\/2018\/05\/sitepoint-300x93.png\" alt=\"\" width=\"300\" height=\"93\" srcset=\"https:\/\/blog.hassler.ec\/wp\/wp-content\/uploads\/2018\/05\/sitepoint-300x93.png 300w, https:\/\/blog.hassler.ec\/wp\/wp-content\/uploads\/2018\/05\/sitepoint.png 402w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\" \/><\/a><\/strong><\/div>\n<div><a href=\"https:\/\/www.sitepoint.com\/maintaining-your-server-with-command-line-php\/\"><strong>\u00a0https:\/\/www.sitepoint.com\/maintaining-your-server-with-command-line-php\/<\/strong><\/a><\/div>\n<h4><\/h4>\n<div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>More and more in the Information Technology field are we asked to put on various hats and fill multiple roles [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":206,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[28,29,16],"tags":[32,30,31,19],"class_list":["post-337","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php","category-programacion","category-servidores","tag-automatizacion","tag-php","tag-programacion","tag-servidores"],"_links":{"self":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts\/337","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/comments?post=337"}],"version-history":[{"count":2,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts\/337\/revisions"}],"predecessor-version":[{"id":340,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/posts\/337\/revisions\/340"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/media\/206"}],"wp:attachment":[{"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/media?parent=337"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/categories?post=337"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.hassler.ec\/wp\/wp-json\/wp\/v2\/tags?post=337"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}