SlideShare API without url_file_open

Recently while writing some code that utilised the SlideShare API I found myself on a server which had url_file_open turned off in the php.ini and this couldn’t be over-ridden with a .htaccess file either. So I had to re-write the code which used file_get_contents using the cURL library.

I needed to replace the get_data function within the SSUtil.php file (part of the SlideShare PHP kit). Initially it looked like this:

private function get_data($call,$params) {
	$ts=time();
	$hash=sha1($this->secret.$ts);
	try {
		$res=file_get_contents($this->apiurl.$call."?api_key=$this->key&ts=$ts&hash=$hash".$params);
	} catch (Exception $e) {
	// Log the exception and return $res as blank
	}
	return utf8_encode($res);
}

Following some time spent with google and a bit or trial-and-error I came up with this which seems to work in its place:

private function get_data($call,$params) {
	$timeout=0;
	$ts=time();
	$hash=sha1($this->secret.$ts);
	# use CURL library to fetch remote file
	try {
		$ch = curl_init();
		$url = $this->apiurl.$call."?api_key=$this->key&ts=$ts&hash=$hash".$params;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$this->file_contents = curl_exec($ch);
		$res = $this->file_contents;	
	} catch (Exception $e) {
		// Log the exception and return $res as blank
	}
	return utf8_encode($res);
}

So, for any other unlucky souls who find themselves on a server which doesn’t support url_file_open then there you are.

Jamie Davies is an occasionally brilliant, 33-year-old assistant principal, teacher, author, data scientist and educationalist from Yorkshire.

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers: