我正在尝试用PHP编写基本的curl代码。我认为我所做的是正确的(据我所读)-
$url = '0.0.0.0:8080/data.php';
$data = array('username'=>'name','email'=>'abcd@gmail.com');
$payload = json_encode(array($data));
print_r($payload);
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_PORT , 8080);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
//curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type:application/json'));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
print_r(curl_getinfo($ch));
curl_close($ch);
这是data.php的样子:
$_POST=json_decode(file_get_contents("php://input"),1);
print_r($_POST);
if(isset($_POST['username'],$_POST['email'])){
$username=mysqli_real_escape_string($db,$_POST['username']);
$email=mysqli_real_escape_string($db,$_POST['email']);
$query = "INSERT INTO tbl_user (username, email)
VALUES('$username', '$email')";
mysqli_query($db, $query);
}
我不明白为什么这不起作用。代码卡在curl_exec()
处。我将进行清理,并在工作后使用准备好的语句。
这是日志:
* Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 8080 (#0)
> POST /data.php HTTP/1.1
Host: 0.0.0.0:8080
Accept: */*
Content-Type:application/json
Content-Length: 46
* upload completely sent off: 46 out of 46 bytes
它卡在那里。我在这里做错了什么? curl在本地主机上不起作用吗?
编辑: 这是一个重大变化,但是我认为改变原始问题不大正确。我把所有这些减少到-
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
//curl_setopt ($ch, CURLOPT_PORT , 8080);
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/data.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
// grab URL and pass it to the browser
curl_exec($ch);
if ( curl_error ( $ch ) ) { echo curl_error ( $ch ); }
// close cURL resource, and free up system resources
curl_close($ch);
?>
这也被卡住了。但是,www.example.com
同样适用。因此,我认为问题出在检索我的URL。
这是日志:
* Rebuilt URL to: http://localhost:8080/
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET / HTTP/1.1
Host: localhost:8080
Accept: */*
data.php
现在只有echo "Hello";
可以对其进行测试
如果不需要前面的部分,我可以删除它们。