too long

I set up a cron script that runs every minute in the CPanel of my webhost. The cron runs properly, but I am encountering a script path related issue that I have no idea how to resolve properly. Most of my website uses /home/mysite/public_html/ as the root path, but the cron script uses /home/mysite/ as root path without the public_html part.

This causes a lot of issue with file inclusion, as I am forced to fix this in my class loaders by checking both the default path, and an alternative path prefixed by public_html/:

spl_autoload_register(function($class){
    $className = str_replace("\\", "/", $class);
    $classPath = "{$className}.php";
    $altClassPath = "public_html/{$classPath}";
    if(file_exists($classPath)) require $classPath;
    elseif(file_exists($altClassPath)) require $altClassPath;
    else throw new ClassNotFoundException("Fatal Error: Class {$class} either does not exist, or has its include path mis-configured!");
});

This feels tedious and error prone, and I do not like it at all. Is there a better way to handle this problem? I tried to use set_include_path on the cron script but it seems it doesnt help with the autoloader either.

Had the same problem just a minute ago. It seems a simple one, but those are often the hardest ones to get because everybody knows that, so nobody say it aloud.

In my case using so called magic constant of PHP solved it. The variable is:

__DIR__

And it holds a path to the script it is used in. No matter if run directly or included in some other php file. So you can use it to write relative paths, that always start where your file is. Like that one:

 include(__DIR__ . "/../somewhere/something.php");

Some more useful magic constants