I am trying to write a basic curl code in PHP. I think what I am doing is right (as far as I have read) -
$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);
This is what data.php looks like:
$_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);
}
I can't understand why this is not working. The code gets stuck at curl_exec()
. I will do sanitization, and use prepared statements once I get this to work.
This is the log:
* 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
And it gets stuck there. What am I doing wrong here? Does curl not work on localhosts?
EDIT: This is a major change, but I don't think it would be right to change the original question too much. I reduced all of this down to -
<?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);
?>
Which also gets stuck. However, the same thing works with www.example.com
. So I think the problem is with retrieving my URL.
this is the log:
* 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
only has an echo "Hello";
right now to test it
I can remove the previous parts of the question if they are not necessary.