curldownloadip2location

How to download IP2Location database with curl


I'm trying to download a database from IP2Location using the curl command they provide. I am registered so I have a valid token. The command they give is

    curl -o {LOCAL_FILE_NAME} "https://www.ip2location.com/download?token={DOWNLOAD_TOKEN}&file={DATABASE_CODE}"

Here's the code I am using, except for my token:

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_URL, "https://www.ip2location.com/download?token={mytoken}&file={DB1LITEBIN}");

    $dbfile = curl_exec($curl);

    if (curl_errno($curl)) {
     echo 'err '.curl_errno($curl);
    }                  

    curl_close($curl);

    $file = 'db_download.bin';  
    $mode = 'w';

     if (($fp = fopen($file , $mode))) {    
       $fout = fwrite($fp, $dbfile);
       fclose($fp);  
    }  

The script runs without error but the file that is downloaded is just the page not found page of their site. I get the same page not found if I use the url in a browser. Can someone please point out my mistake?


Solution

  • Please try the following. Note that you will be downloading a zip file containing the bin file.

    <?php
    
    //The resource that we want to download.
    $fileUrl = 'https://www.ip2location.com/download?token=XXXXXXXXXX&file=DB1LITEBIN';
    
    //The path & filename to save to.
    $saveTo = 'db_download.zip';
    
    //Open file handler.
    $fp = fopen($saveTo, 'w+');
    
    //If $fp is FALSE, something went wrong.
    if($fp === false){
        throw new Exception('Could not open: ' . $saveTo);
    }
    
    //Create a cURL handle.
    $ch = curl_init($fileUrl);
    
    //Pass our file handle to cURL.
    curl_setopt($ch, CURLOPT_FILE, $fp);
    
    //Timeout if the file doesn't download after 20 seconds.
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    
    //Execute the request.
    curl_exec($ch);
    
    //If there was an error, throw an Exception
    if(curl_errno($ch)){
        throw new Exception(curl_error($ch));
    }
    
    //Get the HTTP status code.
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    //Close the cURL handler.
    curl_close($ch);
    
    //Close the file handler.
    fclose($fp);
    
    if($statusCode == 200){
        echo 'Downloaded!';
    } else{
        echo "Status Code: " . $statusCode;
    }