使用curl用PHP

问题描述:

我有使用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 
)); 

所以我的问题是,是代码是否正确?以及如何测试它?

虽然这是一个简单的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

如果您可以使用浏览器中的地址栏访问网址,那么它是一个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