cPanel and CRON

I just created a cron job in cpanel, but it’s not working.

I just want to get something straight, because maybe I am doing it wrong…

If I go and create a file which creates a new file, ie:


$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\
";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\
";
fwrite($fh, $stringData);
fclose($fh);

…and then run it in my browser, it creates a file called testFile.txt.

All good so far

I thought that all I had to do to add a cron in cpanel was to set the time for the cron (ie: every 5 minutes for testing purposes, but once I have it all running, I’ll change it to once every 24 hours)… and then just add the location of the file I want to run.

ie:

/home/mysite/public_html/myfile.php

…I did all that, but it’s not working.

What’s the deal? Am I doing it wrong?

Am I supposed to enter some sort of command, as per step 4 of these instructions (instead of just the file loction)?

cPanel Tutorial - Cron Jobs

You need to take in to account that php cron jobs are not run with the current directory set to the directory the file is in; it’s some other directory. To make sure you get the correct files, use absolute paths, or something like


$myFile = dirname(__FILE__)."/testFile.txt"

this has to be at the very top of your file, before anything else

#! /usr/bin/php -q

For example

#! /usr/bin/php -q
<?php
// script goes here...
?>

You may need to chmod your file to 0755 as well.

It’s most likely a path issue. When you run scripts from a webserver environment your webserver is “sand-boxed”. In other words your webserver thinks it’s directory begins at /home.

When you run things via the cron daemon the cron daemon is not in the relative sandbox that the webserver is, so you have to use the actual path which is most likely something like /var/www/username/public_html/home or something along those lines.

If you are unsure what the direct path is for your webserver directory you can use a nifty little php function to spit it out, then you can hard write the path into your script.

For example, create a file called true_dir.php and put the following in it.

<?
//Run this from your web browser
//Get the true path of a scripts execution.

echo $_SERVER['SCRIPT_FILENAME']; //<-- This will spit out the true directory
?>

Then in your cron script, hardwrite the path into your script.

<?
$_SERVER['DOCUMENT_ROOT'] = '/var/www/username/etc/etc/etc/etc';
?>

Then you can use $_SERVER[‘DOCUMENT_ROOT’] to write out your files like normal. Give that a shot and let us know how it goes.

Also don’t forget to make sure you have write privileges into which ever directory you are wanting to write the files.

That would depend on whether he’s executing the file in his cron, or executing the php engine and calling the file as a parameter.