Question

I have a server-side call with PHP to Bing translate to store input results from one language to English. If the connection is slow, the function will time out and throw an ugly PHP error that the time exceeded 30 seconds. Is there a way to stop the translation function attempt after 10 seconds and throw a custom error to the user that I've written an not throw a system error?

PHP code called in script:

//Translate product description from native language to english with Bing (Microsoft) API
if ($_POST['Translate_Code'] != 'en' ){//do not translate if already in english
require_once('./classes/Az1/BingTranslate.php');
$gt = new Az1_BingTranslateWrapper();
$lang_trans = $_POST['Translate_Code'];
/* Translate from "Native Language" to "English" */
$eng_description = $gt->translate($description, $lang_trans, "en");
} else{//language is english
    $eng_description= $description;
}

Bing Translation Classes relevant:

class Az1_AccessTokenAuthentication {
/*
 * Get the access token.
 *
 * @param string $grantType    Grant type.
 * @param string $scopeUrl     Application Scope URL.
 * @param string $clientID     Application client ID.
 * @param string $clientSecret Application client ID.
 * @param string $authUrl      Oauth Url.
 *
 * @return string.
 */
function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
    try {
        //Initialize the Curl Session.
        $ch = curl_init();
        //Create the request Array.
        $paramArr = array (
             'grant_type'    => $grantType,
             'scope'         => $scopeUrl,
             'client_id'     => $clientID,
             'client_secret' => $clientSecret
        );
        //Create an Http Query.//
        $paramArr = http_build_query($paramArr);
        //Set the Curl URL.
        curl_setopt($ch, CURLOPT_URL, $authUrl);
        //Set HTTP POST Request.
        curl_setopt($ch, CURLOPT_POST, TRUE);
        //Set data to POST in HTTP "POST" Operation.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
        //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //Execute the  cURL session.
        $strResponse = curl_exec($ch);
        //Get the Error Code returned by Curl.
        $curlErrno = curl_errno($ch);
        if($curlErrno){
            $curlError = curl_error($ch);
            throw new Exception($curlError);
        }
        //Close the Curl Session.
        curl_close($ch);
        //Decode the returned JSON string.
        $objResponse = json_decode($strResponse);
        if ($objResponse->error){
            throw new Exception($objResponse->error_description);
        }
        return $objResponse->access_token;
    } catch (Exception $e) {
        echo "Exception-".$e->getMessage();
    }
}
}

/*
* Class:HTTPTranslator
* 
* Processing the translator request.
*/
class Az1_HTTPTranslator {
/*
 * Create and execute the HTTP CURL request.
 *
 * @param string $url        HTTP Url.
 * @param string $authHeader Authorization Header string.
 * @param string $postData   Data to post.
 *
 * @return string.
 *
 */
function curlRequest($url, $authHeader, $postData=''){
    //Initialize the Curl Session.
    $ch = curl_init();
    //Set the Curl url.
    curl_setopt ($ch, CURLOPT_URL, $url);
    //Set the HTTP HEADER Fields.
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
    //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
    if($postData) {
        //Set HTTP POST Request.
        curl_setopt($ch, CURLOPT_POST, TRUE);
        //Set data to POST in HTTP "POST" Operation.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    //Execute the  cURL session.
    $curlResponse = curl_exec($ch);
    //Get the Error Code returned by Curl.
    $curlErrno = curl_errno($ch);
    if ($curlErrno) {
        $curlError = curl_error($ch);
        throw new Exception($curlError);
    }
    //Close a cURL session.
    curl_close($ch);
    return $curlResponse;
}
}

class Az1_BingTranslateWrapper{
protected $_clientID = "####"; //Client ID of the application
protected $_clientSecret = "####";//Client Secret key of the application   
protected $_authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";//OAuth Url
protected $_scopeUrl = "http://api.microsofttranslator.com";//Application Scope Url
protected $_grantType = "client_credentials";//Application grant type
protected $_accessToken = "";//Id generated from Microsoft
protected $_authHeader = "";//Takes access token created for input in Url
protected $_detectMethodUrl = "";//Forms Url for translation
protected $_strResponse = "";//translation of supplied text

public function translate($text, $lang_from, $lang_to){

//Create the AccessTokenAuthentication object.
$authObj      = new Az1_AccessTokenAuthentication();
//Get the Access token.
$this->_accessToken  = $authObj->getTokens($this->_grantType,$this->_scopeUrl,$this->_clientID,$this->_clientSecret,$this->_authUrl);
//Create the authorization Header string.
$this->_authHeader = "Authorization: Bearer ". $this->_accessToken;

//Create the Translator Object.
$translatorObj = new Az1_HTTPTranslator();

//HTTP Detect Method URL.
$this->_detectMethodUrl = "http://api.microsofttranslator.com/V2/Http.svc/Translate?text=".urlencode($text)."&from=".$lang_from."&to=".$lang_to;
//Ask for response as JSON
//Call the curlRequest.
$this->_strResponse = $translatorObj->curlRequest($this->_detectMethodUrl, $this->_authHeader);
//Remove XML formatting
$str_start = strrpos($this->_strResponse,'/">')+3;
$this->_strResponse = substr($this->_strResponse,$str_start,strlen($this->_strResponse)-$str_start-9);
return $this->_strResponse;
 }
Était-ce utile?

La solution

Ok youre using cURL - just set the CURLOPT_TIMEOUT as something less than your max_execution_time and then throw an exception on that timeout. and then handle that however... easy peasy :-)

It should be noted that values for CURLOPT_TIMEOUT are in seconds, but there is also CURLOPT_TIMEOUT_MS which is in milliseconds.

Additionally there are a number of additional options to deal with timeouts and speeds for connections, dns resolution, and overall bandwidth. You might also want to make use of those

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top