I have do post some information in cross domain . And i am achieving this thing by below code
<?php
function do_post_request($sendingurl, $data, $optional_headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'url' => $data
)
);
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($sendingurl, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $sendingurl, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $sendingurl, $php_errormsg");
}
return $response;
}
$response = do_post_request('http://mag16.playtrickz.com/testing.php','http%3A%2F%2Fwww.facebook.com');
echo $response;
But it is not working .
On successful POST Request : It will display its value
otherwise it will show : nodata found.
Why it is not working and how to make them work .
Here is how I would write your function:
function do_post_request($url, $data = NULL, $optional_headers = NULL) {
// Build a body string from an array
$content = (is_array($data)) ? http_build_query($data) : '';
// Parse the array of headers and strip values we will be setting
$headers = array();
if (is_array($optional_headers)) {
foreach ($optional_headers as $name => $value) {
if (!in_array(strtolower($name), array('content-type', 'content-length', 'connection'))) {
$headers[$name] = $value;
}
}
}
// Add our pre-set headers
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
$headers['Content-Length'] = strlen($content);
$headers['Connection'] = 'close';
// Build headers into a string
$header = array();
foreach ($headers as $name => $value) {
if (is_array($value)) {
foreach ($value as $multi) {
$header[] = "$name: $multi";
}
} else {
$header[] = "$name: $value";
}
}
$header = implode("\r\n", $header);
// Create the stream context
$params = array(
'http' => array(
'method' => 'POST',
'header' => $header,
'content' => $content
)
);
$ctx = stream_context_create($params);
// Make the request
$fp = #fopen($url, 'rb', FALSE, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === FALSE) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
This has been re-built so that the data to send to the server and the headers are passed in as associative arrays. So you would build an array that looks like you would want $_POST to look in the remote script, and pass that in. You can also pass an array of additional headers to send, but the function will automatically add a Content-Type, Content-Length and Connection header.
So your request would be called like this:
$data = array(
'url' => 'http://www.facebook.com/'
);
$response = do_post_request('http://mag16.playtrickz.com/testing.php', $data);
echo $response;
Related
I am using php file_get_contents and dom documment for login to 3rd party site (gmail). But when i run my code, it's displaying cookie problem text page: Turn cookies on or off, that's mean i am not enable cookie. But already i turn it on using this code $http_response_header, check below code then you will understand.
I don't want to use curl. Curl support cookies but file_get_contents not supporting cookies. I want to remote login using only php, so i don't used curl. I don't understand exactly where is my mistake and why displaying cookie problem after adding cookie function on code. After unsuccessful, i submitting this post on here for getting solution from genius.
Here Is My gmail.php Code:
<?php
class LoginGmail
{
public $request_cookies = '';
public $response_cookies = '';
public $content = '';
public function set_cookies_json($cookies)
{
$cookies_json = json_decode($cookies, true);
$cookies_array = array();
foreach ($cookies_json as $key => $value)
{
$cookies_array[] = $key .'='.$value;
}
$this->request_cookies = 'Cookie: ' . join('; ', $cookies_array) . "\r\n";
}
public function set_cookies_string($cookies)
{
$this->request_cookies = 'Cookie: ' . $cookies . "\r\n";
}
private function get_cookies($http_response_header)
{
$cookies_array = array();
foreach($http_response_header as $s)
{
if (preg_match('|^Set-Cookie:\s*([^=]+)=([^;]+);(.+)$|', $s, $parts))
{
$cookies_array[] = $parts[1] . '=' . $parts[2];
}
}
$this->response_cookies = 'Cookie: ' . join('; ', $cookies_array) . "\r\n";
}
public function get($url)
{
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Accept-language: en\r\n" .
"User-Agent: com.google.android.apps.maps/984200142 (Linux; U; Android 5.0; en_US; GT-I9500; Build/LRX21M; Cronet/66.0.3359.100)\r\n" .
$this->request_cookies
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies($http_response_header);
return $this->content;
}
public function post($url, $inputs)
{
$post_content = array();
foreach ($inputs as $key => $value)
{
$post_content[] = $key .'='.$value;
}
$opts = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"User-Agent: com.google.android.apps.maps/984200142 (Linux; U; Android 5.0; en_US; GT-I9500; Build/LRX21M; Cronet/66.0.3359.100)\r\n" .
$this->request_cookies,
'content' => join('&', $post_content),
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies($http_response_header);
return $this->content;
}
public function postPass($url, $inputs)
{
$post_content = array();
foreach ($inputs as $key => $value)
{
$post_content[] = $key .'='.$value;
}
$opts = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"User-Agent: com.google.android.apps.maps/984200142 (Linux; U; Android 5.0; en_US; GT-I9500; Build/LRX21M; Cronet/66.0.3359.100)\r\n" .
$this->request_cookies,
'content' => join('&', $post_content),
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies($http_response_header);
return $this->content;
}
}
?>
And Here Is My login.php Code:
<?php
require_once('gmail.php');
$connect = new LoginGmail();
$url = 'https://store.google.com/account';
$first = $connect->get($url);
$domd = #DOMDocument::loadHTML($first);
$xp = new DOMXPath($domd);
foreach($domd->getElementsByTagName("form")->item(0)->getElementsByTagName("input") as $get)
{
$inputs[$get->getAttribute("name")]=$get->getAttribute("value");
}
$inputs["Email"]="HERE_IS_GMAIL_ID";
$url = $xp->query("//form")->item(0)->getAttribute("action");
$second = $connect->post($url, $inputs);
$domd = #DOMDocument::loadHTML($second);
$xp = new DOMXPath($domd);
foreach($domd->getElementsByTagName("form")->item(0)->getElementsByTagName("input") as $get)
{
$inputs[$get->getAttribute("name")]=$get->getAttribute("value");
}
$inputs["Passwd"]="HERE_IS_GMAIL_PASSWORD";
$url = $xp->query("//form")->item(0)->getAttribute("action");
echo $connect->postPass($url, $inputs);
?>
NB: I hide my personal Email & Password on code. Sorry for not good english. Thanks
I believe that the way you are performing requests on google is not the correct form. Your code is not wrong, the way you try to authenticate yourself. Check out this documentation, maybe it will help.
I am using OpenTok API for the audio/video chat and now trying to record the audio/video chat conference with the same.
I have downloaded the API from this link
But the result always comes empty (check the result by var_dump($res); ) and response comes empty array.
Following is my function:
protected function request($method, $url, $opts = null) {
$url = $this->endpoint . $url;
if(($method == 'PUT' || $method == 'POST') && $opts) {
$bodyFormat = $opts->contentType();
$dataString = $opts->dataString();
}
$authString = "X-TB-PARTNER-AUTH: $this->apiKey:$this->apiSecret";
if (function_exists("file_get_contents")) {
$http = array(
'method' => $method
);
$headers = array($authString);
if($method == "POST" || $method == "PUT") {
$headers[1] = "Content-type: " . $bodyFormat;
$headers[2] = "Content-Length: " . strlen($dataString);
$http["content"] = $dataString;
}
$http["header"] = $headers;
$context_source = array ('http' =>$http);
$context = stream_context_create($context_source);
$res = file_get_contents( $url ,true, $context);
var_dump($res);
$statusarr = explode(" ", $http_response_header[0]);
$status = $statusarr[1];
$headers = array();
foreach($http_response_header as $header) {
if(strpos($header, "HTTP/") !== 0) {
$split = strpos($header, ":");
$key = strtolower(substr($header, 0, $split));
$val = trim(substr($header, $split + 1));
$headers[$key] = $val;
}
}
$response = (object)array(
"status" => $status
);
if(strtolower($headers["content-type"]) == "application/json") {
$response->body = json_decode($res);
} else {
$response->body = $res;
}
} else{
throw new OpenTokArchivingRequestException("Your PHP installion doesn't support file_get_contents. Please enable it so that you can make API calls.");
}
return $response;
}
When I print $context_source then I get the following array:
Array
(
[http] => Array
(
[method] => POST
[content] => {"action":"start","sessionId":"1_MX40NTM2MDgxMn4xMjcuMC4wLjF-MTQ0MzcxMDQ0NzU2NH4wWkZ3bkN1NDJaYlNFMFZFZmYwcGZ1a2F-UH4","name":"filename"}
[header] => Array
(
[0] => X-TB-PARTNER-AUTH: 45360812:cbbd8b29be4c75d5aab1945a71bf0cb3443e3939
[1] => Content-type: application/json
[2] => Content-Length: 136
)
)
)
Everything seems good. Can anyone tell me what I am doing wrong.
I use the file_get_contents() from server M to get the response from server X. The result was success but it take too long.
$url = "http://10.20.30.40";
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Connection: close\r\n'
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$result = json_decode($result);
$response = parse_http_response_header($http_response_header);
print_r($result);
print_r($response);
/////// below is just function to parse the response ///////
function parse_http_response_header(array $headers)
{
$responses = array();
$buffer = NULL;
foreach ($headers as $header)
{
if ('HTTP/' === substr($header, 0, 5))
{
// add buffer on top of all responses
if ($buffer) array_unshift($responses, $buffer);
$buffer = array();
list($version, $code, $phrase) = explode(' ', $header, 3) + array('', FALSE, '');
$buffer['status'] = array(
'line' => $header,
'version' => $version,
'code' => (int) $code,
'phrase' => $phrase
);
$fields = &$buffer['fields'];
$fields = array();
continue;
}
list($name, $value) = explode(': ', $header, 2) + array('', '');
// header-names are case insensitive
$name = strtoupper($name);
// values of multiple fields with the same name are normalized into
// a comma separated list (HTTP/1.0+1.1)
if (isset($fields[$name]))
{
$value = $fields[$name].','.$value;
}
$fields[$name] = $value;
}
unset($fields); // remove reference
array_unshift($responses, $buffer);
return $responses;
}
Is there any suggestion or function option to get the response (the content and the response code) faster?
(NOTE: I am not allowed to install cURL, so please gimme other option)
I watched a tutorial and did exactly what the guy did. I have the following code for my index.php. The guy in the tutorial recieves a result ( from $result variable ) but i get nothing.
var_dump on $result:
string(0) ""
Where is the problem?
<?php
class Paypal_IPN
{
public function __construct($mode)
{
if ($mode == 'live')
$this->_url = 'https://www.paypal.com/cgi-bin/webscr';
else
$this->_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
}
public function run()
{
$postFields = "cdm=_notify-validate";
foreach ((array)$_POST as $key => $value)
{
$postFields .= "&$key=".urlencode($value);
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $this->_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields
));
$result = curl_exec($ch);
curl_close($ch);
$fh = fopen('result.txt', 'w');
fwrite($fh, $result . " -- \n" . $postFields);
fclose($fh);
var_dump( $result );
}
}
$paypal = new Paypal_IPN('sandbox');
$paypal->run();
I should have recieved INVALID or VALID as result...
You have a typo in the string
$postFields = "cdm=_notify-validate";
Should be
$postFields = "cmd=_notify-validate";
I'm trying to develop a full PHP web browser that can handle cookies. I've created the following class:
<?php
class Browser
{
private $cookies = '';
private $response_cookies = '';
private $content = '';
/**
* Cookie manager
* #Description : To set or get cookies as Array or String
*/
public function set_cookies_json($cookies)
{
$cookies_json = json_decode($cookies, true);
$cookies_array = array();
foreach ($cookies_json as $key => $value)
{
$cookies_array[] = $key .'='.$value;
}
$this->cookies = 'Cookie: ' . $cookies_array.join('; ') . "\r\n";
}
public function set_cookies_string($cookies)
{
$this->cookies = 'Cookie: ' . $cookies . "\r\n";
}
private function get_cookies()
{
global $http_response_header;
$cookies_array = array();
foreach($http_response_header as $s)
{
if (preg_match('|^Set-Cookie:\s*([^=]+)=([^;]+);(.+)$|', $s, $parts))
{
$cookies_array[] = $parts[1] . '=' . $parts[2];
}
}
$this->cookies = 'Cookie: ' . $cookies_array.join('; ') . "\r\n";
}
/**
* GET and POST request
* Send a GET or a POST request to a remote URL
*/
public function get($url)
{
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Accept-language: en\r\n" .
$this->cookies
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies();
return $this->content;
}
public function post($url, $post_data)
{
$post_content = array();
foreach ($post_data as $key => $value)
{
$post_content[] = $key .'='.$value;
}
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
$this->cookies,
'content' => $post_content.join('&'),
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies();
return $this->content;
}
}
Basically, it can send a GET request and 'should' retrieve the cookies.
I've made a very simple test script:
<?php
require('browser.class.php');
$browser = new Browser();
$browser->get('http://google.com');
print_r($browser->response_cookies);
But it fails on line 32 as $http_response_header looks to be null. Isn't it supposed to contain the header of my response ? I've read that page but it looks to work well for this guy : get cookie with file_get_contents in PHP
I know I could use cUrl to handle this but I'd really like to use a rough PHP code.
Did I make something wrong ?
Thanks for your precious help.
Edit:
Solution is:
<?php
class Browser
{
public $request_cookies = '';
public $response_cookies = '';
public $content = '';
/**
* Cookie manager
* #Description : To set or get cookies as Array or String
*/
public function set_cookies_json($cookies)
{
$cookies_json = json_decode($cookies, true);
$cookies_array = array();
foreach ($cookies_json as $key => $value)
{
$cookies_array[] = $key .'='.$value;
}
$this->request_cookies = 'Cookie: ' . join('; ', $cookies_array) . "\r\n";
}
public function set_cookies_string($cookies)
{
$this->request_cookies = 'Cookie: ' . $cookies . "\r\n";
}
private function get_cookies($http_response_header)
{
$cookies_array = array();
foreach($http_response_header as $s)
{
if (preg_match('|^Set-Cookie:\s*([^=]+)=([^;]+);(.+)$|', $s, $parts))
{
$cookies_array[] = $parts[1] . '=' . $parts[2];
}
}
$this->response_cookies = 'Cookie: ' . join('; ', $cookies_array) . "\r\n";
}
/**
* GET and POST request
* Send a GET or a POST request to a remote URL
*/
public function get($url)
{
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Accept-language: en\r\n" .
$this->request_cookies
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies($http_response_header);
return $this->content;
}
public function post($url, $post_data)
{
$post_content = array();
foreach ($post_data as $key => $value)
{
$post_content[] = $key .'='.$value;
}
$opts = array(
'http' => array(
'method' => 'GET',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
$this->request_cookies,
'content' => join('&', $post_content),
)
);
$context = stream_context_create($opts);
$this->content = file_get_contents($url, false, $context);
$this->get_cookies($http_response_header);
return $this->content;
}
}
According to php.net:
$http_response_header will be created in the local scope.
Because of this $http_response_header is available only in the scope of get().
You can pass it like $this->get_cookies($http_response_header); or create a property to store it.