how to add a custom request header in php - php

i want to send a custom header to a domain.
i tried like the following :
header("myheader: value1");
//i want to redirect above header to a samplesite now
header('Location: http://localhost/samplesite', FALSE);
exit;
And now in samplesite, I could not get myheader.
How to achieve it, please help me.

You can simply send a custom header with file_get_contents() and give it a context.
It would look something like this:
$data = http_build_query(array("username" => $uid));
$opts = array (
'http' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
$context = stream_context_create($opts);
$returnedData= file_get_contents("example.com", false, $context);
Remember that the remote host needs to allow this kind of requests or you will get an error
The header() function you tried to use in your example will just change the header send back from your server so header('Location: http://localhost/samplesite', FALSE); would just be a simple redirect to that site.

If you already have request and you need to add request header, try set function
$request->headers->set('key', $value);

Related

Redirect in php server side after http request

I am very new to php so this question might be trivial.
I am trying to understand if it is possible to redirect the browser from php server side to the page returned by HTTP request.
I have a HTTP Post request looking like so:
$postdata = http_build_query(
array(
"someData" => "data" ,
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'content' => $postdata,
'header' =>
"Cookie: someCookie" .
'content-type: application/x-www-form-urlencoded; charset=utf-8'
)
);
$context = stream_context_create($opts);
$result = fopen('myWebsiteUrl', 'r', false, $context);
var_dump(stream_get_contents($result));
In the post I am being redirected to a different page with Get.
I am trying to force the browser to move to the 'redirected' page. With the above code I am getting back the html of the redirected page but what I'm after is an actual redirect.
The option of retrieving the redirect URL and doing the redirect myself in PHP doesn't work because the Get request has to happen within the same session as the Post.
header('Location: whereveryouwantogo.php?get=123456');
does a redirect for you with a GET-parameter attached. I'm not sure if I really got your question right, but I'm pretty sure you could do what you want/need with the header-command.

file_get_contents return all php code

I want to send a POST request to some file when I load index.php. I use this code:
$query = http_build_query(array('ajax' => 'gwonline', 'session' => $current_session));
$contextData = array (
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
$context = stream_context_create (array ( 'http' => $contextData ));
$result = file_get_contents(PATH::Includes . 'ajax.php', false, $context);
$result_decoded = json_decode($result, true);
echo '<div id="gwonline">' . ($result_decoded['isonlinestr'] ?: '<span class="fa fa-circle" style="color:orange"></span> Unavailable') . '</div>';
The problem is, $result ends with getting the PHP code instead of whatever the file actually printed. How can I fix it without changing the site to http://... as it's not an option for me at the moment.
Use include with output buffering. file_get_contents is reading the file from the filesystem, it isn't going to use PHP to analyze it. The only reason it works when you use http:// is because then the web server is serving the file, not the filesystem.
ob_start();
include "ajax.php";
$result = ob_get_clean();

AuthKey in header

So my client needs a REST API using PHP that provides output as per the conditions on the URL parameters
So now there are three URL's basically which is currently needed and they are done.
so they are
localhost/newapi/client/<AuthKey> - for authorizing
localhost/newapi/client/<clientid>/categories/ - to get all the categories
localhost/newapi/client/<clientid>/categories/<categoryid> - to get all items in a category
used .htaccess for fancy URL
So now he requested that AuthKey need to be added to HTTP header not the URL. So the AuthKey must be passed as header and the rest as URL parameters
So my question is how this can be done. and how to retrieve the AuthKey from the request?
Any tutorials or comments regarding this question is welcome
you can tell the client when he request your api he add a header as below:
AuthKey: your-api-auth-key
or
Token: your-api-token
and then in your php code make
$headers = getallheaders();
$token = $headers['Token'] or ['AuthKey'];
then you check if the key in database and then process your code
Note:
your client can add Header with PHP cURL
curl_setopt($curl-handle, CURLOPT_HEADER, array(
'Token' => 'client-auth-token', //or
'AuthKey' => 'client-auth-token'
));
you can use this code to connect with rest in php
$url = 'localhost/newapi/client/';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n"."Authorization: Basic ".<authkey>."\r\n",
'content' => $data,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context, -1, 40000);
return $result;

Can't send data in post request via file_get_contents

Need to request some code two times in my app. Fist request url as ajax call, and also need to request this url in controller (something like hmvc). I know how to develop this via curl but I found another kind of idea how to implement this, just use function file_get_contents with before prepared params. This my code:
// Setup limit per page
$args['offset'] = $offset;
$args['limit'] = $this->_perpage;
// --
// Convert search arguments to the uri format
$data = http_build_query($args);
// Define request params
$options = array(
'http' => array(
'header' => 'Content-type: application/json' . PHP_EOL .
'Content-Length: ' . strlen($data) . PHP_EOL,
'method' => 'POST',
'content' => $data,
),
);
$context = stream_context_create($options);
$result = file_get_contents(
'http://'.$_SERVER['HTTP_HOST'].'/search/items', FALSE, $context
);
Request method was detected ok in requested uri, but params wasn't passed. Why this is not pass arguments to request? Where is bug in my code? Many thanks for any answers.
http_build_query builds application/x-www-form-urlencoded content. (not application/json)
There is a full example:
How to post data in PHP using file_get_contents?
Content type should be application/x-www-form-urlencoded. If you want to stay with application/json, try to get posted data using file_get_contents("php://input").

php http request

$post_data = array(
'url' => $all[2],
'op' => 'sv',
'sid' => 1
);
// Send a request to example.com
$result = post_request('http://www.yahoo.com', $post_data);
function PostRequest($url) {
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Content-type: application/x-www-form-urlencoded\r\n"."Accept-language: en\r\n" .
"Cookie: member_id=8593099\r\n" .
"Cookie: pass_hash=fad917fe75e1059f85fc6d9bb6f7a19f\r\n".
"Cookie: session_id=279fe56fd87e5371dc7e1c9f66c27522"
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
return $result;
}
I am able to send the request, but my action needs login to be performed.
Even once I'm logged in, it classifies me as not logged in.
I'm using localhost to send out the request. Is that because of the different domain?
I already copied the login cookies for my localhost, but it is still not working.
Any ideas?
What I tried to do is send http request with php.
My request has sent out, but my destination cannot detect cookies, and claim I am not login.
I'm not too sure what you're trying to accomplish, as the code you've posted isn't quite clear. post_request() isn't a native PHP-function, so you'd have to give us a sample of it for us to be able to help you further.
I would however recommend that you've check that you've put session_start(); way up top in your PHP-files - it ensures that you're able to access the session/cookie.

Categories