0

I am using the following $_SERVER variables in my include file.

$page_url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ip_address = $_SERVER['REMOTE_ADDR'];

When I include this file to my PHP script located in the home directory for my Cron jobs, it's throwing errors Undefined array key "HTTP_HOST", Undefined array key "REQUEST_URI", Undefined array key "REMOTE_ADDR" to the error_log file.

To avoid this, I want to make this code to show only if the file is in the public_html directories. How do I say it with PHP if statement?

Thanks!

  • 1
    Does this answer your question? [PHP - how to best determine if the current invocation is from CLI or web server?](https://stackoverflow.com/questions/933367/php-how-to-best-determine-if-the-current-invocation-is-from-cli-or-web-server) – bassxzero Nov 10 '21 at 05:36
  • 1
    You can check current directory with `getcwd()`. See more https://www.w3schools.com/php/func_directory_getcwd.asp – iazaran Nov 10 '21 at 05:39
  • `To avoid this, I want to make this code to show only if the file is in the public_html directories` - that’s an odd direction, it’s not directly related to the problem you’re trying to solve. You could use `empty($_SERVER['HTTP_HOST'])` as a naive but functional test; but checking the sapi name is the normal way to do it. – AD7six Nov 10 '21 at 07:25
  • As of now it's working fine for me, and get no errors or issues. I will definitely try the complicated way if I face any issues in the future. Thanks for your suggestion! –  Nov 10 '21 at 07:39
  • `the complicated way` ? – AD7six Nov 10 '21 at 10:23
  • As a naive that must be a complicated way for me! –  Nov 10 '21 at 15:16

2 Answers2

0
/**
 * Check if file is in public directory. This will not work if running via CLI.
 *
 * @param bool $checkCallerScript Set to `true` to check for caller script using trace.
 * @return bool Return `true` if it is in public directory, return `false` for otherwise.
 */
function isInPublicDir(bool $checkCallerScript = true): bool
{
    if (!isset($_SERVER['HTTP_HOST']) || !isset($_SERVER['REMOTE_ADDR'])) {
        // if no HTTP or ip address from user.
        return false;
    }

    if (!isset($_SERVER['DOCUMENT_ROOT']) || empty($_SERVER['DOCUMENT_ROOT'])) {
        // if no document root. run from CLI don't have this value.
        // see https://www.php.net/manual/en/reserved.variables.server.php for more details.
        return false;
    }
    $docRoot = str_replace(['\\', '/', DIRECTORY_SEPARATOR], DIRECTORY_SEPARATOR, $_SERVER['DOCUMENT_ROOT']);

    if (true === $checkCallerScript) {
        $traces = debug_backtrace();
        if (is_array($traces)) {
            foreach ($traces as $trace) {
                $callerFile = str_replace(['\\', '/', DIRECTORY_SEPARATOR], DIRECTORY_SEPARATOR, ($trace['file'] ?? null));
                if (!isset($callerFile) || stripos($callerFile, $docRoot) === false) {
                    return false;
                }
            }
            unset($callerFile, $trace);
        }
        unset($traces);
    }
    unset($docRoot);

    return true;
}

The function above will not work if running via CLI or something that don't have DOCUMENT_ROOT value. Read more about $_SERVER

If I have files like this...

/var/www/public_html/run.php
/var/www/test.php
/var/www/functions.php <- the function above is in this file.

And public directory is /var/www/public_html

require dirname(__DIR__) . '/functions.php';



var_dump(isInPublicDir());// expect true
var_dump(isInPublicDir(false));// expect true


require dirname(__DIR__) . '/test.php';

run.php contents.

.

<?php



echo 'hello from ' . __FILE__ . '<br>' . PHP_EOL;

var_dump(isInPublicDir());// expect **false**
var_dump(isInPublicDir(false));// expect true

test.php contents.

vee
  • 4,506
  • 5
  • 44
  • 81
  • Oh, man.., I really appreciate your effort :) But this `if (strpos(getcwd(), 'public_html') !== false) { $myVariables; }` would be sufficient for my case. I am giving an upvote for your answer. Thanks a lot mate..! –  Nov 10 '21 at 07:00
0

Based on iazaran's response, this code is working for me!

if (strpos(getcwd(), 'public_html') !== false) {
  $page_url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $ip_address = $_SERVER['REMOTE_ADDR'];
}

I thought it could be useful for someone like me.