Skip to content
PHP Logo

How can the PHP code be modified to avoid using absolute file paths in the HTML pages and includes?

When using absolute file paths in HTML pages and includes, the code becomes less portable and can break when moved to a different server or directory structure. To avoid this issue, you can use PHP's predefined constants like `__DIR__` or `$_SERVER['DOCUMENT_ROOT']` to dynamically generate file paths based on the current file location. This way, the code will be more flexible and easier to maintain.

php
<?php
// Define root path
define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);

// Include a file using the dynamically generated path
include(ROOT_PATH . '/includes/header.php');
?>