What potential issues can arise when setting a filename using CURLOPT_HEADERFUNCTION in PHP?

When setting a filename using CURLOPT_HEADERFUNCTION in PHP, a potential issue that can arise is that the filename may contain invalid characters or be too long, causing errors when trying to save the file. To solve this issue, you can sanitize the filename by removing any invalid characters and ensuring it is within a reasonable length limit before saving the file.

// Sanitize the filename by removing invalid characters and ensuring it is within a reasonable length limit
function sanitizeFilename($filename) {
    $filename = preg_replace("/[^\w\-_.]/", '', $filename); // Remove invalid characters
    $filename = substr($filename, 0, 255); // Limit filename length to 255 characters
    return $filename;
}

// Example of setting a filename using CURLOPT_HEADERFUNCTION with sanitized filename
$ch = curl_init();
$file = fopen('downloaded_file.txt', 'w+');

curl_setopt($ch, CURLOPT_URL, 'http://example.com/file-to-download.txt');
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) use ($file) {
    if (strpos($header, 'Content-Disposition: attachment') !== false) {
        preg_match('/filename="(.*?)"/', $header, $matches);
        $filename = sanitizeFilename($matches[1]);
        fwrite($file, $header);
    }
    return strlen($header);
});

curl_exec($ch);
curl_close($ch);
fclose($file);