Good day! My client gave us an API endpoint where the response is XML when you pass in some commands, I would like to know if there's a way where we can run the endpoint in the PHP and get the response back, I have tried using PHP curl but the response shows 400 or bad request. I can access the endpoint with the commands/parameters in the URL browser so it works. But when I try it using curl, there is no response in it. Is this possible, or am I doing something wrong with my code?
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.winquote.net/cgi-bin/compete.pl?dc=-cv1.5 -ccca -qt0 -pccaXXXXXXXXX -rt0 -dob11061992 -gen1 -rR -fa500000 -pg0 -pi4 -lc1 -pm0 -rc0 -rop0 -langen -fmt -ceilp -faEXACT",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Have a look at White spaces in postFields in PHP Curl which may answer your question.
The only issue here is the query param are not proper and '400' response is saying you so. In browser you you look the spaces are converted to '%20'.The browser has done that work for you. You have to do the similar thing i.e. encode your query parameter because of the spaces before doing the post request.
From https://curl.haxx.se/docs/manpage.html#--data-urlencode
--data-urlencode
(HTTP) This posts data, similar to the other -d, --data options with
the exception that this performs URL-encoding.
To be CGI-compliant, the part should begin with a name followed
by a separator and a content specification. The part can be
passed to curl using one of the following syntaxes:
Related
I am trying to send a file to a slim API via curl PHP.
Actually I have a PHP file that receive a from post data and is suppose to call a slim API with the received data and slim API is going to store the data in the database. It works fine when there is no file in the data but when I send a file to API along with other data using PHP curl and set the 'content-type: multipart/form-data' I miss all the posted data in API side. I couldn't figure out what's wrong with it!!!
By the way it works well when I test the API with postman. The API successfully gets the file and save it in the storage. The problem must be in the client side where I call the API using curl and PHP.
Could anybody please help me how to setup the curl call to to make the API work ?
Thanks a lot
route.php
$app->post('/softwareskills/insert', SoftwareSkillsController::class . ':insert')->setName('SoftwareSkills.insert');
SoftwareSkillsController.php
class SoftwareSkillsController {
public function insert(Request $request, Response $response, array $args)
{
$params= $request->getParsedBody();
$file = $request->getUploadedFiles();
var_dump($params); // return empty array!
var_dump($file); // return empty array!
}
}
upload.php
<?php
// $_POST and $_FILES to send them via php CURL
$tmpfile = $_FILES['attachment']['tmp_name'];
$filename = basename($_FILES['attachment']['name']);
$filemime = $_FILES['attachment']['type'];
$data = array(
"StNo" => $_POST['StNo'],
"SoftwareName" => $_POST['SoftwareName'],
"proficiency" => $_POST['proficiency'],
"attachment" => new CURLFile($tmpfile,$filemime,$filename)
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://myapi.com/softwareskills/insert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => array(
"content-type: multipart/form-data"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I used the function file_get_contents to get content from a website. but just see messege "sorry! something went wrong."
My code here:
<?php
$kkk = 'https://batdongsan.com.vn/phan-tich-nhan-dinh/thi-truong-can-ho-cao-cap-can-mot-su-sang-loc-khat-khe-ar97716';
$ddd = file_get_contents($kkk);
echo $ddd;
?>
Can you help me explain this error or any idea
thank you so much!
Yes, file_get_contents() returns that msg "sorry! something went wrong." for me also. Make API call using PHP CURL. Let's try like this way-
Note:
URL which is not retrieved by file_get_contents(), because their
server checks whether the request come from browser or any script?. If
they found request from script they simply disable page contents.
So that you have to make a request similar as browser request. PHP
Curl is suitable choice for this kind of job. See here
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://batdongsan.com.vn/phan-tich-nhan-dinh/thi-truong-can-ho-cao-cap-can-mot-su-sang-loc-khat-khe-ar97716",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I try to get a booking.com page from a hotel to fetch the prices afterwards with regex. The problem is the following:
I call file_get_contents with parameter like checkin and checkout (file_get_contents("/hotel/at/myhotel.html?checkin=2017-10-12&checkout=2017-10-13")) dates so that the prices are shown to the visitor. If I watch the source code in the browser I see the entry:
b_this_url : '/hotel/at/myhotel.html?label=gen173nr-1FCAsoDkIcbmV1ZS1wb3N0LWhvbHpnYXUtaW0tbGVjaHRhbEgHYgVub3JlZmgOiAEBmAEHuAEHyAEM2AEB6AEB-AEDkgIBeagCAw;sid=58ccf750fc4acb908e20f0f28544c903;checkin=2017-10-12;checkout=2017-10-13;dist=0;sb_price_type=total;type=total&',
If I echo the string from file_get_contents the string looks like:
b_this_url : '/hotel/at/myhotel.html',
So all parameters that I passed to the url with file_get_contents are gone and therefore I couldn't find any prices with my regex on the page ...
Does anyone have a solution for this problem?
The webpage is not completely generated server-side, but it relies heavily on JavaScript after the HTML part loads. If you are looking for rendering the page as it looks in browser, I think you should use php curl instead of file_get_contents() for this kind of web scraping thing. I generated an automatic code for you from Postman (a google chrome extension / standalone desktop app) for your given url. The response contains the full url with params. See the image and I posted the code for you also.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.booking.com/hotel/at/hilton-innsbruck.de.html?checkin=2017-10-10%3Bcheckout%3D2017-10-11",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 581a75a7-6600-6ed6-75fd-5fb09c25d927"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I'm trying to create a relatively simple PHP endpoint for users to send requests to. I know that the endpoint is working because when I accessed it using cURL the parameters I sent to my database we're added. The problem however is that when I use
var_dump($response);
The page returns "NULL".
So the code is working fine, I just want to know how to print an error/success message
This is what I've tried so far on the endpoint
header("HTTP/1.1 200 OK");
header('Content-Type: text/plain');
echo 'Success message';
the full cURL code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
);
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = json_decode($resp, true);
var_dump($response);
So how can I get the success message to properly show instead of "NULL"?
Test if your curl code returns something by testing: var_dump($resp). It looks like NULL comes from json_decode. You are not returning valid JSON from the endpoint.
php > var_dump(json_decode("Success message", true));
NULL
Try returning a json string such as:
php > echo json_encode("Success", true);
"Success"
Note the " around it. This encodes a json string. See the JSON spec for a reference on how to encode json. Best practice, if your return json, then run your content through json_encode().
Your curl code seems correct.
I'm working with Curl to make some petitions to a php script, I'm trying to make the petitions as you see below, my script is ajax2.php
$params=['name'=>'John', 'surname'=>'Doe', 'age'=>36,'method'=>'prueba'];
$defaults = array(
CURLOPT_URL => getcwd().'\src\myApp\ajax2.php',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
}
but I get this error: Couldn't send request: Could not resolve host: C so, how should I call a script that is inside my project folder?
curl or libcurl is, as they put it on the official site, an "URL transfer library", i.e. it expects to work on URL targets. However, you are passing it a file path like C:\PathToYourStuff\src\myApp\ajax2.php, which is not a valid URL format. That is why the error message says
Could not resolve host: C
Interpreting the path above as an URL would mean that C is the host name, because the colon (":") is the part which separates the hostname from the port in an URL. (The part behind that is then nonsense, from the viewpoint of an URL parser, but it does not even get that far, because the supposed host name cannot be resolved.)
So what you have to use instead is an URL that points to that file, e.g. something like http://localhost/path-to-your-stuff/src/myApp/ajax2.php.
So change your code to something like this and adjust the URL as needed:
$params=['name'=>'John', 'surname'=>'Doe', 'age'=>36,'method'=>'prueba'];
$defaults = array(
CURLOPT_URL => 'http://localhost/path-to-your-stuff/src/myApp/ajax2.php',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
curl_exec($ch);
// ... and so on, as seen in your question