How can cURL or fsockopen() be utilized in PHP to have more control over requests and potentially resolve issues with file retrieval?

When using functions like file_get_contents() to retrieve files in PHP, there may be limitations or issues with handling certain types of requests or responses. To have more control over requests and potentially resolve these issues, cURL or fsockopen() can be utilized. These functions provide more flexibility and options for making HTTP requests, handling responses, and troubleshooting connectivity problems.

// Using cURL to retrieve a file with more control
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

// Using fsockopen() to retrieve a file with more control
$fp = fsockopen('example.com', 80, $errno, $errstr, 30);
if (!$fp) {
    echo "Error: $errstr ($errno)\n";
} else {
    $out = "GET /file.txt HTTP/1.1\r\n";
    $out .= "Host: example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 128);
    }
    fclose($fp);
}