Background
Hi,
I am new to cron jobs and I am trying to set up a test one just to see how they work. I created it in cPanel like this:
wget -O - -q https://website.com/staging/wp-content/themes/AT103/test-cron.php
My file is pretty simple so far:
<?php
$email_to = "[email protected]";
$title = "Test title";
$body = "Test body";
mail($email_to, $title, $body);
?>
All works fine here, I recieve the email every interval that my cron job runs.
What I want
On my site people can put up ads/listings to sell their stuff. In the cron job I want to go through all listings and email the buyers and sellers for the ones that has expired. As a first step in this I need to access the variables on my website, e.g. a listing object which is put in a variable like $post. Or through a function which returns the stuff I want if easier.
What I tried
I tried to access a random file and its functions by using lots of different code examples found online. The file is in the same folder as my test-cron.php. Here are a few things I tried to put at the top of test-cron.php (one at a time, not all at once):
require '/functions.php';
require 'https://website.com/staging/wp-content/themes/AT103/functions.php';
require '/home3/username/public_html/staging/wp-content/themes/AT103/functions.php';
This all resulted in the same thing, I did not get an email anymore. So I assume there is some sort of error with the lines? I also tried with require_once() with the same result.
Questions
- How do I access other scripts ("live" variables or functions) in my folder hierarchy through a cron job?
- If it is not possible for some reason, can I instead access my database information somehow?
CodePudding user response:
If the file to be required/included, is in the same folder as the running script you would use one of the following:
require 'functions.php';
no leading slash tells it to look in the include path, then in the current directory.require './functions.php';
(better) the./
explicitly says look in the current directory.
https://www.php.net/manual/en/ini.core.php#ini.include-path
EDIT: I just realized I did not address the fact that you are using cron and that's because ...
You are sill running PHP, cronjob or not makes no difference it still works the same!
However, it can be more difficult to debug on a production server. If you want to see exactly what's happening when the script fails then you can wrap it in a try
block, catch
and send the error to your email, or output the error and view it in the browser.
I know on Bluehost shared-hosting, if any of my cronjobs produce any output it will be automatically sent to me via email. I use the format below, and always get an email telling me when & why it happened. While developing you can simply navigate to your test-cron.php
in the browser.
<?php
try {
require './functions.php';
/*
all of your logic
*/
} catch (Error $e) {
echo "Caught Error: \n" . $e;
}