How can PHP be used to restrict access to files and prevent direct URL access in a web application?

To restrict access to files and prevent direct URL access in a web application, you can use PHP to check if the request is coming from a valid source (such as a form submission or a specific session) before allowing access to the file. This can help prevent unauthorized users from accessing sensitive files directly through the URL.

<?php
// Check if the request is coming from a valid source
if(isset($_POST['submit'])) {
    // Allow access to the file
    $file = 'example.txt';
    header('Content-Type: text/plain');
    readfile($file);
} else {
    // Redirect or display an error message
    echo 'Access denied';
}
?>