Monthly Archives: October 2016

Cron Job Not Working

Cron jobs seem to be one of the things I have to do often that give me trouble. That's why I'm putting together this guide full of troubleshooting tips for people having problems with cron jobs.

Just today, for example, I wasted several hours figuring out why my cron job didn't seem to be working and here is what happened:

I set up my cron job exactly as I always do according to my own tutorial I posted here:

Linux Cron Job Tutorial

however, it didn't seem to be working so I tried chaing the shebang, changing the php location, etc. with no luck at all.

The Solution

Finally after hours of wasting time, I figured out that the output of my cron job was not going where I thought it would go. For example, my test script created a file and wrote a line to that file to show the cron job ran. My cron test PHP file looked like this:

crontest.php:

<?php

#!/usr/bin/php
<?php
$myFile = "cronresults.txt";
$fh2 = fopen($myFile, 'a') or die("can't open file to append");
$stringData = "appended text from cron job...\n";
fwrite($fh2, $stringData);
fclose($fh2);
?>

Simple, right? well the trick is the $myFile variable works as expected in that it creates the file in the same directory as crontest.php when crontest is called from a web browser. So when I opened up Firefox and went to mysite.com/crontest.php, it worked fine, it would create a file named cronresults.txt in my public_html folder and write a simple line of text to it. However. HERE IS THE TRICKY PART! I call the script in crontest.php from a cron tab by adding the following line in crontab -e:

* * * * * /usr/bin/php   /var/www/mysite.com/public_html/crontest.php

but when I call it that way and look for the cronresults.txt file or look for the line of text it added to the file if it already exists, there is nothing so it appears as if the cron job didn't work! Oh damn! I say. Then I try everything I can think of to fix it. The problem is that is was never broken! When you call a PHP script from a cron job and you do not specify the file path of the results file, it assumes the current users home folder! Therefore, it was working the whole time, but was creating and writing to a file in my /home/root directory because that's the directory I called crontab -e from! THerefore my solution was as simply as replacing the $myFile line with this:

$myFile = "/var/www/mysite.com/public_html/cronresults.txt";

WHEN YOU USE THE ENTIRE PATH IT WORKS AS EXPECTED! I can't over emphasize the importance of this because I wasited several hours due to not knowing this.

Cron Job Troubleshooting Tips

  • Always use a simple test script to test cron jobs for the first time on a new server. You can use my example crontest.php script above, but be careful to set the $myFile variable with the entire path to the output file or you'll have the same problem I wrote about above in this post.
  • Always use a very simple command line in crontab when first testing your cron job. You can customize it after you get it working. I use something like:                               * * * * *  /usr/bin/php  /path/to/cron/crontest.php      then crontest.php will be executed every minute so you can quickly see if it is working. This makes testing and debugging much easier.
  • Can't figure out your Shebang or don't know where PHP is on your server? Then simply go to a command prompt on your server using putty remotely or any command prompt if you are on your own server and type the following command: "which php" without the quotes. That will give you the path to php for both your shebang and your crontab file, like where it says /usr/bin/php in my examples above.

How to Use PHP SESSION Variables in a WordPress Plugin

I was writing a WordPress plugin today that required me to use PHP SESSION variables so the app could save variables across multiple runs of the application. So at first, I tried using SESSION variables in my PHP code just like I would with any other PHP application outside of WordPress, but it failed. So read on for the solution I found that works perfectly and is as simple as adding three lines of code to your plugin or functions.php file.

Add this code to your main plugin file or theme's functions.php file:

function register_session(){
    if(!session_id()) session_start();
}
add_action('init','register_session');

Those four magic lines of code was all I had to add to my main plugin file to make the following code work:

<?php
// Start the session
session_start();

    if(isset($_SESSION['timesran'])){
        $_SESSION['timesran']++;
        $runno = $_SESSION['timesran'];
    }else{
        $runno = 1;
        $_SESSION['timesran'] = 1;
    }
    echo "Run number $runno<br />";
    ?>

So each time the WordPress plugin's application is ran, it increments the timesran session variable successfully as long as I have already added the previous code snippet above to my plugin's main file. The register_session function is needed for sessions to work and should be in your plugin's index.php file or whatever file is your plugin's main file. You can then use PHP session variables in any file within your plugin.

 

How to Restart a Web Server with PHP

Today, I had the task of having to write a PHP script that restarts a web server. This is not allowed by default. It should be noted before I continue, that it is not allowed because it opens a security hole. It makes possible a server attack that would lock up your server by constantly restarting it from PHP. However, now that you're aware of the risk, if you still wish to continue. Here is how it is done:

PHP Code:

    if(exec("sudo service nginx restart")) {
            echo "server restarted!<br />";
        }else{
            echo "ERROR! Server failed to restart!<br />";
        }

Test the above code. NOTE: it is likely not to work because normally you will have to edit the sudoers file on the server.

Edit the Sudoers File to Allow PHP to Use the Restart Command

On the Linode/Nginx server I am working on currently the sudoers file can be found at /etc/sudoers. It can be found in a similar location on most Linux servers. In order to edit the sudoers file on a Linux NGINX server, simply open the file and add the following to the end of the file and save it before restarting the web server:

www-data ALL=(ALL) NOPASSWD: /usr/sbin/service nginx start,/usr/sbin/service nginx stop,/usr/sbin/service nginx restart

Note that your server may require you to edit the sudoers file with visudo.