What are the potential security risks of uploading files outside of the document root using PHP?

When uploading files outside of the document root using PHP, there is a risk of exposing sensitive information or allowing malicious files to be executed on the server. To mitigate this risk, it is important to validate the file paths and restrict access to only specific directories where file uploads are allowed.

// Example code snippet to restrict file uploads to a specific directory
$uploadDir = '/var/www/uploads/';
if (strpos(realpath($uploadDir), realpath('/var/www/')) === 0) {
    // File upload is within the allowed directory
    // Proceed with file upload logic
} else {
    // File upload is outside the allowed directory
    // Handle error or reject the file upload
}