简体   繁体   中英

How to check the extension of our file before uploading it to our server with cURL?

I am using cURL features to take a file and upload it to my server. Now I want to check the file extension before uploading it.

Here is my problem:

Suppose we have a URL that does not display the file extension in the URL like this one: https://images.unsplash.com/photo-1533450718592-29d45635f0a9?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80

This link sends an image, but in my case, I want to get the extension of this image without uploading it so that I can compare it to the file extensions that are accepted.

Here is the code that I had used to upload the file in my site:

$url = 'https://images.unsplash.com/photo-1533450718592-29d45635f0a9?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80';

function collect_file($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($ch, CURLOPT_REFERER, "https://file-examples.com");
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec($ch);

    curl_close($ch);
    return($result);
}

function write_to_file($text,$new_filename){
    $fp = fopen($new_filename, 'w');
    fwrite($fp, $text);
    fclose($fp);
}


// start loop here

$new_file_name = uniqid() . '.jpeg';

$temp_file_contents = collect_file($url);
write_to_file($temp_file_contents,$new_file_name); 

Now I would like to know how can I improve this code to compare the extension to other file extensions that are accepted in my system? I found this piece of code here .

THANKS FOR YOUR HELP.

Edit: Here are the extensions that are accepted: "jpeg", "docx", "xlsx", "xml", "txt", "pptx", "pdf", "md", "ods", "odp", "odt", "odg", "ots", "ott", "csv", "tsv", "rtf", "resx", "html", "srt", "vtt", "stl", "sbv", "sub", "ass", "dfxp", "ttml".

I want to check the data formats of these files. HELP ME PLEASE

I don't think there's a general solution for arbitrary files, but for image files you can use getimagesize() . One of the values it returns is one of the IMAGETYPE_xxx constants, and it also returns the corresponding MIME type. These correspond to extensions, so you can check these.

write_to_file($temp_file_contents,$new_file_name); 
$typedata = getimagesize($new_file_name);
$allowed_types = [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_BMP];
if ($typedata) {
    $type = $typedata[2];
    if (in_array($type, $allowed_types)) {
        // code to upload the file
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM