How can I catch this PHP connection error?

Here's the Problem:

On some websites, my code that connects to Twitter is generating a fatal error that stops PHP from running for the rest of the page load. It creates a total page kill. How can I catch this error so that I can simply display zeroes or use one of the tweet counts from the most previous successful connections?

Presumably, this is because a site that has this code on it has hit the Twitter API limits. But in the rare cases where that does happen, I need it to fail gracefully so that I can just use my previously fetched tweet count.

Here's the code:

If the user has the Twitter Button active, we fetch the share count:

$social = new shareCount($url); if( $options['twitter'] ) $tweets = $social->get_tweets();

This is where that function request gets passed inside the shareCount class:

function get_tweets() { $json_string = file_get_contents_curl('https://urls.api.twitter.com/1/urls/count.json?url=' . $this->url); $json = json_decode($json_string, true); return isset($json['count'])?intval($json['count']):0; }

And this is the file_get_contents_curl() function which is, I believe where the error is occurring and is where we need to catch the error.

function file_get_contents_curl($url){ $ch=curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($ch, CURLOPT_FAILONERROR, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); $cont = curl_exec($ch); if(curl_error($ch)) { die(curl_error($ch)); } return $cont; }

This is the error that is being generated:

connect() timed out!

This is the requested solution:

So the question is, how do I catch that error and have the file_get_contents_curl() function either return a zero or return a specific code that I can look for indicating quietly to my script that it failed to connect?

-------------Problems Reply------------

There are two timeout settings for cURL:

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4); // Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 4); // Timeout in seconds

Set them both and cURL will fail gracefully on a timeout of either type.

However, slow DNS resolutions will trigger SIGALRM which cURL interprets as the timeout alarm. Add this to quiet that alarm, and any alarms that will halt the PHP execution:

curl_setopt($ch, CURLOPT_NOSIGNAL, 1);

You should continue to be checking for cURL errors and dealing with them, not suppressing them, like this:

$curl_errno = curl_errno($ch);
if ($curl_errno > 0) {
// Deal with error
}

In PHP you can use @ to suppress any errors that are thrown. These errors will not be shown and the script will continue to execute. Just put @ in front of any line that you think causes the error.

You can put it here where you are calling the function

function get_tweets() {
$json_string = @file_get_contents_curl('https://urls.api.twitter.com/1/urls/count.json?url=' . $this->url); // This will not throw any errors if file_get_contents_curl() fails.
$json = json_decode($json_string, true);
return isset($json['count'])?intval($json['count']):0;
}

Or you can put it in your function, at any line where you think the error is caused.

Category:php Views:3 Time:2018-04-12
Tags: php curl

Related post

  • How do I catch a PHP Fatal Error 2008-11-10

    I can use set_error_handler() to catch most PHP errors, but it doesn't work for fatal (E\_ERROR) errors, such as calling a function that doesn't exist. Is there another way to catch these errors? I am trying to call mail() for all errors and am runni

  • How can I improve this PHP code? 2009-08-17

    I have the php code below which help me get a photo's thumbnail image path in a script It will take a supplied value like this from a mysql DB '2/34/12/thepicture.jpg' It will then turn it into this '2/34/12/thepicture_thumb1.jpg' I am sure there is

  • How can I write this PHP code in JavaScript 2010-11-02

    How can I write this PHP code in JavaScript? I have no knowledge about JavaScript... :-s <?php $pozethumb=scandir("./pics/flori/thumbs"); $size=count($pozethumb); $nrpoze=$size-2; for($i=2;$i<$size;$i++) { echo"<img src=\"./pics/flori/thumbs

  • How can I catch this error? (POST Content-Length -) 2012-02-16

    While uploading image I'm getting this error: (max 8mb an image) Warning: POST Content-Length of 14259306 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 How can I display this message customly? I mean I want to put that error in CSS st

  • How can I fix this undefined index error? Jquery Ajax to PHP 2011-11-08

    I'm using Jquery, Ajax and PHP to try and send a variable to be written in a mysql database. The Ajax request is being made but the variable is not being picked up by the php. I don't know why this is the case. Using firebug and console.log() I can s

  • .net : How to correctly catch an internet connection error during web service call? 2010-02-15

    I am calling a 3rd party web service, during testing I am simulating what would happen if the web server lost internet connectivity by disabling the network adapter during a web service operation. I have a simple try/ catch scenario. The ex.message i

  • How can I solve a PHP syntax error that I receive when parsing html code? 2010-08-01

    Trying to print out some html forms but I get a parsing syntax error. I believe it gets stuck on the SERVER[PHP_SELF] but I'm not sure. How can I get this to echo correctly? Error occurs on the SERVER[PHP_SELF] line Parse error: syntax error, unexpec

  • How can I make this PHP else statement work? 2011-09-04

    <?php if (!empty($_GET['type'])) { echo str_replace(" ", "", strtolower(htmlspecialchars($_GET['type']))); } ?> I want this to return 'helloworld' when the type variable is 'Hello World' and this works perfectly. However, I'm trying to add an e

  • How can I fix this bizarre LoadError error produced by coffeescript/asset pipeline? 2012-04-30

    I'm using the Rails 3 asset pipeline. I got into a situation where I needed to order my Javascript files in a specific way so I added them all explicitly to application.js like this: //= require admin //= require application //= require users ... //=

  • How can I implement this PHP code in Java Servlet 2014-10-15

    I am trying to upload images via a drag and drop interface, I got the JavaScript code here but the server side code is implemented in PHP as shown below (I modified it to insert the image to database): <?php //Connect to database mysql_connect("lo

  • How can i secure this PHP script? 2011-04-15

    Can anyone offer any suggestions on how to secure this PHP script from sql injection: <?php include("config.php"); if(isset($_POST['lastmsg'])) { $lastmsg = mysqli_real_escape_string($_GET['lastmsg']); $result=mysql_query("select * from messages w

  • How can I combine this php statement to get the results of multiple variable inputs? 2011-04-30

    This is my WordPress query but is not a wordpress related question. It shows the posts that have meta_key as extra1 and meta_value as test <?php $customkey1 = extra1; ?> <?php $customvalue1 = test; ?> <?php query_posts('meta_key=' . $c

  • How can I duplicate this PHP code in Ruby? 2011-10-14

    I'm moving some projects to Rails and I would like to duplicate this PHP code: http://www.php.net/manual/en/functions.anonymous.php#106046 so far I have this: def html (tag, id = "", hclass = "") hopen = "<#{tag}" hclose = "</#{tag}>" unless

  • How can I save this php created image? 2011-10-25

    What are some possible ways to save an image or make use of it that is generated from a PHP script. Using save as it does not help though. This is not an image created by me that's why I want to avoid get_contents. here is the picture and here is the

  • Recently a new connection has shown up on my Verizon connect window and is interfering with my connection, How can I delelte this other connection? 2012-08-11

    Recently a "VillageGreenPreservationSociety" connection show up on my Verizon connect window. How can i delete it. It is interfering with my WIFI connection thru Verizon. --------------Solutions------------- Hi, It could be a network that is being us

  • How can i solve this java lang error? 2014-12-23

    I am trying to solve this java lang error: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sebasdeldihotmail.mediocre11/com.sebasdeldihotmail.mediocre11.SignUpOrLogInActivity}: java.lang.ClassCastException: com.sebasdeldi

  • How can I catch for a connection timeout error in Python's SMTPlib? 2010-03-28

    The error being thrown is: error: [Errno 110] Connection timed out I'm not sure what to except for? try: smtpObj = smtplib.SMTP('smtp.example.com') smtpObj.starttls() smtpObj.login('user','pass') smtpObj.sendmail(sender, receivers, message) print "Su

  • How can I fix this PHP XML parsing error? 2009-05-30

    This is my first question :). Im writing a little twitter app in PHP that sends a DMs to all your followers. What im trying to do right now is to get the list of followers. So through twitter api and getting all usernames but for some reason this par

  • How can I make this php database class more secure? 2011-06-02

    I'm using the following PHP MySQL database class. I'm curious as to what I could do to make it more secure. I'm happy with it so far, but without suggesting to "use PDO" what can I do to improve this currently? <? class DbConnector { public static

  • How can I make this PHP program faster? 2011-07-18

    I built a program to loop through words and get their synonyms from www.dicsin.com.br, but this will take ages (literally), because there are 307k words on my testfile.txt, what can I do ? give me advises please, can I make it multi-process or multi-

  • How can I fix this JavaScript syntax error? 2009-07-07

    This is puzzling me. I'm using Google Map's Geocoding to find locations. I am attempting to use the example here, which is from Google, and it is just not working for me. Error: http://maps.gstatic.com/intl/en_us/mapfiles/159e/maps2.api/main.js Line

  • How can I improve this PHP pagination algorithm? 2010-09-19

    I'm working on a pagination algorithm in PHP. I can guess that it needs room for improvement, so I'd like some thoughts on how to improve it, be it cleaning up the code itself, from a UI/UX standpoint, or anything else you can think of. The algorithm

  • How can I improve this PHP/MySQL news feed? 2010-11-12

    Let me start right off the bat by saying that I know this is not the best solution. I know it's kludgy and a hack of a feature. But that's why I'm here! This question/work builds off some discussion on Quora with Andrew Bosworth, creator of Facebook'

  • How can I put all PHP Oracle error functions in one function? 2011-04-16

    i try to build one function hold all errors here is my example: <?php $stid = oci_parse($conn, "select does_not_exist from dual"); $r = oci_execute($stid); if (!$r) { $e = oci_error($stid); // For oci_execute errors pass the statement handle print

  • How can i solve this Crystal reports error? 2011-10-21

    I have just completed developing my web application. I was trying to deploy it to test it. When i was doing that It first gave me crystal reports related assemblies missing error then I took all Cr assemblies from my GAC to the bin, republished and r

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.085 (s). 11 q(s)