How to set custom REQUEST header in PHP - php

In creating RESPONSE headers, using header() function will do the trick. How about for request headers?
Thanks in advance!

If you are talking about making a request and specifying your headers, one way to do it is using CURL:
$data = "<soap:Envelope>[...]</soap:Envelope>";
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_URL, "http://example.com/path/for/soap/url/");
curl_setopt($tuCurl, CURLOPT_POST, 1); // if post request
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","SOAPAction: \"/soap/action/query\"", "Content-length: ".strlen($data)));
$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
$info = curl_getinfo($tuCurl);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
} else {
echo 'Curl error: ' . curl_error($tuCurl);
}
curl_close($tuCurl);
echo $tuData;

Related

Something went wrong when I convert API code to PHP CURL

I am trying to convert API code to curl.
Here is the code.
url = config.ERPNEXT_URL + "/api/method/erpnext.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field"
headers = {
'Authorization': "token "+ config.ERPNEXT_API_KEY + ":" + config.ERPNEXT_API_SECRET,
'Accept': 'application/json'
}
data = {
'employee_field_value' : employee_field_value,
'timestamp' : timestamp.__str__(),
'device_id' : device_id,
'log_type' : log_type
}
Here is what I have done.
$curl = config.ERPNEXT_URL . "/api/method/erpnext.hr.doctype.employee_checkin.employee_checkin.add_log_based_on_employee_field";
$data = array(
'employee_field_value' => employee_field_value,
'timestamp' => timestamp.__str__(),
'device_id' => device_id,
'log_type' => log_type
);
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, $curl);
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_POST, 1);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:token ' . config.ERPNEXT_API_KEY . ":" . config.ERPNEXT_API_SECRET));
$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
echo $tuCurl;
} else {
echo 'Curl error: ' . curl_error($tuCurl);
}
curl_close($tuCurl);
I want to know what is wrong with the CURL code?
Many thanks
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
change it to
curl_setopt($tuCurl, CURLOPT_HEADER, $headers);
first store headres in $headers

How to publish media (image) on Mastodon using API?

I'm trying to POST an image on Mastodon (specifically on Humblr) but I cannot get the media_id, the response is null, but I'm not sure where the problem is.
I can publish text, no problem, so the authentication part is fine, I only have the problem with the image, the only difference I can see in the documentation is that "Media file encoded using multipart/form-data".
Here's my code so far...
$headers = ['Authorization: Bearer '.$settings['access_token'] , 'Content-Type: multipart/form-data'];
$mime_type = mime_content_type($urlImage);
$cf = curl_file_create($urlImage,$mime_type,'file');
$media_data = array( "file" => $cf);
$ch_status = curl_init();
curl_setopt($ch_status, CURLOPT_URL, "https://humblr.social/api/v1/media");
curl_setopt($ch_status, CURLOPT_POST, 1);
curl_setopt($ch_status, CURLOPT_POSTFIELDS, $media_data);
curl_setopt($ch_status, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_status, CURLOPT_HTTPHEADER, $headers);
$media_status = json_decode(curl_exec($ch_status));
echo "Response: ".json_encode($media_status);
From this I want to extract the $media_status-> media_id
I don't really know much about 'multipart/form-data' to be honest.
Am I missing something?
This took some trial and error for me as well. Here's what worked for me (PHP 7.3):
$curl_file = curl_file_create('/path/to/file.jpg','image/jpg','file.jpg');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://instanceurl.com/api/v1/media');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer YOUR_TOKEN_HERE',
'Content-Type: multipart/form-data'
]);
$body = [
'file' => $curl_file
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$response = curl_exec($ch);
if (!$response) {
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
echo 'HTTP Status Code: ' . curl_getinfo($ch, CURLINFO_HTTP_CODE) . PHP_EOL;
echo 'Response Body: ' . $response . PHP_EOL;
curl_close($ch);

file_get_content return null for some url

why some url with json content return null on php function get page content?
i used these ways :
file_get_content
curl
http_get
but return null . but when page open with browser json content show on browser ?? anyone can help me?
$url = 'https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/?access_token=9IaRpdmQzFppJMabLHbHyzBaQnm8bM';
$result = file_get_content($url);
return null but in browser show
{"error_description": "Access token has expired.", "error": "invalid_credentials"}
It returns the following:
failed to open stream: HTTP request failed! HTTP/1.1 401 UNAUTHORIZED
So, you have to be authorized.
You ca play with this code snippet (I can't test since token expired again):
<?php
$access_token = "s9spZax2Xrj5g5bFZMJZShbMrEVjIo"; // use your actual token
$url = "https://pardakht.cafebazaar.ir/devapi/v2/api/validate/com.pdgroup.insta/inapp/coin_follow_1/purchases/324234235/";
// Solution with file_get_contents
// $content = file_get_contents($url . "?access_token=" . $access_token);
// echo $content;
// Solution with CURL
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
"Authorization: Basic " . $access_token
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url); // . $params - if you need some params
curl_setopt($ch, CURLOPT_POST, false);
// curl_setopt($ch, CURLOPT_USERPWD, $userPwd);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($ch_error) {
throw new Exception("cURL Error: " . $ch_error);
}
if ($info["http_code"] !== 200) {
throw new Exception("HTTP/1.1 " . $info["http_code"]);
}
echo $result;

File_get_contents and Telegram API (reply_markup)

i want to make a command that send a message with button like this
So i did this
$url = "https://api.telegram.org/" . $token . "/sendMessage?chat_id=" . $message_chat_id . "&text=" . urlencode($message_text) . '&reply_markup={"inline_keyboard":[[{"text":"Visualizza spoiler!","url":"http://google.com/"}]]}';
and it make this url
https://api.telegram.org/censored/sendMessage?chat_id=censored&text=%2Fspoiler+ciao&reply_markup={"inline_keyboard":[[{"text":"Visualizza spoiler!","url":"http://google.com/"}]]}
when i use this url in browser it works but when i use file_get_contents it doesn't
someone can help me?
I had the same problem few days ago and I just tried CURL instead and it worked.
function curl_get_contents($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

PHP function fails at curl_exec command

I'm trying to pull information from Evergage, but based on my console log debugging, the function terminates at the curl_exec function (see comment). debug_to_console("success"); and curl_error both return nothing at all. However, if I debug_to_console("success"); just before curl_exec, it returns properly. When I test run the function, it runs for about 30 seconds and then ends. I originally thought it was a timeout, so I tried removing any time restrictions but it still doesn't seem to be working. Any help would be greatly appreciated. Thanks!
function RetrieveData($account, $dataset, $kind, $apiToken)
{
$port = "";
if ($account === "localtest") {
$port = ":8443";
}
$requestURI = "https://" . $account . ".evergage.com" . $port . "/api/dataset/" . $dataset . "/" . $kind . ".json?_at=" . $apiToken;
debug_to_console("request URL: " . $requestURI);
$session = curl_init();
curl_setopt($session, CURLOPT_FAILONERROR, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($session, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
curl_setopt ($session, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($session, CURLOPT_URL, $requestURI);
// EVERYTHING RUNS FINE UP TO THIS POINT
set_time_limit(0);
$response = curl_exec($session);
debug_to_console("success");
echo 'Curl error: ' . curl_error($session);
$info = curl_getinfo($session);
$responseCode = $info["http_code"];
if ($responseCode >= 300) {
print("Error loading data: " . $responseCode . "<br/>");
print($response);
} else {
$body = substr($response, $info['header_size']);
$decoded_result = json_decode($body, true);
}
curl_close($session);
return $decoded_result;
}
Edit: I should mention that I have printed out $requestURI and it is correct. Navigating to it results in the JSON information that I need downloading right away.

Categories