使用curl将名称值对发布到URL

时间:2013-02-11 16:20:54

标签: php post curl

我已注册了基于网络的短消息服务,以发送短信以确认网络表单提交。我使用的是CURL,我的PHP代码如下

$url = "http://www.mysmservice.co.uk/smsgateway/sendmsg.aspx?";
$param = "username=" . $username . "&password=" . $password . "&to=" . $diner_mobile . "&text=";
$smsmessage = "Hello, your table booking for " . $bookingdate . " at " . $booking_time . " is confirmed " , " Myrestaurant";

$ch = curl_init() or die(curl_error()); 
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$param); 
curl_setopt($ch, CURLOPT_PORT, 80);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$data1=curl_exec($ch) or die(curl_error());
curl_close($ch); 

但它似乎没有向URL发布任何内容(mysmsservice告诉我日志不指示任何传入请求)。但是,如果我访问以下URL并替换相应的变量,则服务正常工作。

http://www.mysmsservice.co.uk/smsgateway/sendmsg.aspx?username=MyUsername& password = MyPassword& to = 44771012345,44771054321& text = TheMessage

不确定我是否正确使用了CURL调用。任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:0)

也许SMS服务表示在邮件丢失时没有有效请求。如果你在这里查看你的代码:

$param = "username=" . $username . "&password=" . $password . "&to=" . $diner_mobile . "&text=";

您永远不会将消息添加到$ param。但是,您可以在变量$ smsmessage中构建它。您应该将代码修改为:

$smsmessage = "Hello, your table booking for " . $bookingdate . " at " . $booking_time . " is confirmed, " . " Myrestaurant";
$param = "username=" . $username . "&password=" . $password . "&to=" . $diner_mobile . "&text=" . $smsmessage;

答案 1 :(得分:0)

如果您说如果您访问直接在地址栏中输入所有参数的页面(作为GET参数),那么它就有用了,那么这意味着您不需要进行POST调用。

在这种情况下,您甚至不需要使用cURL:

$base = 'http://www.mysmservice.co.uk/smsgateway/sendmsg.aspx';
$params = array(
    'username' => $username,
    'password' => $password,
    'to'       => $diner_mobile,
    'text'     => 'Your booking has been confirmed',
);
$url = sprintf('%s?%s', $base, http_build_query($params));
$response = file_get_contents($url);

但是,如果你这样做,需要使用POST,这应该有效:

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL            => $base,
    CURLOPT_POST           => 1,
    CURLOPT_POSTFIELDS     => $params,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_SSL_VERIFYHOST => 0, // to avoid SSL issues if you need to fetch from https
    CURLOPT_SSL_VERIFYPEER => 0, // same ^
));
$response = curl_exec($curl);

注意:我没有明显测试代码,但这是我通常发出cURL请求的方式。