I have 2 folders restdemo1 and restdemo2.
1 has index.php and 2 has api.php I am trying to fetch data from table and show it, but getting nothing using curl
index.php->
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
$curl = curl_init('http://localhost/restdemo2/api.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$result = curl_exec($curl);
$errors = curl_error($curl);
var_dump($result);
print_r(json_decode($result));
curl_close($curl);
api.php->
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "root";
$db = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = array();
// output data of each row
while($row = $result->fetch_assoc()) {
$data[]=$row;
//echo "id: " . $row["id"]. " - Name: " . $row["user_fullname"]. " Password: " . $row["user_password"]. "<br>";
}
return json_encode($data);
} else {
return "0 results";
}
There's a simple way to identify where your problem lies - first, try to access api.php with the browser and see if you're getting any response. If not - your problem is there. The, try to run index.php on another URL. If you did not retrieve anything - the problem is there (or also there).
In any case, try this for CURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/restdemo2/api.php');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$pageResponse = curl_exec($ch);
curl_close($ch);