Student Student - 2 months ago 6
MySQL Question

No results from cronjob using crontab at localhost

I am trying to update a mysql table every 1 minute under linux localhost using cronjob with no success. I am using wordpress to make the connection with the database. What I have done so far:

In terminal I opened crontab using:

crontab -e


and typed:

*/1 * * * * /usr/bin/php /var/www/.../myscript.php


I saved the changes and checked the file in /var/spool/cron/crontabs.

Content of myscript.php:

<?php
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = $_SERVER['REQUEST_URI'];
$my_url = explode('wp-content' , $url);
$path = $_SERVER['DOCUMENT_ROOT']."/".$my_url[0];

include_once $path . '/wp-config.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

global $wpdb;

$wpdb->query("INSERT INTO mytable (id) VALUES ('1')");

?>


When I run myscript.php from browser, the table gets updated. What am I doing wrong?

Answer

You realise that you don't have webserver, and because of that the $_SERVER variable won't have SERVER_NAME and REQUEST_URI?

Because of that $path will never be filled in correctly, and your required files will not load.

Normally you would see some notices (if that's not the case, your php.ini is not well configured), but the code should still run. Only will $path just hold '/', and thus load everything from the root of your server.
The files are not there, so it's not working.

If you need to determe your path that way (while browing), you will need to determine if you're browsing, or are running it in CLI.
For example with this:

if (php_sapi_name() === 'cli') {
    $path = 'PATH THAT YOU KNOW, probably /var/www';
} else {
    $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    $url = $_SERVER['REQUEST_URI'];
    $my_url = explode('wp-content' , $url);
    $path = $_SERVER['DOCUMENT_ROOT']."/".$my_url[0];
}