开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

使用 PHP CURL 执行 HTTP POST

一位客户最近给我带来了一个独特的挑战。我的客户希望将信息请求表数据收集到数据库中。没什么新鲜的,对吧?好吧,有一个障碍——信息不会保存在本地主机数据库中——它需要存储在我无法直接连接到的远程数据库中。

我考虑了解决这一挑战的所有可能解决方案并确定了这个流程:

  1. 用户将像往常一样提交表单。
  2. 在处理 PHP 的表单中,我使用 cURL 执行 POST 传输到客户服务器上的 PHP 脚本。
  3. 远程脚本会对客户的私有数据库执行 MySQL INSERT 查询。

此解决方案效果很好,所以我想与您分享。以下是使用 PHP CURL 库执行 POST 的方法。

//extract data from the post
//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
	'lname' => urlencode($_POST['last_name']),
	'fname' => urlencode($_POST['first_name']),
	'title' => urlencode($_POST['title']),
	'company' => urlencode($_POST['institution']),
	'age' => urlencode($_POST['age']),
	'email' => urlencode($_POST['email']),
	'phone' => urlencode($_POST['phone'])
);

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

你会如何解决这个问题?

未经允许不得转载:我爱分享网 » 使用 PHP CURL 执行 HTTP POST

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏