What are the potential security risks of including an external upload script in PHP?

Including an external upload script in PHP can pose security risks such as allowing malicious files to be uploaded to the server, leading to potential security vulnerabilities such as code execution, file inclusion, or denial of service attacks. To mitigate these risks, it is important to thoroughly validate and sanitize user input, restrict file types and sizes, and implement proper file permissions on the server.

// Example of a secure file upload script in PHP

// Check if a file was uploaded
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Validate file type and size
    $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
    $max_size = 5 * 1024 * 1024; // 5MB

    $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    if(!in_array($file_ext, $allowed_types) || $file['size'] > $max_size) {
        die('Invalid file type or size.');
    }

    // Move the uploaded file to a secure directory
    $upload_dir = 'uploads/';
    $upload_file = $upload_dir . basename($file['name']);
    move_uploaded_file($file['tmp_name'], $upload_file);

    echo 'File uploaded successfully.';
}