Sending XML to URL in PHP (without cURL) - php

Trying to send the following XML data to URL below.
$xml="<?xml version='1.0' encoding='utf-8'?>
<Job>
<Name>Set-up - ".$client_name."</Name>
<Description></Description>
<ClientID>".$accountantid."</ClientID>
<StartDate>".$start_date."</StartDate>
<DueDate>".$due_date."</DueDate>
<TemplateID>".$templateid."</TemplateIDr>
</Job>";
$createjob_url="https:<url>apiKey=[apikey]&accountKey=[accountkey]";
$stream_options = array (
'http' => array (
'method' => "POST",
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => $xml
)
);
$context=stream_context_create($stream_options);
$response=file_get_contents($createjob_url, false, $context);
echo "<p>".$response."</p>";
The response should come out 'OK', but its just blank.
The debug.log has the following error.
PHP Warning: file_get_contents(https:<url>?apiKey=[apikey]&accountKey=[accountkey]): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
I noticed the URL changes the '&' to '&'. If I put the url directly into the browser, it doesnt work, however if I remove 'amp;' it gives me the OK response.
But then if I remove from the code 'false, $context' e.g. file_get_contents($createjob_url), the response comes back 'OK', so the URL is fine.
I am using Google App Engine hence unable to use cURL.
I assume it has something to do with my stream options? Any feedback would be greatly appreciated.

So looks like my issue was a couple of small things.
For the particular URL I was parsing to, I didnt need to have the XML tag, so removed <?xml version='1.0' encoding='utf-8'?>
They also wanted the content type as xml, so changed it to 'header' => "Content-type: text/xml"
Once I got these two sorted, all worked well :)

Related

file_get_contents() gets 403 from api.github.com every time

I call myself an experienced PHP developer, but this is one drives me crazy. I'm trying to get release informations of a repository for displaying update-warnings, but I keep returning 403 errors. For simplifying it I used the most simple usage of GitHubs API: GET https://api.github.com/zen. It is kind of a hello world.
This works
directly in the browser
with a plain curl https://api.github.com/zen in a terminal
with a PHP-Github-API-Class like php-github-api
This works not
with a simple file_get_contents()from a PHP-Skript
This is my whole simplified code:
<?php
$content = file_get_contents("https://api.github.com/zen");
var_dump($content);
?>
The browser shows Warning: file_get_contents(https://api.github.com/zen): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden, the variable $content is a boolean and false.
I guess I'm missing some sort of http-header-fields, but neither can I find those informations in the API-Docs, nor uses my terminal curl-call any special header files and works.
This happens because GitHub requires you to send UserAgent header. It doesn't need to be anything specific. This will do:
$opts = [
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: PHP'
]
]
];
$context = stream_context_create($opts);
$content = file_get_contents("https://api.github.com/zen", false, $context);
var_dump($content);
The output is:
string(35) "Approachable is better than simple."

PHP readfile() returns 'HTTP/1.1 500 Internal Server Error'

A have a strange problem. There are some soap api: https://ctaau.vedaxml.com/cta/sys2/business-enquiry-v3-2
It works in browser fine
I've try to
readfile('https://ctaau.vedaxml.com/cta/sys2/business-enquiry-v3-2');
then I get HTTP/1.1 500.
But curl works fine too:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://ctaau.vedaxml.com/cta/sys2/business-enquiry-v3-2',
));
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
Questiong: how do you think, I can to get http 200 from that api via readfile()? file_get_contents() returns also 500 error.
p.s: why readfile(), but no SoapClient: as I understand, SoapClient class incapsulates readfile() in it. So, if I get success from readfile(), than I'll try to find a solution for SoapClient.
If I open https://ctaau.vedaxml.com/cta/sys2/business-enquiry-v3-2 in my browser, it does give me a HTTP 500 error (check the network tab in developer tools).
The result I'm getting is this:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server</faultcode>
<faultstring>Policy Falsified</faultstring>
<faultactor>https://ctaau.vedaxml.com:8443/cta/sys2/business-enquiry-v3-2</faultactor>
<detail>
<l7:policyResult
status="Service Not Found. The request may have been sent to an invalid URL, or intended for an unsupported operation." xmlns:l7="http://www.layer7tech.com/ws/policy/fault"/>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
Take a look at the result status message
Service Not Found. The request may have been sent to an invalid URL, or intended for an unsupported operation.
Find documentation on the API and find the right service url or find out if you need to authenticate first before using the API.

Cakephp hanging after post request via httpsocket containing json data

at the moment I am fighting with a http post request within cakePHP.
I am using the code below to communicate with an external API that requires Authorization.
The problem is, as soon as I add the body with the JSON context, the whole application is hanging. It's loading forever in the browser, not coming back with any results. Have to stop and start Apache to come back to normal. Tested on different machines, same effect.
If I don't send the (JSON) body, I am getting obviously a 500 server error, but it's telling me that the authorization is working otherwise I would get an unauthorized.
If I do a "GET" request to the same API, it's working fine and coming back with a result.
The JSON syntax is clean, if I process the variable and the other information using an API tester it's working (https://apigee.com/console).
UPDATE: It is working if the request is valid. However, on the API tester it's giving me a "400 Bad Request". I would need to handle that within my application but in this case the situation described above is happening. Expectation would be that it's returning the error.
$options = array(
'body' => $json_order,
'header' => array(
'Authorization' =>'123456',
'Content-Type' => 'application/json; charset=utf-8',
),
);
$result=$HttpSocket->post('https://<address>',null,$options);
debug($HttpSocket->request);
same effect if I would do it the other way
$options = array(
'header' => array(
'Authorization' =>'123456',
'Content-Type' => 'application/json; charset=utf-8',
),
);
$result=$HttpSocket->post('https://<address>',$json_order,$options);
debug($HttpSocket->request);
Any help would be more than appreciated!
To clear that up: The problem was on the far end not responding correctly with an error code. =

Onedrive uploading fails with the Internal Server Error

I'm trying to create file on the OneDrive using REST API with PHP, but in the response I retrieve HTTP status code 500.
Code:
`
$url = $this->buildUrl(
'{folder_id}/files/{filename}?access_token={token}',
array(
'folder_id' => $folderId,
'filename' => $filename,
'token' => $this->getAccessToken(),
)
);
$response = wp_remote_request($url, array(
'body' => $content,
'method' => 'PUT',
));
`
Error message from the response body:
An error occurred while performing the action. Try again later.
What i'm doing wrong?
I just went through the same problem. It worked for me when I removed 'Content-type' line from request header.
If you are using PHP Curl to send request in wp_remote_request, you can remove 'Content-type' line from request header by calling something similar to this, before calling curl_exec:
curl_setopt($ci, CURLOPT_HTTPHEADER, array("Content-Type:"));
By adding the code above, the actual request header looks like this (note there is no 'Content-Type'):
PUT /v5.0/{folderId}/files/{filename}?access_token={accesstoken}
User-Agent: SOMEAGENT
Host: apis.live.net
Accept: */*
Expect: 100-continue
Content-Length: 29
FYI: I got a hint from here:
http://msdn.microsoft.com/en-us/library/dn631834.aspx
"For a PUT request, leave the Content-Type blank and put the contents of the file in the request body."
Hope it helps.

PHP Curl returning inconsistent data for XML feed

I'm working on a XML reader and am running into a odd issue with a few feeds. Using CURL or even file_get_contents the feeds load as binary data more often than real data. Whenever I load the feed in a browser it looks fine.
The specific feed is http://www.winnipegsun.com/home/rss.xml
The code I am using is
$string = file_get_contents("http://www.winnipegsun.com/home/rss.xml");
var_dump( $string );
The response is gzipped:
If you look at the HTTP headers:
Content-Encoding: gzip
Unzip it with PHP:
gzinflate(substr($string, 10));
http://php.net/manual/en/function.gzinflate.php
Hope that helps... cheers
You should be able to send an empty Accept-Encoding header to the server and then it should not send the content gzipped or return a Not Acceptable response:
$string = file_get_contents(
"http://www.winnipegsun.com/home/rss.xml",
FALSE,
stream_context_create(
array(
'http' => array(
'method' => "GET",
'headers' => 'Accept-Encoding:\r\n'
)
)
)
);
var_dump($string);
I am not sure the webserver is configured correctly though, because it wouldnt respond to that with the uncompressed feed, even when adding Cache Control headers telling to it not send a cached response. Oddly enough, just doing
$string = file_get_contents("http://www.winnipegsun.com/home/rss.xml?".time());
worked out of the box. And you can also send a POST request.

Categories