How can the use of server variables like DOCUMENT_ROOT and getcwd() be optimized to troubleshoot file download issues in PHP?

When troubleshooting file download issues in PHP, server variables like DOCUMENT_ROOT and getcwd() can be used to ensure that the correct file paths are being referenced. By using these variables, you can accurately determine the file paths and address any discrepancies that may be causing the download issues. This can help in resolving issues related to file not found errors or incorrect file paths.

// Use server variables to get the correct file path
$documentRoot = $_SERVER['DOCUMENT_ROOT'];
$currentDir = getcwd();

// Example usage of the file path
$filePath = $documentRoot . '/path/to/file.txt';

// Use the file path in your code to download the file
// For example, using header() function to force download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
readfile($filePath);