2013-03-22 85 views
0

我有使用HTTP服務器進行遠程操作短信Android應用程序,它需要得到這樣的構成URL請求:當我輸入使用curl用PHP

http://server.com:9090/sendsms?phone=123456789&text=foobar&pass=123456 

該網址在瀏覽器地址欄和按回車,應用程序發送短信。 我是新來的捲曲,而且我不知道如何來測試它,這是我到目前爲止的代碼:

$phonenumber= '12321321321' 
    $msgtext = 'lorem ipsum' 
    $pass  = '1234' 

    $url = 'http://server.com:9090/sendsms?phone=' . urlencode($phonenumber) . '&text=' . urlencode($msgtext) . '&password=' . urlencode($pass); 



    $curl = curl_init(); 
    curl_setopt_array($curl, array(
     CURLOPT_RETURNTRANSFER => 1, 
     CURLOPT_URL => $url 
)); 

所以我的問題是,是代碼是否正確?以及如何測試它?

回答

1

雖然這是一個簡單的GET,但我不能完全同意hek2mgl。有很多情況,當你必須處理超時,http響應代碼等,這是cURL的用途。

這是一個基本的設置:

$handler = curl_init(); 
curl_setopt($handler, CURLOPT_URL, $url); 
curl_setopt($handler, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($handler, CURLOPT_FOLLOWLOCATION, true); 
// curl_setopt($handler, CURLOPT_MAXREDIRS, 10); // optional 
// curl_setopt($handler, CURLOPT_TIMEOUT, 10); // optional 
$response = curl_exec($handler); 
curl_close($handler); 
+0

使用這種方式,網址會像從瀏覽器訪問一樣進行處理? – thesubroot 2013-03-22 23:41:49

+0

是的,當然curl提供了更多的功能,但請注意,擴展可能沒有安裝在某些環境中。特別是當涉及到共享主機。但是,爲解釋+1;) – hek2mgl 2013-03-22 23:42:01

0

如果您可以使用瀏覽器中的地址欄訪問網址,那麼它是一個HTTP GET請求。最簡單的事情做,在PHP將使用file_get_contents(),因爲它可以對網址進行操作,以及:

$url = 'http://server.com:9090/sendsms?phone=123456789&text=foobar&pass=123456'; 
$response = file_get_contents($url); 

if($response === FALSE) { 
    die('error sending sms'); 
} 

// ... check the response message or whatever 
... 

當然你也可以使用curl擴展,但是對於一個簡單的GET請求,file_get_contents()將是最簡單,最便攜的方案。

+0

。謝謝你們的回答:)我要,只要我可以測試它。 – thesubroot 2013-03-22 23:18:15