What could be causing the HTTP Error 500 (Internal Server Error) when trying to delete directories and files dynamically using PHP on a web server?

The HTTP Error 500 (Internal Server Error) when trying to delete directories and files dynamically using PHP on a web server could be caused by incorrect file permissions or a syntax error in the PHP code. To solve this issue, you should check and ensure that the directories and files have the correct permissions set and that there are no syntax errors in the PHP code.

<?php
$directory = 'path/to/directory'; // Specify the directory path
if (is_dir($directory)) {
    $files = glob($directory . '/*'); // Get all files in the directory
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file); // Delete files
        }
    }
    rmdir($directory); // Delete directory
    echo 'Directory and files deleted successfully.';
} else {
    echo 'Directory does not exist.';
}
?>