I have a file called "run.php". I want to make sure that only the server can access that file as a cron job and run it. Is there any kind of code to make sure no one can load the file up in their browser to run it? Thanks in advance!
Are you invoking a web browser in your cron job or just running it directly via the PHP CLI binary? If the latter, check $_SERVER, there are some variables that are always set differently when running CLI vs via a web server. Depending on your hosting environment, you may be able to grant permissions on the script solely to your own user account and deny them to the web server user account. Again this would require using the PHP CLI method.
There is a very simple way to do this: in run.php if($_GET['password']!="y0urp@$$w0rdh3r3") { die("You do not have access to this page."); } else { //Your Code Here } Code (markup): Now for your cron, the link should be: wget http://www.yoursite.com/run.php?password=y0urp@$$w0rdh3r3 I dont know about cPanel cron jobs and wget, so if you are using cPanel, you would use curl instead of wget, unless you know wget works in the cpanel cronjobs (like i said, i donno) I have used this method on a number of sites, and it has never been comprimised, as long as you use a secure password containing numbers, letters(caps and lowercase), and symbols. Hope this was helpful!
I always put my crons in my root folder: ie /home/user/cron whilst the publicly accessable files are at /home/user/public_html
Check if $_SERVER['REMOTE_ADDR'] is set (normally works on most hosts), i.e.: if (!empty($_SERVER['REMOTE_ADDR'])){ die("You are not a cron job!"); } PHP: Jay
Another option (mentioned earlier) is to use .htaccess to protect the directory it resides in (provided that is available). This would block web access to the file. For the cron job, use php from the command line instead of wget. For example: cd /home/admin/domains/yourdomain.com/public_html/background/; /usr/local/bin/php -f run.php Code (markup):
i believe cron jobs use HTTP protocol to run the crons, so blocking access with htaccess would be stupid. honestly, a $_GET['password'] like i said above would be your best and easiest bet...
If you use PHP from the command line, the .htaccess is ignored. Ideally, using the command line approach with the file either in an .htaccess protected directory -or- outside of the web root would be best. Passing a password via the $_GET could potentially be made visible, particularly if any of your web statistics (WebStats can expose this) are not secured. Another option is to create a file that contains a time stamp and use that as a reference as to when the last time the run.php file was last executed. If it is less than X period of time, do nothing and exit. This would avoid abuse by someone attempting to execute it manually.