How can global variables be utilized to solve issues related to setting filenames in PHP CURL functions?

When using PHP CURL functions, setting filenames dynamically can be challenging, especially when dealing with multiple requests. One way to solve this issue is by using global variables to store the filenames and access them when needed. By storing the filenames in global variables, you can easily set and retrieve them within different functions without the need to pass them as parameters.

<?php

// Global variable to store filename
$filename = '';

function downloadFile($url) {
    global $filename;
    
    // Set the filename dynamically
    $filename = 'downloaded_file_' . time() . '.txt';
    
    // CURL code to download the file and save it with the dynamic filename
}

function uploadFile($url, $file) {
    global $filename;
    
    // Set the filename dynamically
    $filename = 'uploaded_file_' . time() . '.txt';
    
    // CURL code to upload the file with the dynamic filename
}

// Example usage
downloadFile('http://example.com/file.txt');
echo "Downloaded file: $filename\n";

uploadFile('http://example.com/upload', 'local_file.txt');
echo "Uploaded file: $filename\n";

?>