Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

nicholas maddren
nicholas maddren
12,793 Points

How can I hide a PHP script and cron it?

My script is currently in my public_html, the issue I am having is anyone can visit the file and the script will execute. I want it to run in the background with a cron job setup so it runs every day. The reason I want the file to be non accessible by the public is because it will have a performance effect on my server if someone were to spam it.

Any ideas?

2 Answers

Michael Collins
Michael Collins
433 Points

When you set up a cron job, you specific the path of the script from the root of the server (not the document root of the web server). So, you can create a folder any where on the server and then tell cron where the php script is.

nicholas maddren
nicholas maddren
12,793 Points

I am aware how I can set up a cron job I just don't know how I can make that script non accessible to traffic.

Michael Collins
Michael Collins
433 Points

Are you able to upload the script to some place besides public_html

Do you FTP into the server? So maybe you have a folder/file structure like this ....

username
  - public_html
    -- myscript.php

Instead of that, you want to do this ...

username
  -public_html
  - myscript (no longer inside public_html)
Michael Collins
Michael Collins
433 Points

Cron also runs as a user. So, if you are user BillyBob, and you do a: crontab -l You'll get a listing of cron jobs for BillyBob. When cron runs those commands, cron is running them as BillyBob.

Likewise, if you are root and you do a crontab -l, you get cron jobs listed for root.

You can create a script that is owned by user -> BillyBob / group -> BillyBob. Then chmod 700 the script. That way, only BillyBob can execute the script.

When you run the script through the web server, the web server knows where the PHP executable is. You don't have to tell it. But when you run a PHP script through the shell, you have to tell it where it is. You do that with a #!, like this

#!/usr/bin/php
<?php

// your code goes here.

?>

That's assuming your PHP executable is in /usr/bin/php

Mike Costa
PLUS
Mike Costa
Courses Plus Student 26,362 Points

If you want it in the public folder, you could write a conditional statement to prevent it from running on the web.

<?php

if (PHP_SAPI !== 'cli') {
die();
}