file_get_contents - failed to open stream
-
16-10-2019 - |
Question
I have this code on my functions.php for getting shorturl over bit.ly
function bitly() {
global $post;
$bitly = file_get_contents('http://api.bit.ly/v3/shorten?login=USER&apiKey=KEY&longUrl='.urlencode(get_permalink($post->ID)).'&format=txt');
echo $bitly;
}
but, sometimes i got error like this "Function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in functions.php on line 614"
Line 614 is code from above. What i want is to handle that error and not show it for users. But instead of showing bit.ly short url, if error 404 is there, i want to show default wp.me url for users or if not possible wp.me then whole url.
EDIT I fixed this with this code
function bitly() {
global $post;
$bitly = wp_remote_retrieve_body (wp_remote_get('http://api.bit.ly/v3/shorten?login=USERNAME&apiKey=APIKEY&longUrl='.urlencode(get_permalink($post->ID)).'&format=txt'));
if( is_wp_error( $bitly ) ) {
echo wp_get_shortlink($post->ID); }
else { echo $bitly; }
}
Solution
I agree that this is PHP rather than WP question.
To bring it closer to WP I do suggest to take a look at following functionality:
- HTTP API is highly suggested for making HTTP requests;
add_post_meta()
and related meta functions to store post-specific information;the_shortlink()
function, that is suggested template tag to use for natvie short link functionality (and hook into for third party).
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange