POST xml WITHOUT using CURL - php

I need to POST xml data without CuRL.
there are a LOT of snippets, but nothing seems to work.
The latest attempt:
function salesOrder($xml, $url)
{
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/xml\r\n",
'content' => $xml,
'timeout' => 5,
),
));
$ret = file_get_contents($url, false, $context);
return false !== $ret;
}
returns nothing, blank page.
I have tried http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
The problem is I dont really understand it and i can not seem to find a good tutorial that covers this problem. Can anyone point me in the right direction?

You can use this to achieve that
$xml = "<xml><name>hello</name></xml>" ;
$opts = array (
'http' => array (
'method' => "POST",
'content' => $xml,
'timeout' => 5,
'header' => "Content-Type: text/xml; charset=utf-8"
)
);
$context = stream_context_create ( $opts );
$fp = fopen ( 'http://example.com/b.php', 'r', false, $context );
fpassthru ( $fp );
fclose ( $fp );
http://example.com/b.php
file_put_contents("php://output", file_get_contents("php://input"));

Related

PHP sends GET instead of POST

I have to post some data, but the same adress have some GET and POST functions. My PHP is sending a GET instead of a POST.
$apiURL = 'https://myAPI.com.br/api';
$data = http_build_query(array('postdata' => 10));
$uriRequest = $apiURL.'/main';
$options = array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
'https' => array(
'header' => 'Content-type: application/x-www-form-urlencoded',
'method' => 'POST',
'content' => $data
),
);
$context = stream_context_create($options);
$result = file_get_contents($uriRequest, false, $context);
if ($result === FALSE) {
return var_dump($result);
}
return var_dump($result);
I know the ssl part it isnt safe, but it is just for prototyping purpose.
I cant get PHP to POST intestead of GET on the adress 'https://myAPI.com.br/api/main'.
Judging from http://php.net/manual/de/function.stream-context-create.php#74795 the correct way to create a stream context for a https secured page is:
<?php
$context_options = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
As you can see we are using 'http' => array... instead of https.

HTTP request failed Length required

I humbly come before the people for some much needed assistance with this..
I am using (or trying to use) the skyscanner API - http://partners.api.skyscanner.net/apiservices/pricing/v1.0 as documented here. But I am coming up against this error:
HTTP request failed! HTTP/1.1 411 Length Required
PHP attempt 1
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers);
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
My server doesn't support cURL so I'm in need of a solution without it. I'm using localhost with WAMP but I have also tried a live version which comes up with the same error and seemingly same problem. I have tried almost every combination of variables in order to correct the error with a discouraging amount of success (none). This is one such variation including the form contents that I am attempting to send.
PHP attempt 2
function getSkyScanner() {
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0?apiKey=MY-API-KEY';
$params = array( 'country' => 'GB',
'currency' => 'GBP',
'locale' => 'en-GB',
'originplace' => 'LHR',
'destinationplace' => 'EDI',
'outbounddate' => '2016-10-10',
'adults' => '1'
);
$query = http_build_query($params);
$headers = array( 'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml');
$contextData = array (
'method' => 'POST',
'header' => $headers,
'content' => $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo 'error'; }
var_dump($result);
}
This throws out:
Content-type not specified
Followed by:
HTTP/1.1 400 Bad Request
If you can help I would appreciate some insight right about now.
Many thanks!
You create headers in a wrong way - instead of an array, headers should be passed as a string.
$headers = "Content-Type: application/x-www-form-urlencoded\r\n" .
"Accept: application/xml\r\n";
You can use below snippet to create the correct request:
function prepare_headers($headers) {
return
implode('', array_map(function($key, $value) {
return "$key: $value\r\n";
}, array_keys($headers), array_values($headers))
);
}
function http_post($url, $data, $ignore_errors = false) {
$data_query = http_build_query($data);
$data_len = strlen($data_query);
$headers = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept' => 'application/xml',
'Content-Length' => $data_len
);
$response =
file_get_contents($url, false, stream_context_create(
array('http' => array(
'method' => 'POST',
'header' => prepare_headers($headers),
'content' => $data_query,
'ignore_errors' => $ignore_errors
)
)
));
return (false === $response) ? false :
array(
'headers' => $http_response_header,
'body' => $response
);
}
Example usage of http_post method:
$result = http_post('http://business.skyscanner.net/apiservices/pricing/v1.0', array(
'apiKey' => 'YOUR_API_KEY',
'country' => 'UK',
'currency' => 'GBP',
'locale' => 'en-GB',
'locationSchema' => 'iata',
'originplace' => 'EDI',
'destinationplace' => 'LHR',
'outbounddate' => '2016-10-10',
'adults' => '1'
), false);
Parameter $ignore_errors in http_post method is reponsible for fetching the content even on failure status codes (400, 500, etc.). If you receive Bad request, set ignore_errors = true -> you'll receive full response from server.

Twitter API works only with one method

$key = 'fd2fdfsdfsdfdsf';
$secret = 'fdsfdsfdsfdsfdsfsdf';
$basic_credentials = base64_encode($key.':'.$secret);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Authorization: Basic '.$basic_credentials."\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => 'grant_type=client_credentials'
)
);
$context = stream_context_create($opts);
$pre_token = file_get_contents('https://api.twitter.com/oauth2/token', false, $context);
$token = json_decode($pre_token, true);
if (isset($token["token_type"]) && $token["token_type"] == "bearer")
{
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Authorization: Bearer '.$token["access_token"]
)
);
$context = stream_context_create($opts);
$data = file_get_contents('https://api.twitter.com/1.1/search/users.json?q=twitter', false, $context);
var_dump($data); die();
The code above returns false. I have no idea why. When I change the url into:
https://api.twitter.com/1.1/statuses/user_timeline.json?count=200&user_id=43243243
It works perfectly and returns the whole JSON.
Why is that so? I can't get it to work with any other API methods other than this one. The key and secret are the same in each situation. Nothing should be changed.

PHP - Content-type not specified assuming application/x-www-form-urlencoded

For 2 days I'm having trouble with my PHP script on my server. I've changed nothing and suddenly it didn't work anymore.
Here is the code:
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n",
'method' => "POST",
'content' => $query,
),
);
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n",'method' => 'POST',
'content' => http_build_query($data),));
$contexts = stream_context_create($opts);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $contexts, -1, 40000);
I'm getting these error messages:
Notice: file_get_contents(): Content-type not specified assuming
application/x-www-form-urlencoded in
Warning: file_get_contents(https://mobile.dsbcontrol.de): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server
Error in
But when I try the script locally it works perfectly.
You are passing $contexts to file_get_contents() and that only contains the User-Agent header in the $opts array. All other headers and options are in the $options array which you add in to $context but aren't using. Try:
$query = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => "POST",
'content' => $query,
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context, -1, 40000);
While the existing answers did not work for me, I managed to solve the problem like this:
The PHP Manual says params must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($postdata)
);
$packet['method'] = "POST";
$packet['header'] = implode("\r\n", $header);
$packet['content'] = $postdata;
$transmit_data = array('http' => $packet);
$context = stream_context_create($transmit_data);
i'm using this
$url = '';
$result = json_decode(file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => http_build_query($dataQuery)
)
))), true);

Post data & show source code

I have question, is it possible to first post data to a site and then get the source code of the site I was posting the data to?
I tried with this:
$html = file_get_contents('http://test.com/test.php?test=test');
But the ?test=test is $_GET....
So yeah, I hope someone can help me! :) Thanks in advance (Sorry for bad english!).
You can use 3rd parameter of this function: context
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array(
'http' => array(
'method' => "POST",
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($postdata)."\r\n",
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
// edit -little bug should be:
$opts = array(
'http' => array(
'method' => "POST",
'header' => "Connection: close\r\n".
"Content-type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($postdata)."\r\n",
'content' => $postdata
)
);
You can not get the source, but you can get the page/output as it is provided by the server. As you mention file_get_contents(), you can use it to send a POST-request, but it would look something like this.
// Create map with request parameters
$params = array ('surname' => 'Filip', 'lastname' => 'Czaja');
// Build Http query using params
$query = http_build_query ($params);
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
'http://www.sample-post-page.com', // page url
false,
$context);
// Server response is now stored in $result variable so you can process it
Example from: http://fczaja.blogspot.se/2011/07/php-how-to-send-post-request-with.html

Categories