How to add values to HTTP response header using php - php

So far I manage to get HTTP response header from this
$ch = curl_init();<br/>
$url="http://localhost/PHP_Projects/Test/response.php";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$headers = get_headers_from_curl_response($response);
foreach($headers as $x => $x_value){<br/>
print $x.": ".$x_value;<br/>
}
function get_headers_from_curl_response($response)
{<br/>
$headers = array();
$header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
foreach (explode("\r\n", $header_text) as $i => $line)
if ($i === 0)
$headers['http_code'] = $line;
else
{
list ($key, $value) = explode(': ', $line);
$headers[$key] = $value;
}
return $headers;
}
The out put from this is like
HTTP/1.1 200 OK
Date: Thu, 07 May 2015 03:26:26 GMT
Server: Apache/2.4.12 (Win32) OpenSSL/1.0.1l PHP/5.6.8
X-Powered-By: PHP/5.6.8
Content-Length: 128
Content-Type: text/html; charset=UTF-8
but I want to add some more to this like
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Path=/application_uri
Freeflow: FC
charge: Y
amount: 100
Expires: -1
Pragma: no-cache
Cache-Control: max-age=0
Content-Type: UTF-8
Content-Length: 20

$headers = array( 'Path: application_uri',
'Freeflow: FC',
'charge: Y',
'amount: 100',
);
curl_setopt ($ch, CURLOPT_HTTPHEADER,$headers);

Related

PHP curl to display output for URL like 'HTTP/1.1 200 OK'

I am trying to get the response/status code including the header for multiple URL's. My first try I was successful in getting the status code i.e. 200 or 301 or 302. But I want the output to be like HTTP/1.1 200 OK or HTTP/1.1 302 Found etc.
Below is my code in which I get just the response code i.e. 200 or 301.
<?php
$line = "https://www.pnc.com";
$ch = curl_init($line);
curl_setopt($ch, CURLOPT_URL, $line);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER,true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$out = curl_exec($ch);
$ret = true;
if ($out !== false) {
$statuscode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
echo "Response Code:" .$statuscode. "\r";
}
curl_close($ch);
?>
Actual Ouput
Response Code:HTTP/1.1 200 OK
ETag: "846caf551746b12e876c0bad5a50830d:1475788950"
Last-Modified: Thu, 06 Oct 2016 21:22:30 GMT
Accept-Ranges: bytes
Content-Length: 17609
Content-Type: text/html
Expires: Fri, 21 Sep 2018 15:35:01 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Fri, 21 Sep 2018 15:35:01 GMT
Connection: keep-alive
Expected Output
HTTP/1.1 200 OK.
Can someone help me with this?
This can be done using strtok
Example:
$statuscode = strtok( $statuscode, "\n" );
-or-
Using explode is pretty standard:
$statuscode = explode( "\n", $statuscode )[0];
There are definitely other methods as well
However probably the cleanest way might be to use cURL itself:
$response = curl_getinfo( $ch, CURLINFO_HTTP_CODE );

i'm able to search google using cURL but ajax is returning null

i'm unable to return $data when i do echo $data the page will load(see arrow ---> getPage.php).
but i want return $data to page1.php i will get {"html":null,"url":"floret media"} you can see here "html":null why it is happening? when i replace return $data to echo $data in response tab i see this(with WHOLE PAGE)
> HTTP/1.1 200 OK Date: Tue, 27 Dec 2016 09:24:01 GMT Expires: -1
> Cache-Control: private, max-age=0 Content-Type: text/html;
> charset=ISO-8859-1 P3P: CP="This is not a P3P policy! See
> https://www.google.com/support/accounts/answer/151657?hl=en for more
> info." Server: gws X-XSS-Protection: 1; mode=block X-Frame-Options:
> SAMEORIGIN Set-Cookie:
> NID=93=XFlY_DE0XhLLdLDiTeHZi44J_z61nRxwTBInVkZlRVA3MsnuhB3iAqcR12lMs44dRI3dMWriif3USxysmiXDqm317uTYg08TzgYzFZa-VVgII_KE5fVsxueZcAmzlMCrOCw1LCSPCuIKfVI;
> expires=Wed, 28-Jun-2017 09:24:01 GMT; path=/; domain=.google.com;
> HttpOnly Accept-Ranges: none Vary: Accept-Encoding Transfer-Encoding:
> chunked
<!doctype html><html itemscope="" ><!--WHOLE PAGE --></html>
is browser is not allowing to return response to calling ajax?
page1.php
var url = 'floret media';
$.ajax({
url:"getPage.php",
type:"POST",
dataType:"json",
data:{url:url},
success: function(data){
console.log(data);
}
});
getPage.php
function curl_google($keyword){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,
'http://www.google.com/search?hl=en&q='.urlencode($keyword).'&btnG=Google+Search&meta=');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILETIME, true);
$data = curl_exec($ch);
//ob_flush();//Flush the data here
if ($data === FALSE) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
------> return $data; <---- // when i change it to echo $data it will work, but return $data; will not work i will get json response as {"html":null,"url":"floret media"}
}
$url = $_POST["url"];
$html = curl_google($url);
$response = json_encode(array("html"=>$html,"url"=>$url));
echo $response;
Encode the html response with utf8_encode. Replace the following statement
$response = json_encode(array("html"=>$html,"url"=>$url));
with
$response = json_encode(array("html" => utf8_encode($html), "url" => $url));
Since the response returned from Google is having some non-utf8 characters, which result to null while performing json_encode.

header('Content-Disposition: attachment') not triggering when using with curl

I am exporting some invoices in json in my XmlController.php and converting them in xml in my xml_export.php
In my XmlController.php:
private function exportBills() {
$bill_ids = $this->_getParam('bill_ids');
$bill_model = new Model_Bills();
$bills = $bill_model->findByIds($bill_ids);
$data = array('bills' => array());
$extract = array();
foreach($bills as $bill) {
$data['bills'][] = $bill->getJsonView();
$extract[$bill->bill_reference_number] = $bill;
}
try {
$response = $this->post('xml_export.php', $data);
$this->getResponse()->setHttpResponseCode(200);
return;
} catch (Exception $e) {
$this->view->error = 'Unknown Error';
$this->view->description = $e->getMessage();
$this->getResponse()->setHttpResponseCode(500);
return;
}
}
private function post($url, $data) {
$data = json_encode($data);
$headers = array_merge(
array(
'Accept: application/xml',
'Content-Length: ' . strlen($data),
'Origin: ' . get_base_url()));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$xml = curl_exec($curl);
curl_close($curl);
if(false === $xml) {
throw new Exception('cURL failed! URL was: ' . $url);
}
}
And in my xml_export.php:
require_once('../library/functions.php');
$json = file_get_contents('php://input');
$date = date('Y-m-d H:i:s');
try{
$input = json_decode($json, true);
$response = array();
$xml_string = null;
$xml_concat = null;
if(implode('', array_keys($input)) === 'invoices') {
foreach ($input['invoices'] as $invoice) {
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
array_to_xml($invoice, $xml_data);
$xml = $xml_data->asXML();
$xml = preg_replace('~<(\d)~', '<number$1', $xml);
$xml = preg_replace('~<\/(\d)~', '</number$1', $xml);
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml);
$xml_string = $domxml->saveXML();
$xml_concat .= $xml_string;
}
}elseif(implode('', array_keys($input)) === 'bills') {
foreach ($input['bills'] as $bill) {
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
array_to_xml($bill, $xml_data);
$xml = $xml_data->asXML();
$xml = preg_replace('~<(\d)~', '<number$1', $xml);
$xml = preg_replace('~<\/(\d)~', '</number$1', $xml);
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml);
$xml_string = $domxml->saveXML();
$xml_concat .= $xml_string;
}
}
file_put_contents('/tmp/report.xml', print_r(htmlspecialchars($xml_concat), true));
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="report.xml"');
echo $xml_concat;
readfile('/tmp/report.xml');
exit;
}catch(OAuthException $e){
die('Unable to export. Please contact support for assistance');
}
My $xml_concat definitely has output and my /tmp/report.xml also exists and has output but the download was not triggered.
Below is my reponse header:
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre- check=0
Content-Type: application/json
Date: Sat, 26 Mar 2016 14:47:22 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: nginx
Vary: Accept
X-Powered-By: PHP/5.6.16-1+deb.sury.org~trusty+1
Content-Length: 0
Connection: keep-alive
and my request header:
POST /v1/xml HTTP/1.1
Connection: keep-alive
Content-Length: 81
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.108 Safari/537.36
Content-Type: application/json
Accept: application/json
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
I am not exactly sure why it is in application/json when I specified in application/xml in my controller and the headers did not pick up the content-disposition.

PHP CURL fetch header from URL and set it to variable

I have a piece of code that trying to call Cloudstack REST API :
function file_get_header($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
$datas = curl_exec($ch);
curl_close($ch);
return $datas;
}
$url = "http://10.151.32.51:8080/client/api?" . $command . "&" . $signature . "&" . $response;
echo $test = file_get_header($url);
And the output is like this :
HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT
What I am trying to do is how to print JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 only and assign it into variable? Thankss,
Here's a method that will parse all your headers into a nice associative array, so you can get any header value by requesting $dictionary['header-name']
$url = 'http://www.google.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$datas = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($datas, 0, $header_size);
curl_close($ch);
echo ($header);
$arr = explode("\r\n", $header);
$dictionary = array();
foreach ($arr as $a) {
echo "$a\n\n";
$key_value = explode(":", $a, 2);
if (count($key_value) == 2) {
list($key, $value) = $key_value;
$dictionary[$key] = $value;
}
}
//uncomment the following line to see $dictionary is an associative-array of Header keys to Header values
//var_dump($dictionary);
Simple, just match the part of the string you want with preg_match:
<?php
$text = "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT";
preg_match("/JSESSIONID=\\w{32}/u", $text, $match);
echo $result = implode($match);
?>

Using cURL to findout where website redirects?

I'm trying to get server redirect url. I have tried
function http_head_curl($url,$timeout=10)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // in seconds
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
if ($res === false) {
throw new RuntimeException("cURL exception: ".curl_errno($ch).": ".curl_error($ch));
}
return trim($res);
}
echo http_head_curl("http://www.site.com",$timeout=10);
Result is;
HTTP/1.1 301 Moved Permanently Date: Sun, 12 May 2013 23:34:22 GMT
Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.23
Set-Cookie: PHPSESSID=0d4b28dd02bd3d8413c92f71253e8b31; path=/;
HttpOnly X-Pingback: http://site.com/xmlrpc.php Content-Type:
text/html; charset=UTF-8 Location: http://site.com/ HTTP/1.1 200 OK
Date: Sun, 12 May 2013 23:34:23 GMT Server: LiteSpeed Connection:
close X-Powered-By: PHP/5.3.23 Set-Cookie:
PHPSESSID=630ed27f107c07d25ee6dbfcb02e8dec; path=/; HttpOnly
X-Pingback: http://site.com/xmlrpc.php Content-Type: text/html;
charset=UTF-8
It shows almost all header information, but not showing where it redirects. How do I get the redirected page url ?
It's the Location header.
$headers = array();
$lines = explode("\n", http_head_curl('http://www.site.com', $timeout = 10));
list($protocol, $statusCode, $statusMsg) = explode(' ', array_shift($lines), 3);
foreach($lines as $line){
$line = explode(':', $line, 2);
$headers[trim($line[0])] = isset($line[1]) ? trim($line[1]) : '';
}
// 3xx = redirect
if(floor($statusCode / 100) === 3)
print $headers['Location'];
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$response_header = substr($response, 0, $info['header_size']);
$response_header = parseHeaders($response_header, 'Status');
$content = substr(response, $info['header_size']);
$url_redirect = (isset($response_header['Location'])) ? $response_header['Location'] : null;
var_dump($url_redirect);
/*
* or you can use http://php.net/http-parse-headers,
* but then need to install http://php.net/manual/en/book.http.php
*/
function parseHeaders($headers, $request_line)
{
$results = array();
$lines = array_filter(explode("\r\n", $headers));
foreach ($lines as $line) {
$name_value = explode(':', $line, 2);
if (isset($name_value[1])) {
$name = $name_value[0];
$value = $name_value[1];
} else {
$name = $request_line;
$value = $name_value[0];
}
$results[$name] = trim($value);
}
return $results;
}
After your CURL request is done, use curl_getinfo with the CURLINFO_EFFECTIVE_URL option. Done.
Compared to the other (complicated) answers, this will provide you the full URL that your request "ended up on".

Categories