How does the use of dirname() and $_SERVER['SCRIPT_NAME'] help in determining the correct file path for included resources in PHP templates?

When including resources in PHP templates, it's important to determine the correct file path to ensure that the resources are loaded properly. Using dirname() function along with $_SERVER['SCRIPT_NAME'] can help in dynamically generating the correct file path for included resources. dirname() function returns the directory name of a path, and $_SERVER['SCRIPT_NAME'] provides the current script's path. By combining these two, we can determine the correct file path for included resources regardless of the file structure.

<?php
// Get the current directory path
$currentDir = dirname($_SERVER['SCRIPT_NAME']);

// Include a CSS file using the correct path
echo '<link rel="stylesheet" href="' . $currentDir . '/css/styles.css">';

// Include a JavaScript file using the correct path
echo '<script src="' . $currentDir . '/js/script.js"></script>';
?>