Get Photos and Videos from Instagram in PHP

Posted on October 8, 2017 at 11:37 am

Example PHP function to get the image and video url from Instagram:

function get_instagram_image_url($url)
{
    $result = array();
 
	if(preg_match('/^https\:\/\/www\.instagram\.com\//is', $url))
    {
 
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
	$data = curl_exec($ch);
	curl_close($ch);
 
	if(preg_match('/property\=\"og\:image\"\s+content\=\"(.+?)\"/is', $data, $matches))
	{
		$imageurl = trim($matches[1]);
 
		if($imageurl)
		{			
			if(preg_match('/property\=\"og\:video\"\s+content\=\"(.+?)\"/is', $data, $matches))
			{
				$videourl = trim($matches[1]);
			}
 
			$result['imageurl'] = $imageurl ? $imageurl.'?dl=1' : '';
			$result['videourl'] = $videourl ? $videourl.'?dl=1' : '';
		}
		else
		{
			$result['error'] = 'Failed to parse image url';
		}
	}
 
	}
	else
	{
		$result['error'] = 'Instagram url is not valid';
	}
}

It gets also the video url if present.

Example usage:

$insta = get_instagram_image_url("https://www.instagram.com/p/BZ9X0J6nWTk/");
print_r($insta);

Other Posts

Updated Posts