I need someone to explain to me the following beginner PHP Code

OS: Centos
PHP: 7.3

I am following a course by Kevin Skoglund about PHP. These are a few lines from the code. I understand define() and dirname() function. I just don’t understand what is happening here.

 define("PRIVATE_PATH", dirname(__FILE__));
  define("PROJECT_PATH", dirname(PRIVATE_PATH));
  define("PUBLIC_PATH", PROJECT_PATH . '/public');
  define("SHARED_PATH", PRIVATE_PATH . '/shared');

here is another section of code.

$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 7;
  $doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
  define("WWW_ROOT", $doc_root);

It’s just making constants of the paths so you don’t have remember them when you need to use them. Especially helpful when working on a local server. It is also a good way to make your PHP a little more secure. I like Kevin Skoglund and have followed a couple of his tutorials.

The second section is just define the root path of you website/app.

I personally find this easier to do ->

define("APP_ROOT", dirname(dirname(__FILE__)));
define("PRIVATE_PATH", APP_ROOT . "/private");
define("PUBLIC_PATH", APP_ROOT . "/public");

and stick it in an initial file, BUT the tutorial you are doing there must be a reason to do it that way. Though without seeing the whole code it is kind of hard to tell, but I would guess that the WWW_ROOT constant is easier to access in other sections of the PHP code, plus it might make the code a little more secure? Though someone else here might be able to tell right off the bat the real reason it is like that.

1 Like

Instead of dirname(FILE) you can just use __DIR__

Sponsor our Newsletter | Privacy Policy | Terms of Service