What precautions should be taken when defining upload directories in PHP?

When defining upload directories in PHP, it is important to ensure that the directories are not publicly accessible to prevent unauthorized users from uploading potentially harmful files or accessing sensitive information. It is recommended to store uploaded files outside of the web root directory and restrict access using appropriate permissions.

// Define the upload directory outside of the web root
$uploadDir = '/path/to/upload/directory/';

// Check if the directory exists, if not create it
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Set appropriate permissions for the upload directory
chmod($uploadDir, 0777);