Search code examples
phpyoutubedownloadyoutube-dlresume-download

Is it possible to download YouTube video links through PHP with resumable?


Is it possible to download youtube video links through php with resumable. I can easily fetch the download links through youtube-dl.

In PHP resumable, it needs to be known the size of the video. But from the link i can't fetch out the size, so is it possible to make resumable through PHP.

Let say the link is: [mp4]

https://r10---sn-hp576n7z.googlevideo.com/videoplayback?mt=1415174349&itag=22&fexp=915516%2C930666%2C932404%2C934601%2C947209%2C947215%2C948124%2C952302%2C952901%2C953912%2C957103%2C957201&key=yt5&upn=xe1em66NCSc&sparams=gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmime%2Cmm%2Cms%2Cmv%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&ipbits=0&ratebypass=yes&gcr=us&mv=u&id=o-ANmao-OacohTVjp7yijSePI5a3vvlERcSs6uL3WLfOA7&ms=au&expire=1415196179&sver=3&ip=176.576.184.114&mime=video%2Fmp4&requiressl=yes&source=youtube&mm=31&signature=29046D03C1EC013A78BD20E4CDD362BBA62ADF4B.A0E2E8E104769DD664202597A91F0888F9E554B3

Solution

  • Try this to get filesize:

    <?php
     /**
     * Returns the size of a file without downloading it, or -1 if the file
     * size could not be determined.
     *
     * @param $url - The location of the remote file to download. Cannot
     * be null or empty.
     *
     * @return The size of the file referenced by $url, or -1 if the size
     * could not be determined.
     */
    function curl_get_file_size( $url ) {
        // Assume failure.
        $result = -1;
    
        $curl = curl_init( $url );
    
        // Issue a HEAD request and follow any redirects.
        curl_setopt( $curl, CURLOPT_NOBODY, true );
        curl_setopt( $curl, CURLOPT_HEADER, true );
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt( $curl, CURLOPT_USERAGENT, 'user_agent_string' );
    
        $data = curl_exec( $curl );
        curl_close( $curl );
    
        if( $data ) {
            $content_length = "unknown";
            $status = "unknown";
    
            if( preg_match( "/^HTTP\/1\.[01] (\d\d\d)/", $data, $matches ) ) {
                $status = (int)$matches[1];
            }
    
            if( preg_match( "/Content-Length: (\d+)/", $data, $matches ) ) {
                $content_length = (int)$matches[1];
            }
    
            // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
            if( $status == 200 || ($status > 300 && $status <= 308) ) {
                $result = $content_length;
            }
        }
    
        return $result;
    }
    

    Usage:

    $file_size = curl_get_file_size($url);