curl snippet to get video

Last updated on
30 April 2025
name = "Youtube Downloader"
description = "Downloads youtube videos"
package = Custom
dependencies[] = video
core = "7.x"

<?php
function curlGet($URL) {
    $ch = curl_init();
    $timeout = 3;
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    /* if you want to force to ipv6, uncomment the following line */
    //curl_setopt( $ch , CURLOPT_IPRESOLVE , CURLOPT_IPRESOLVE_V6);
    $tmp = curl_exec($ch);
    curl_close($ch);
    return $tmp;
}

function get_file_data($url) {
    $res = array();
    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => "spider",
        CURLOPT_AUTOREFERER => true,
        CURLOPT_CONNECTTIMEOUT => 120,
        CURLOPT_TIMEOUT => 2400,
        CURLOPT_MAXREDIRS => 10,
    );
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);

    $res['content'] = $content;
    $res['url'] = $header['url'];
    return $res;
}

/**
 * Implements hook_node_insert().
 */
function youtube_downloader_node_insert($node) {
    global $base_path;
//    echo $base_path;
//    die;
    if ($node->type == 'video') {

        if (isset($node->field_video_url['und'][0]['value'])) {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . base_path() . 'sites/default/files/videos/';

            $video_url = $node->field_video_url['und'][0]['value'];
            $video_id = substr(strstr($video_url, "v=", false), 2);
            $new_video_url = 'http://www.youtube.com/get_video_info?&video_id=' . $video_id;
            $new_video_url = curlGet($new_video_url);

            parse_str($new_video_url);

            if (isset($url_encoded_fmt_stream_map)) {
                // Now get the url_encoded_fmt_stream_map, and explode on comma 
                $my_formats_array = explode(',', $url_encoded_fmt_stream_map);
                if (count($my_formats_array) == 0) {
                    drupal_set_message(t('No format stream map found - was the video id correct?'), 'error');
                } else {
                    // create an array of available download formats
                    $avail_formats[] = '';

                    foreach ($my_formats_array as $format) {
                        parse_str($format);
                        $type = explode(';', $type);
                        if ($type[0] == 'video/webm') {
                            $file_url = urldecode($url) . '&signature=' . $sig;
                            $ext = str_replace(array('/', 'x-'), '', strstr($type[0], '/'));
			    $mime = $type[0];
			    break;
                        }
			/*else if ($type[0] == 'video/mp4') {
                            $file_url = urldecode($url) . '&signature=' . $sig;
                            $ext = str_replace(array('/', 'x-'), '', strstr($type[0], '/'));
			    $mime = $type[0];
			    break;
                        }*/
			else if ($type[0] == 'video/x-flv') {
                            $file_url = urldecode($url) . '&signature=' . $sig;
                            $ext = str_replace(array('/', 'x-'), '', strstr($type[0], '/'));
			    $mime = $type[0];
			    break;
                        }
                    }
                    $filtered_url = filter_var($file_url);

                    $video_path = $file_path . 'original/';

                    $name = urldecode($title) . '.' . $ext;
		    $name = str_replace(array(':','/','\\','*','?','"','<','>','|'),'',$name);
                    $data = get_file_data($filtered_url);
                    
                    file_put_contents($video_path . $name, $data['content']);

                    $fid = db_insert('file_managed') // Table name no longer needs {}
                            ->fields(array(
                                'uid' => $node->uid,
                                'filename' => $name,
                                'uri' => 'public://videos/original/' . $name,
                                'filemime' => $mime,
                                'filesize' => filesize($video_path . $name),
                                'status' => 1,
                                'timestamp' => REQUEST_TIME,
                            ))
                            ->execute();

                    //$file = file_save_upload($video_path . $name);
                    //print_r($file);
                    //die;

                    $thumb_name = 'thumbnail-' . $fid . '_0001.jpg';
                    mkdir($file_path . "thumbnails/" . $fid, 0755);
                    $data = get_file_data($thumbnail_url);
                    $img = imagecreatefromstring($data['content']);
                    
                    imagejpeg($img, $file_path . "thumbnails/" . $fid . '/' . $thumb_name);

                    $tid = db_insert('file_managed')
                            ->fields(array(
                                'uid' => $node->uid,
                                'filename' => $thumb_name,
                                'uri' => 'public://videos/thumbnails/' . $fid . '/' . $thumb_name,
                                'filemime' => 'image/jpeg',
                                'filesize' => filesize($file_path . "thumbnails/" . $fid . '/' . $thumb_name),
                                'status' => 1,
                                'timestamp' => REQUEST_TIME,
                            ))
                            ->execute();

                    $nid = db_insert('field_data_field_video')
                            ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'video',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->vid,
                                'language' => $node->language,
                                'delta' => 0,
                                'field_video_fid' => $fid,
                                'field_video_thumbnail' => $tid,
                            ))
                            ->execute();

                    $nid = db_insert('field_revision_field_video')
                            ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'video',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->vid,
                                'language' => $node->language,
                                'delta' => 0,
                                'field_video_fid' => $fid,
                                'field_video_thumbnail' => $tid,
                            ))
                            ->execute();

                    $nid = db_insert('video_thumbnails')
                            ->fields(array(
                                'videofid' => $fid,
                                'thumbnailfid' => $tid,
                            ))
                            ->execute();

                    $nid = db_insert('file_usage')
                            ->fields(array(
                                'fid' => $fid,
                                'module' => 'file',
                                'type' => 'node',
                                'id' => $node->nid,
                                'count' => 1,
                            ))
                            ->execute();
                    
                    db_delete('field_data_field_video_url')
                            ->condition('entity_id', $node->nid)
                            ->execute();
                    
                    db_delete('field_revision_field_video_url')
                            ->condition('entity_id', $node->nid)
                            ->execute();
                }
            } else {
                drupal_set_message(t('No encoded format stream found.'), 'error');
            }
        }
    }
}

/**
 * Implements hook_node_update().
 */
function youtube_downloader_node_update($node) {
    if ($node->type == 'video') {
//        print "<pre>";
//        print_r($node);
//        die;

        if (isset($node->field_video_url['und'][0]['value'])) {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . base_path() . 'sites/default/files/videos/';

            $video_url = $node->field_video_url['und'][0]['value'];
            $video_id = substr(strstr($video_url, "v=", false), 2);
            $new_video_url = 'http://www.youtube.com/get_video_info?&video_id=' . $video_id;
            $new_video_url = curlGet($new_video_url);

            parse_str($new_video_url);

            if (isset($url_encoded_fmt_stream_map)) {
                // Now get the url_encoded_fmt_stream_map, and explode on comma 
                $my_formats_array = explode(',', $url_encoded_fmt_stream_map);
                if (count($my_formats_array) == 0) {
                    drupal_set_message(t('No format stream map found - was the video id correct?'), 'error');
                } else {
                    // create an array of available download formats
                    $avail_formats[] = '';

                    foreach ($my_formats_array as $format) {
                        parse_str($format);
                        $type = explode(';', $type);
                        if ($type[0] == 'video/webm') {
                            $file_url = urldecode($url) . '&signature=' . $sig;
                            $ext = str_replace(array('/', 'x-'), '', strstr($type[0], '/'));
			    $mime = $type[0];
			    break;
                        }
			/*else if ($type[0] == 'video/mp4') {
                            $file_url = urldecode($url) . '&signature=' . $sig;
                            $ext = str_replace(array('/', 'x-'), '', strstr($type[0], '/'));
			    $mime = $type[0];
			    break;
                        }*/
			else if ($type[0] == 'video/x-flv') {
                            $file_url = urldecode($url) . '&signature=' . $sig;
                            $ext = str_replace(array('/', 'x-'), '', strstr($type[0], '/'));
			    $mime = $type[0];
			    break;
                        }
                    }
                    $filtered_url = filter_var($file_url);

                    $video_path = $file_path . 'original/';

                    $name = urldecode($title) . '.' . $ext;
		    $name = str_replace(array(':','/','\\','*','?','"','<','>','|'),'',$name);
                    $data = get_file_data($filtered_url);
                    
                    db_delete('video_thumbnails')
                            ->condition('videofid', $node->field_video['und'][0]['fid'])
                            ->execute();
                    
                    db_delete('file_usage')
                            ->condition('fid', $node->field_video['und'][0]['fid'])
                            ->execute();
                    
                    db_delete('field_data_field_video')
                            ->condition('entity_id', $node->nid)
                            ->execute();
                    
                    db_delete('field_revision_field_video')
                            ->condition('entity_id', $node->nid)
                            ->execute();
                    
                    file_put_contents($video_path . $name, $data['content']);

                    $fid = db_insert('file_managed') // Table name no longer needs {}
                            ->fields(array(
                                'uid' => $node->uid,
                                'filename' => $name,
                                'uri' => 'public://videos/original/' . $name,
                                'filemime' => $mime,
                                'filesize' => filesize($video_path . $name),
                                'status' => 1,
                                'timestamp' => REQUEST_TIME,
                            ))
                            ->execute();

                    
                    $thumb_name = 'thumbnail-' . $fid . '_0001.jpg';
                    mkdir($file_path . "thumbnails/" . $fid, 0755);
                    $data = get_file_data($thumbnail_url);
                    $img = imagecreatefromstring($data['content']);

                    imagejpeg($img, $file_path . "thumbnails/" . $fid . '/' . $thumb_name);
                    
                    $tid = db_insert('file_managed')
                            ->fields(array(
                                'uid' => $node->uid,
                                'filename' => $thumb_name,
                                'uri' => 'public://videos/thumbnails/' . $fid . '/' . $thumb_name,
                                'filemime' => 'image/jpeg',
                                'filesize' => filesize($file_path . "thumbnails/" . $fid . '/' . $thumb_name),
                                'status' => 1,
                                'timestamp' => REQUEST_TIME,
                            ))
                            ->execute();


                    $nid = db_insert('field_data_field_video')
                            ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'video',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->vid,
                                'language' => $node->language,
                                'delta' => 0,
                                'field_video_fid' => $fid,
                                'field_video_thumbnail' => $tid,
                            ))
                            ->execute();

                    $nid = db_insert('field_revision_field_video')
                            ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'video',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->vid,
                                'language' => $node->language,
                                'delta' => 0,
                                'field_video_fid' => $fid,
                                'field_video_thumbnail' => $tid,
                            ))
                            ->execute();

                    $nid = db_insert('video_thumbnails')
                            ->fields(array(
                                'videofid' => $fid,
                                'thumbnailfid' => $tid,
                            ))
                            ->execute();

                    $nid = db_insert('file_usage')
                            ->fields(array(
                                'fid' => $fid,
                                'module' => 'file',
                                'type' => 'node',
                                'id' => $node->nid,
                                'count' => 1,
                            ))
                            ->execute();
                    
                    db_delete('field_data_field_video_url')
                            ->condition('entity_id', $node->nid)
                            ->execute();
                    
                    db_delete('field_revision_field_video_url')
                            ->condition('entity_id', $node->nid)
                            ->execute();
                }
            } else {
                drupal_set_message(t('No encoded format stream found.'), 'error');
            }
        }
    }
}

Help improve this page

Page status: Not set

You can: