Curl request times out php

Hi everyone,
We r trying to make some api calls via curl and our last curl request times out for some reason.

Now we have a small chunk of code that sends an xml file to a seperate system via curl.

As far as we can tell the call code is corect but maybe there s something we r missing in our curl request options so i will paste the code.

Now here s the first part of code, where we just prep the required xml data and make the function call:
	
	$paymentXml='<Payments>
  <Payment>
    <Invoice>
      <InvoiceNumber>'.$invoiceNumber.'</InvoiceNumber>
    </Invoice>
    <Account>
      <AccountID>'.$xeroBankAcc.'</AccountID>
    </Account>
    <Date>'.date("Y-m-d").'T00:00:00</Date>
    <Amount>'.$amt.'</Amount>
  </Payment>
</Payments>';
//echo $paymentXml;
$response = $XeroOAuth->request('PUT', $XeroOAuth->url('Payments', 'core'), array(), $paymentXml);
		  if ($XeroOAuth->response['code'] == 200) {
		    $payment = $XeroOAuth->parseResponse($XeroOAuth->response['response'], $XeroOAuth->response['format']);
		    echo $payments;
		  } else {
		    outputError($XeroOAuth); 
		  }//*/
	}

Open in new window

The second part is from the wrapper library privided to us for using that specific api.
Theres a bit more code here but i think these r all the function that r used when making this call so i ll paste it all here in hope that someone will enlighten us.
 /**
     * Makes a curl request. Takes no parameters as all should have been prepared
     * by the request method
     *
     * @return void response data is stored in the class variable 'response'
     */
    private function curlit()
    {
        // method handling
        switch ($this->method) {
            case 'POST':
                
                break;
            default:
                // GET, DELETE request so convert the parameters to a querystring
                if (!empty($this->request_params)) {
                    foreach ($this->request_params as $k => $v) {
                        // Multipart params haven't been encoded yet.
                        // Not sure why you would do a multipart GET but anyway, here's the support for it
                        if ($this->config['multipart']) {
                            $params[] = $k . '=' . $v;
                        } else {
                            $params[] = $this->safe_encode($k) . '=' . $this->safe_encode($v);
                        }
                    }
                    $qs                   = implode('&', $params);
                    $this->url            = strlen($qs) > 0 ? $this->url . '?' . $qs : $this->url;
                    $this->request_params = array();
                }
                break;
        }
        
        // configure curl
        $c         = curl_init();
        $useragent = (isset($this->config['user_agent'])) ? (empty($this->config['user_agent']) ? 'XeroOAuth-PHP' : $this->config['user_agent']) : 'XeroOAuth-PHP';
        curl_setopt_array($c, array(
            CURLOPT_USERAGENT => $useragent,
            CURLOPT_CONNECTTIMEOUT => $this->config['curl_connecttimeout'],
            CURLOPT_TIMEOUT => $this->config['curl_timeout'],
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_SSL_VERIFYPEER => $this->config['curl_ssl_verifypeer'],
            CURLOPT_CAINFO => $this->config['curl_cainfo'],
            CURLOPT_SSL_VERIFYHOST => $this->config['curl_ssl_verifyhost'],
            CURLOPT_FOLLOWLOCATION => $this->config['curl_followlocation'],
            CURLOPT_PROXY => $this->config['curl_proxy'],
            CURLOPT_ENCODING => $this->config['curl_encoding'],
            CURLOPT_URL => $this->sign['signed_url'],
            CURLOPT_VERBOSE => $this->config['curl_verbose'],
            // process the headers
            CURLOPT_HEADERFUNCTION => array(
                $this,
                'curlHeader'
            ),
            CURLOPT_HEADER => FALSE,
            CURLINFO_HEADER_OUT => TRUE
        ));
        
        if ($this->config['application_type'] == "Partner") {
            curl_setopt_array($c, array(
                // ssl client cert options for partner apps
                CURLOPT_SSLCERT => $this->config['curl_ssl_cert'],
                CURLOPT_SSLKEYPASSWD => $this->config['curl_ssl_password'],
                CURLOPT_SSLKEY => $this->config['curl_ssl_key']
            ));
        }
        
        if ($this->config['curl_proxyuserpwd'] !== false)
            curl_setopt($c, CURLOPT_PROXYUSERPWD, $this->config['curl_proxyuserpwd']);
        
        if (isset($this->config['is_streaming'])) {
            // process the body
            $this->response['content-length'] = 0;
            curl_setopt($c, CURLOPT_TIMEOUT, 0);
            curl_setopt($c, CURLOPT_WRITEFUNCTION, array(
                $this,
                'curlWrite'
            ));
        }
        
        switch ($this->method) {
            case 'GET':
            	$contentLength = 0;
                break;
            case 'POST':
                curl_setopt($c, CURLOPT_POST, TRUE);
                $post_body = $this->safe_encode($this->xml);
        		curl_setopt($c, CURLOPT_POSTFIELDS, $post_body);
        		$this->request_params['xml'] = $post_body;
        		$contentLength = strlen($post_body);
                
                break;
            case 'PUT':
                $fh = fopen('php://memory', 'w+');
                $put_body = $this->safe_encode($this->xml);
                fwrite($fh, $put_body);
                rewind($fh);
                curl_setopt($c, CURLOPT_PUT, true);
                curl_setopt($c, CURLOPT_INFILE, $fh);
                curl_setopt($c, CURLOPT_INFILESIZE, strlen($put_body));
                $contentLength = strlen($put_body);
                
                break;
            default:
                curl_setopt($c, CURLOPT_CUSTOMREQUEST, $this->method);
        }
        
        if (!empty($this->request_params)) {
            // if not doing multipart we need to implode the parameters
            if (!$this->config['multipart']) {
                foreach ($this->request_params as $k => $v) {
                    $ps[] = "{$k}={$v}";
                }
                $this->request_params = implode('&', $ps);
            }
            curl_setopt($c, CURLOPT_POSTFIELDS, $this->request_params);
        } else {
            // CURL will set length to -1 when there is no data
            $this->headers['Content-Type']   = '';
            $this->headers['Content-Length'] = $contentLength;
        }
        
        $this->headers['Expect'] = '';
        
        if (!empty($this->headers)) {
            foreach ($this->headers as $k => $v) {
                $headers[] = trim($k . ': ' . $v);
            }
            curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
        }
        
        if (isset($this->config['prevent_request']) && false == $this->config['prevent_request'])
            return;
        
        
        // do it!
        $response = curl_exec($c);
        if ($response === false) {
            $response = 'Curl error: ' . curl_error($c);
            $code     = 1;
        } else {
            $code = curl_getinfo($c, CURLINFO_HTTP_CODE);
        }
        
        $info = curl_getinfo($c);
        
        curl_close($c);
        
        // store the response
        $this->response['code']     = $code;
        $this->response['response'] = $response;
        $this->response['info']   = $info;
        $this->response['format'] = $this->format;
        return $code;
    }
    
    function MakeRequest($endpoint, $parameters, $action, $data, $app_type, $format = "xml")
    {
        $oauthObject = new OAuthSimple();
        
        # Set some standard curl options....
        
        $useragent                       = USER_AGENT;
        $useragent                       = isset($useragent) ? USER_AGENT : 'XeroOAuth-PHP';
        $options[CURLOPT_USERAGENT]      = $useragent;
        $options[CURLOPT_VERBOSE]        = 1;
        $options[CURLOPT_RETURNTRANSFER] = 1;
        $options[CURLOPT_SSL_VERIFYHOST] = 0;
        $options[CURLOPT_SSL_VERIFYPEER] = 0;
        
    }
    
    /**
     * Make an HTTP request using this library. This method doesn't return anything.
     * Instead the response should be inspected directly.
     *
     * @param string $method the HTTP method being used. e.g. POST, GET, HEAD etc
     * @param string $url the request URL without query string parameters
     * @param array  $params the request parameters as an array of key=value pairs
     * @param string $format the format of the response. Default json. Set to an empty string to exclude the format
     
     */
    function request($method, $url, $params = array(), $xml = "", $format = 'xml')
    {
    	// removed these as function parameters for now
    	$useauth = true; $multipart = false;
        
        if (isset($format)) {
            switch ($format) {
                case "pdf":
                    $this->headers['Accept'] = 'application/pdf';
                    break;
                case "json":
                    $this->headers['Accept'] = 'application/json';
                    break;
                case "xml":
                default:
                    $this->headers['Accept'] = 'application/xml';
                    break;
            }
        }
        
        if ($xml !== "")
            $this->xml = $xml;
            
        if($method == "POST")
        	$params['xml'] = $xml;
        
        $this->prepare_method($method);
        $this->config['multipart'] = $multipart;
        $this->url                 = $url;
        if (!isset($_REQUEST['order']))
            $_REQUEST['order'] = "";
        $oauthObject = new OAuthSimple();
        try {
            $this->sign = $oauthObject->sign(array(
                'path' => $url,
                'action' => $method,
                'parameters' => array_merge($params, array(
                    'order' => urlencode($_REQUEST['order']),
                    'oauth_signature_method' => $this->config['signature_method']
                )),
                'signatures' => $this->config
            ));
        }
        
        catch (Exception $e) {
            $errorMessage = $e->getMessage();
        }
        $this->format = $format;
        
        $curlRequest = $this->curlit();
        
        if ($this->response['code'] == 401 && isset($this->config['session_handle'])) {
            if ((strpos($this->response['response'], "oauth_problem=token_expired") !== false)) {
                $this->response['helper'] = "TokenExpired";
				
            } else {
                $this->response['helper'] = "TokenFatal";
            }
            
        }
        if ($this->response['code'] == 403) {
            $errorMessage               = "It looks like your Xero Entrust cert issued by Xero is either invalid or has expired. See http://developer.xero.com/api-overview/http-response-codes/#403 for more";
            // default IIS page isn't informative, a little swap
            $this->response['response'] = $errorMessage;
            $this->response['helper']   = "SetupIssue";
        }
        if ($this->response['code'] == 0) {
            $errorMessage               = "It looks like your Xero Entrust cert issued by Xero is either invalid or has expired. See http://developer.xero.com/api-overview/http-response-codes/#403 for more";
            $this->response['response'] = $errorMessage;
            $this->response['helper']   = "SetupIssue";
        }
        
        
        return $this->response;
    }

Open in new window


Hope to hear from someone son and thank you for your help
webfactorAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kevin CrossChief Technology OfficerCommented:
What are the values of config['curl_connecttimeout'] and config['curl_timeout']? Also check that you do not need to increase (or use indefinite connection timeout) for the following code.

if (isset($this->config['is_streaming'])) {
            // process the body
            $this->response['content-length'] = 0;
            curl_setopt($c, CURLOPT_TIMEOUT, 0);
            curl_setopt($c, CURLOPT_WRITEFUNCTION, array(
                $this,
                'curlWrite'
            ));
        }

CURLOPT_TIMEOUT is for cURL functions; CURLOPT_CONNECTTIMEOUT is for connection.
Reference: http://www.php.net/manual/en/function.curl-setopt.php

Kevin
0
Ray PaseurCommented:
Is the request method GET or POST?  Is there any documentation available for the API?  Here is my teaching example of cURL GET with error reporting.

<?php // RAY_curl_example.php
error_reporting(E_ALL);


// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function my_curl
( $url
, $get_array=array()
, $timeout=3
, $error_report=TRUE
)
{
    // PREPARE THE ARGUMENT STRING IF NEEDED
    $get_string = NULL;
    foreach ($get_array as $key => $val)
    {
        $get_string
        = $get_string
        . $key
        . '='
        . urlencode($val)
        . '&';
    }
    $get_string = rtrim($get_string, '&');
    if (!empty($get_string)) $url .= '?' . $get_string;

    // START CURL
    $curl = curl_init();

    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE THIS BLANK

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt( $curl, CURLOPT_URL,            $url  );
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  ); // HISTORY
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0'  );
    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header  );
    curl_setopt( $curl, CURLOPT_REFERER,        'http://www.google.com'  );
    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate'  );
    curl_setopt( $curl, CURLOPT_AUTOREFERER,    TRUE  );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE  );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE  );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );

    // THIS SEEMS TO LET IT WORK WITH HTTPS SITES
    curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);

    // ON FAILURE HANDLE ERROR MESSAGE
    if ($htm === FALSE)
    {
        if ($error_report)
        {
            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS RETURN XML / HTML STRING
    curl_close($curl);
    return $htm;
}


// USAGE EXAMPLE - PUT YOUR FAVORITE URL HERE
$url = "http://finance.yahoo.com/d/quotes.csv";

// PUT YOUR ARRAY OF KEY=>VALUE PAIRS HERE
$args = array
( 's' => 'tsla'
, 'f' => 'snl1c1ohgvt1'
)
;

// MAKE THE CALL
$htm = my_curl($url, $args, 2, TRUE);
if (!$htm) die("NO $url");

// SHOW WHAT WE GOT
echo "<pre>";
var_dump($args);
echo PHP_EOL . "<b>$url</b>";
echo PHP_EOL . htmlentities($htm);

Open in new window

0
webfactorAuthor Commented:
Apologies about this getting left un-responded to,  the issue was in fact resolved i just don't have all the details as the developer is not with us anymore
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
webfactorAuthor Commented:
Unfortunately i don't have the details of the end result
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.