I'm trying to get the content header query string returned. I'm getting a response but it does not include the query string I am trying to pass. I'm running on an Apache server.
$postdata = http_build_query(
array(
'feed_them_social' => 'yes',
'refresh_token' => get_option( 'custom_refresh_token' ),
'time' => esc_html( get_option( 'custom_token_exp_time' ) ),
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$command = 'curl --data "' . $context . '" https://my-url.com';
exec($command, $token);
$output = implode('', $token);
print_r( $output );
I added this to php file on the server I am trying to get a response from. I just want to print out the header content with my query string for now but not having any luck.
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
stream_context_create doesn't generate a string which you can concatenate onto a command with the . operator. What it does is sets up a "resource" (a memory structure, a bit like an object where everything is private) for use with selected PHP functions, such as file_get_contents.
If you want to use curl, use PHP's built-in curl functions, or a more user-friendly library like Guzzle.
If for some reason you really need to construct a set of command-line options, you have to do that yourself (and deal with all the risks of accidentally running the wrong thing), PHP doesn't know how to generate the right argument for curl or any other command.
Is there an easy way to send out push notifications in PHP without using external libraries? Here is my current code. when executed the server gives a 400 UnauthorizedRegistration error. I do not care about how fast or efficient the process is, I am fine with sending one notification at a time.
My PHP code is:
<?php
ini_set("display_errors","1");
$endpoint = "https://fcm.googleapis.com/fcm/send/fImmyvrGiSo:APA91bFg8A4N4GLmJMhouxPfw_R3ocv44uBaNkZu_JMVjAvueISJUJTQROpVxlBnX8PIeJGwE5s1pvLAldtcW-z6WzZ0Ixus2fc3jUADGbJ2L8kAdMv56S5cSmKMsFmPwDsdd2MoCrHC";
$postdata = http_build_query(
array(
"p256dh" => "BAHBGTIPl7M1v8Ui7EaNVlauLmi_jEJOreCQ3YTRu_nWgF4k8nwP5rewGWO86-3wP8yZ86GoKjHQpK_0sls05FI=",
"auth" => "V08681gA2Gs_2x_UNFCN0g=="
)
);
$opts = array('http' =>
array(
'ignore_errors' => true,
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $postdata
)
);
$context = stream_context_create($opts);
// here file_get_contents is used to send a POST request
$result = file_get_contents($endpoint, false, $context);
echo $result;
?>
My push subscription is:
{"endpoint":"https://fcm.googleapis.com/fcm/send/dcgCC59wHCE:APA91bHEzFoal6MXgXWt16aSdGHFAeS7D4vre99pCvzU_QWK22YFkmYdUQ5OmiLmUUbuhyiFEDHg61TrpllZ-TcaSgqXXOIcyTUf_0I-ngZ--aH2OFnEIrB2eI-ZRiArHD5LVAAz1EiM","expirationTime":null,"keys":{"p256dh":"BAHBGTIPl7M1v8Ui7EaNVlauLmi_jEJOreCQ3YTRu_nWgF4k8nwP5rewGWO86-3wP8yZ86GoKjHQpK_0sls05FI=","auth":"V08681gA2Gs_2x_UNFCN0g=="}}
I hope my question will be understood, my english is a not so good.
I'm nearly new with PHP and I just discovered REST APIs: I'm trying to use a REST API from my PHP script. Docs for the API can be found here
My final goal is to get a single product from this webservice and update it by adding the wholesalePrices array.
I've already managed to perform a GET request using file_get_contents(), in order to get the product ID i want to update. Now I have such id but can't understand how to perform the PUT request: as far I can understand, there are mainly two ways to do REST calls in PHP: one with file_get_contents, another by using cURL.
Since I used file_get_contents for my GET request, I continued with this approach, but my code:
$wholesalePrices = json_encode($wholesalePrices);
$dataRAW = array(
"wholesalePrices" => $wholesalePrices
);
$dataToPut = http_build_query($dataRAW);
$context = [
'http' => [
'method' => 'PUT',
'header' => "Authorization: apikeystring\r\n" . "Content-Length: " . strlen($dataToPut) . "\r\n" . "Content-Type: application/json\r\n",
'content' => $dataToPut
]
];
$context = stream_context_create($context);
$url = "https://app.ecwid.com/api/v3/xxxxxxx/products/".urlencode($productId)."?token=".urlencode(myToken);
$result = file_get_contents ($url, false, $context);
returns a PHP warning:
Warning: file_get_contents(https://app.ecwid.com/api/v3/xxxxxxxxx/products/xxxxxxxxx?token=xxxxxxxxxxx): failed to open stream: HTTP request failed! HTTP/1.1 400 Wrong JSON format: A JSONObject text must begin with '{' at 1 [character 2 line 1] in upload.php on line 95
var_dumping $wholesalePrices just after the json_encode() results in
string '[{"quantity":1,"price":0},{"quantity":5,"price":6},{"quantity":25,"price":12},{"quantity":100,"price":25}]' (length=106)
where am I wrong?
ok, I tried using RamRaider approach and now my code is this
$data = json_encode(array('wholesalePrices' => $wholesalePrices)/*, JSON_FORCE_OBJECT*/);
$dataRAW = array(
"wholesalePrices" => $wholesalePrices
);
$dataToPut = $dataRAW;
$dataToPut = http_build_query($dataRAW);
$context = array('http' => array('method' => 'PUT',
'header' => "Authorization: apikeystring\r\nContent-Length: ".strlen($data)."\r\nContent-Type: application/json\r\n",
'content' => $data));
$context = stream_context_create($context);
$url = "https://app.ecwid.com/api/v3/".urlencode(MY_STORE_ID)."/products/".urlencode($productId)."?token=".urlencode(MY_TOKEN);
$result = file_get_contents ($url, false, $context);
But I obtain a HTTP request failed! HTTP/1.1 400 Field Product.wholesalePrices should be an array message.
If I comment the , JSON_FORCE_OBJECT instead, the HTTP message becomes 409 Conflict and it refers at the line with $result = file_get_contents ($url, false, $context); so perhaps I am on the right track, but how can I troubleshoot such error?
ok, done some mods: now - after the json_encode() - my dataToPut (which I put in "Content" in the HTTP request) var_dumps as following (WPPair is a class I specifically created to reproduce the format required):
object(stdClass)[3]
public 'wholesalePrices' =>
array (size=3)
1 =>
object(WPpair)[5]
public 'quantity' => int 5
public 'price' => int 6
2 =>
object(WPpair)[4]
public 'quantity' => int 25
public 'price' => int 12
3 =>
object(WPpair)[6]
public 'quantity' => int 100
public 'price' => int 25
so I think it has to be right for the api. But I still get a HTTP request failed! HTTP/1.1 400 Bad Request
Ok, finally I managed to form a (perhaps) right structure for my JSON, all the more so as Postman validates my dataToPut with an HTTP
200 OK
And my test record results updated.
This is the print_r() output on dataToPut after json_encode():
string
'{"id":56782231,"wholesalePrices":[{"quantity":5,"price":5.64},{"quantity":25,"price":5.28},{"quantity":100,"price":4.5}]}'
(length=121)
However, if I try to send the same JSON from my PHP page, I still get a
failed to open stream: HTTP request failed!
and in fact, my records still aren't updated.
Here's my code:
$dataToPut = $dataRAW;
$dataRAW = http_build_query($dataRAW);
$context = [
'http' => [
'method' => 'PUT',
'header' => "Authorization: apikeystring\r\n" . "Content-Length: ".sizeof($dataToPut)."\r\n" . "Content-Type: application/json\r\n",
'content' => $dataToPut
]
];
$context = stream_context_create($context);
$url = "https://app.ecwid.com/api/v3/xxxxxxx/products/".urlencode($productId)."?token=".urlencode(myToken);
$dataToPut = json_encode($dataToPut);
$result = file_get_contents($url, false, $context);
Where am I wrong this time?
After rewriting my code by using cURL instead of file_get_contents to connect to the API, I managed to get it to work.
Now the API call part looks like this:
$dataToPut = $dataRAW;
$dataRAW = http_build_query($dataRAW);
$context = [
'http' => [
'method' => 'PUT',
'header' => "Authorization: apikeystring\r\n" . "Content-Length: ".sizeof($dataToPut)."\r\n" . "Content-Type: application/json\r\n",
'content' => $dataToPut
]
];
$context = stream_context_create($context);
$url = "https://app.ecwid.com/api/v3/xxxxxxx/products/".urlencode($productId)."?token=".urlencode($myToken);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: app.ecwid.com','Content-Type: application/json;charset=utf-8','Cache-Control: no-cache'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $dataToPut);
// Make the REST call, returning the result
$response = curl_exec($curl);
echo ($response."<br/>");
if (!$response) {
echo("Connection Failure: ".curl_error($curl));
die();
}
curl_close($curl);
Without seeing the documentation for their api I might be leading you astray but the error message does suggest that their api expects json data whereas you encode the data and then add to an array which seems back to front somehow.
$data = json_encode( array( 'wholesalePrices' => $wholesalePrices ), JSON_FORCE_OBJECT );
/* Perhaps this also is not required */
#$data = http_build_query( $data );
$context = array(
'http' => array(
'method' => 'PUT',
'header' => "Authorization: apikeystring\r\nContent-Length: " . strlen( $data ) . "\r\nContent-Type: application/json\r\n",
'content' => $data
)
);
$context = stream_context_create( $context );
$url = "https://app.ecwid.com/api/v3/7560546/products/".urlencode( $productId )."?token=".urlencode( myToken );
$result = file_get_contents( $url, false, $context );
Having had a quick look at the api documentation I found the following:
PUT https://app.ecwid.com/api/v3/{storeId}/products/{productId}?token={token}
Request body
A JSON object of type 'Product’ with the following fields:
wholesalePrices -> Array<WholesalePrice>
described as: "Sorted array of wholesale price tiers (quantity limit and price pairs)"
The given example request to update a product is:
PUT /api/v3/4870020/products/39766764?token=123456789abcd HTTP/1.1
Host: app.ecwid.com
Content-Type: application/json;charset=utf-8
Cache-Control: no-cache
{
"compareToPrice": 24.99,
"categoryIds": [
9691094
]
}
So using test data
$wholesalePrices=array(
array('quantity'=>10,'price'=>1000),
array('quantity'=>2,'price'=>43),
array('quantity'=>43,'price'=>34),
array('quantity'=>7,'price'=>5),
array('quantity'=>9,'price'=>63),
);
$data = json_encode( array( 'wholesalePrices' => $wholesalePrices ) );
echo '<pre>',$data,'</pre>';
Gives data in the format:
{
"wholesalePrices":[
{"quantity":10,"price":1000},
{"quantity":2,"price":43},
{"quantity":43,"price":34},
{"quantity":7,"price":5},
{"quantity":9,"price":63}
]
}
I am trying to create a issue in Jira .
I am able to make a GET request with a proper response, but the problem arises when i make a POST request.Here is the code.
<?php
$userName ='xxxxxxxxxxxxxxxx';
$password ='xxxxxxxxxxxx';
$data = ['fields' => ['projects'=>['key'=>'ABC'],'summary'=>'abc','description'=>'abc','issuetype'=>['name'=>'Task']]];
$data = http_build_query($data);
$context =
array("http"=>
array(
"method" => "POST",
"header" => "Authorization: Basic " . base64_encode($userName.':'.$password) . "\r\n".
'Accept: application/json'."\r\n".
"Content-Length: ".strlen($data)."\r\n".
'Content-Type: application/json'."\r\n",
'content' => $data,
'verify_peer'=>false,
'verify_peer_name'=>false,
)
);
$context = stream_context_create($context);
$result = file_get_contents("https://xxxxx.atlassian.net/rest/api/2/issue/", false, $context);
echo "The result is ", $result;
?>
I get the following error:
Warning:file_get_contents(https://xxxxx.atlassian.net/rest/api/2/issue/):
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in
/var/www/html/test/new.php on line 27
Could any one help me out? Thanks
P.S
I dont want to use curl as an alternative to http-streams as google app engine does not support curl.
http_build_query() generates a url-encoded string. However, the API requires JSON. You should be using json_encode() instead.
Change:
$data = http_build_query($data);
To:
$data = json_encode($data);
While maybe not your only problem, this is definitely one problem that would result in an 400 Bad Request.
Could you have a typo in your code?
$data=array('fields' => array ('project' => array ('key' => 'WOIS',),'summary' => 'ABC','description' => 'ABC','issuetype' => array ('name' => 'Task',),),);
vs
$data = ['fields' => ['projects'=>['key'=>'WOIS'],'summary'=>'adfsdf','description'=>'adfefsa','issuetype'=>['name'=>'Task']]];
the first line says project while the second line says projects
I have a simple file_get_contents using basic http auth:
$opts = array(
'http' => array(
'timeout' => 15,
'header' => array("Authorization: Basic "
. base64_encode("$user:$pwd"))
)
);
$context = stream_context_create($opts);
$data = file_get_contents($url, false, $context);
When I run this inside one PHP box, it arrives without the Authorization header. When I run it in another box, the header arrives.
What kind of info do I need to look for in order to find the cause?