I have problem with cross domain request. I want to send get request via ajax from 'www.second-domain.com' to 'www.first-domain.com/path/to/plugin' and return html code (plugin view).
I install 'barryvdh/laravel-cors' from github in Laravel 4.2 on 'www.first-domain.com'.
plugin.blade.php
<div id="bookingPlugin">
<div class="container">
<div class="bookingPlugin">
<div class="bookingPluginHeader">
<div class="bookingPluginTxtCenter">REZERWACJA ON-LINE</div>
</div>
<div class="bookingPluginContent bookingPluginNoPadding">
#foreach ($categories as $category)
<div class="bookingPluginButtonContainer">
<button id="{{{ $category->CategoryId }}}" class="bookingPluginTxtCenter">{{{ $category->CategoryName }}}</button>
</div>
#endforeach
</div>
</div>
</div>
</div>
<div id="bookingWindow"></div>
<script>
$.getScript('http://plugins.first-domain.com/bookingWindow.js');
$.getScript('http://first-domain.com/packages/jquery-ui/jquery-ui.min.js');
$("head").append(
"<link href=\"http://first-domain.com/packages/jquery-ui/jquery-ui.min.css\" rel=\"stylesheet\" media=\"all\" type=\"text/css\">"
);
$("#bookingPlugin button").click(function(){
openBookingWindow("{{ $hotelId }}", this.id);
});
</script>
On 'www.second-domain.com' I added the following line to the code. If this line I added to 'www.first-domain.com' it is working.
<script type="text/javascript" src="http://plugins.first-domain.com/book.js"></script>
book.js
$("head").append(
"<style>"+
"#bookingPlugin{position:absolute;top:200px;width:100%;z-index:999;}"+
"#bookingPlugin button{font-size:100%;margin:0;vertical-align:baseline;line-height:normal;text-transform:uppercase;background:#2670b5;}"+
"#bookingPlugin button{width:100%;cursor:pointer;color:#fff;-webkit-appearance:button;border:1px solid #fff;outline:0;padding:5px;}"+
"#bookingPlugin button:hover{background:#275DA2}"+
".bookingPlugin{width:250px;background-color:#fff;color:#444;border:1px solid #fff;padding:5px}"+
".bookingPluginNoPadding{padding:0;}"+
".bookingPluginHeader{width:100%;font-weight:bold;border-bottom:1px dotted #444;margin:0 0 5px 0;padding:5px;}"+
".bookingPluginTxtCenter{text-align:center;}"+
".bookingPluginContent{width:100%;}"+
".bookingPluginButtonContainer{width:100%;}"+
"</style>"
);
$.ajax({
//send get ajax request to laravel
type:'get',
//call to route
url:'http://www.first-domain.com/path/to/plugin',
//return data type as html
dataType:'html'
}).done(function(data){
//insert returned data into body element
$("body").append(data);
}).fail(function(jqXHR, ajaxOptions, thrownError){
alert(thrownError);
});
barryvdh/laravel-cors/config.php
'defaults' => array(
'supportsCredentials' => false,
'allowedOrigins' => array(),
'allowedHeaders' => array(),
'allowedMethods' => array(),
'exposedHeaders' => array(),
'maxAge' => 0,
'hosts' => array(),
),
'paths' => array(
'^/' => array(
'allowedOrigins' => array('*'),
'allowedHeaders' => array('Content-Type'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
'maxAge' => 3600,
)
)
EDIT:
Request headers (www.second-domain.com -> www.first-domain.com)
Accept text/html, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language pl,en-US;q=0.7,en;q=0.3
DNT 1
Host first-domain.com
Origin http://www.first-domain.com
Referer http://www.first-domain.com/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Response headers (www.second-domain.com -> www.first-domain.com)
Cache-Control no-cache
Connection keep-alive
Content-Length 0
Content-Type text/html; charset=UTF-8
Date Mon, 27 Oct 2014 07:49:01 GMT
Server nginx
Set-Cookie laravel_session=eyJpdiI6Imtva3...; expires=Mon, 27-Oct-2014 09:49:01 GMT; Max-Age=7200; path=/; httponly
Vary Origin
X-Powered-By PHP/5.5.17
access-control-allow-origin http://www.first-domain.com
Request headers (www.first-domain.com -> www.first-domain.com)
Accept text/html, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language pl,en-US;q=0.7,en;q=0.3
Cookie laravel_session=eyJpdiI6IjB1V...; _ga=GA1.2.1119242176.1414394349; _gat=1
DNT 1
Host first-domain.com
Referer http://first-domain.com/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
X-Requested-With XMLHttpRequest
Response headers (www.first-domain.com -> www.first-domain.com)
Cache-Control no-cache
Connection keep-alive
Content-Encoding gzip
Content-Type text/html; charset=UTF-8
Date Mon, 27 Oct 2014 07:48:32 GMT
Server nginx
Set-Cookie laravel_session=eyJpdiI6ImVxd...; expires=Mon, 27-Oct-2014 09:48:32 GMT; Max-Age=7200; path=/; httponly
Transfer-Encoding chunked
Vary Accept-Encoding
X-Powered-By PHP/5.5.17
I found the solution.
In www.first-domain.com -> www.first-domain.com request was include the header 'X-Requested-With: XMLHttpRequest', but on www.second-domain.com -> www.first-domain.com request wasn't this header.
The full answer I found on this topic Cross-Domain AJAX doesn't send X-Requested-With header
Related
I have installed a new ubuntu server v20 with PHP Version 7.4.3 to move a web application from an older ubuntu server v18 with PHP Version 7.0 and I am getting a 403 error on the new server when performing a CURL REST API GET. Bellow is the code with the error debug, portions of the license key have been modified for the post. I haven't been able to find anything related to this searching around existing posts. Thanks for the help in advance
ob_start();
$out = fopen('php://output', 'w');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://license.cmadsystems.com?lic=P9xP1o7USRLkS591cFzBbLSmI9ZTtvR7xgfr86dtYiCZuhy",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0",
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_VERBOSE => true,
CURLOPT_STDERR => $out,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
fclose($out);
$debug = ob_get_clean();
echo $response;
echo $err;
echo $debug;
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access this resource.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>
* Trying 216.250.121.144:80...
* TCP_NODELAY set
* Connected to license.cmadsystems.com (216.250.121.144) port 80 (#0)
> GET /?lic= P9xP1o7USRLkS591cFzBbLSmI9ZTtvR7xgfr86dtYiCZuhy HTTP/1.1
Host: license.cmadsystems.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0
Accept: */*
Accept-Encoding: deflate, gzip, br
Content-Type: application/json
* Mark bundle as not supporting multiuse
< HTTP/1.1 403 Forbidden
< Content-Type: text/html; charset=iso-8859-1
< Transfer-Encoding: chunked
< Connection: keep-alive
< Keep-Alive: timeout=15
< Date: Wed, 20 May 2020 23:45:29 GMT
< Server: Apache
< Content-Encoding: gzip
<
* Connection #0 to host license.cmadsystems.com left intact
In my case it this was a DNS issue. license.cmadsystems.com was resolving to the wrong IP address.
echo file_get_contents(
"http://license.cmadsystems.com?lic=P9xP1o7USRLkS591cFzBbLSmI9ZTtvR7xgfr86dtYiCZuhy"
);
Returns
"status":200,
"status_message":"Licensed",
"data":{
"Lic_End":null,
"Lic_Device":0,
"Lic_MOH":0,
"Lic_Info":null
}
}
Every thing was working fine until we have configured checkpoint.
For checkpoint, we have a separate vpc in aws.
After that this bug started randomly. Some users are switched with other user. Example let's say User A was logged into application and after some time User A was suddenly changed with User B. This is so random that i am not able to find the way to reproduce. But end users are reporting it periodically.
My application is built in Yii 1 and logic mechanics is straight forward. Session is setting when user logged into website.
Yii1 Configuration
<?php
return array(
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
'name' => 'Project',
'defaultController' => 'site/login',
// application components
'components' => array(
'request' => array(
'enableCsrfValidation' => true,
'enableCookieValidation' => true,
'class' => 'HttpRequest',
'csrfTokenName' => '_csrf',
),
'session' => array(
'class' => 'CDbHttpSession',
'autoStart' => true,
'connectionID' => 'db',
'sessionTableName' => 'tbl_session',
'timeout' => 3600 * 24 * 30,
'autoCreateSessionTable' => false
),
'user' => array(
'allowAutoLogin' => true,
'authTimeout' => 3600 * 24 * 30,
),
::::::::::::::::::::::::::::::::::::::
//Other Stuff
::::::::::::::::::::::::::::::::::::::
),
);
Below is the sample request:
Note: i have changed the URLs to dummy one.
General
Request URL: https://[randomuniquestring].access.project.com/index.php?r=home/index
Request Method: GET
Status Code: 200
Remote Address: 143.204.*****:443
Referrer Policy: no-referrer-when-downgrade
Request Headers
:authority: randomuniquestring.access.project.com
:method: GET
:path: /index.php?r=home/index
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: max-age=0
cookie: selected_realm=ssl_vpn; _gcl_au=1.1.997081439.1542180219; __qca=P0-2107182343-1542180221727; _ga=GA1.2.663976907.1542956670; ___fnbDropDownState=1; CPCVPN_BASE_HOST=.access.project.com; CPCVPN_OBSCURE_KEY=6a97dc429cb24dafe51d5177d2e87218; _gid=GA1.2.33488363.1549271004; CPCVPN_SESSION_ID=96c6835fb518aeefe7eb64e5767c730401e4f547; _gat=1; CPCVPN_SDATA_VERSION=2
referer: https://[randomuniquestring].access.project.com/index.php?
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Response Header
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
content-length: 0
content-type: text/html; charset=UTF-8
date: Thu, 07 Feb 2019 10:38:55 GMT
expires: Thu, 19 Nov 1981 08:52:00 GMT
location: https://[randomuniquestring].access.project.com/?r=home/index
pragma: no-cache
server: CPWS
set-cookie: CPCVPN_SDATA_VERSION=2; path=/; secure; HttpOnly;
status: 302
strict-transport-security: max-age=1261440000; includeSubDomains
vary: User-Agent
via: 1.1 [randomuniquestring].cloudfront.net (CloudFront)
x-amz-cf-id: lWZ0rvOKiPO5FhJk6oPqdTchfzzsrTlb6du1DD6rNaOQZDSL1cGlcw==
x-cache: Miss from cloudfront
x-frame-options: SAMEORIGIN
x-frame-options: SAMEORIGIN
I have refer this question: PHP cookie-bases session swapping in phorum but didn't found any solution.
So is there a way to find the root cause behind it and how to resolve this one?
Other Detail
For a checkpoint, we have a separate vpc in aws.
This vpc contains link and other migrated application
I have this POST request to login to a website:
http://xxxx.net-kont.it/
POST / HTTP/1.1
Host: xxxx.net-kont.it
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: */*
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Referer: http://xxxx.net-kont.it/
Content-Length: 1904
Cookie: ASP.NET_SessionId=s44bymd3lm4dsykvymjljv5s
Connection: keep-alive
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Set-Cookie: SSOAuth=EDCCFF8CD40064D70B3377CD0389FF7F807F0B774F2CE1CA6C015314911D3D69AB819EAB9938C14608842D25991D11D8F1A5A94090DB926BD7001C526B1920A51AC986182EB016C323983716720E8F345B54E02E44C65753E9183843D23F569EF3FE52C03FC8567E809A77387B8C; path=/; HttpOnly
X-Powered-By: ASP.NET
Date: Sun, 22 Oct 2017 12:26:40 GMT
Content-Length: 714
----------------------------------------------------------
http://xxxx.net-kont.it/aspx/Empty.aspx?ControllaRichieste=true&CheckCode=29a29a891a7d4d7773f480064e5c869929bcca40e7c84812111f9affbc3be4628a3b7defe8fb9b14f9911be9c6545e7cd31c2fc04b79a8d1e7280e0277264bdcec7428037a43961c3dda5bbd54a2e7ae&wsid=1a57f5e6-bf68-4f2f-9a71-c43e8e8bfbaf&wsnew=false
GET /aspx/Empty.aspx?ControllaRichieste=true&CheckCode=29a29a891a7d4d7773f480064e5c869929bcca40e7c84812111f9affbc3be4628a3b7defe8fb9b14f9911be9c6545e7cd31c2fc04b79a8d1e7280e0277264bdcec7428037a43961c3dda5bbd54a2e7ae&wsid=1a57f5e6-bf68-4f2f-9a71-c43e8e8bfbaf&wsnew=false HTTP/1.1
Host: xxxx.net-kont.it
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://xxxx.net-kont.it/
Cookie: ASP.NET_SessionId=s44bymd3lm4dsykvymjljv5s; SSOAuth=EDCCFF8CD40064D70B3377CD0389FF7F807F0B774F2CE1CA6C015314911D3D69AB819EAB9938C14608842D25991D11D8F1A5A94090DB926BD7001C526B1920A51AC986182EB016C323983716720E8F345B54E02E44C65753E9183843D23F569EF3FE52C03FC8567E809A77387B8C
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 22 Oct 2017 12:26:40 GMT
Content-Length: 95935
----------------------------------------------------------
The post request header requires the following fields:
'__LASTFOCUS' => '',
'__EVENTTARGET' => '',
'__EVENTARGUMENT' => '',
'__VIEWSTATE' => $viewstate,
'__VIEWSTATEGENERATOR' => $viewstategenerator,
'ctl00$hwsid' => $hwsid,
'ctl00$PageSessionId' => $pagesessionid,
'ctl00$DefaultUrl' => $defaulturl,
'ctl00$GenericErrorUrl' => $genericerrorurl,
'ctl00$PopupElement' => '',
'ctl00$PollingTimeoutSecs' => $pollingtimeoutsecs,
'ctl00$bodyContent$txtUser' => $user,
'ctl00$bodyContent$txtPassword' => $password,
'__CALLBACKID' => '__Page',
'__CALLBACKPARAM' => '"hwsid="'.$hwsid.'"&PageSessionId="'.$pagesessionid.'"&DefaultUrl="'.$defaulturl.'"&GenericErrorUrl="'.$genericerrorurl.'"&PopupElement="'.'"&PollingTimeoutSecs="'.$pollingtimeoutsecs.'"&txtUser="'.$user.'"&txtPassword="'.$password,
'__EVENTVALIDATION' => $eventvalidation
From an analysis of the post request, you notice that by sending the first cookie obtained from the website "ASP.NET_SessionId=", you immediately get an additional authentication cookie "SSOAuth="
How can I get the second cookie "SSOAuth=" so that I can get access to the site? I tried this code:
$user = "xx";
$password = "xx";
$url = 'http://xxx.it/Default.aspx';
$contents = file_get_contents($url);
$dom = new DOMDocument;
$dom->loadHTML($contents);
$xpath = new DOMXpath($dom);
$eventvalidation = $xpath->query('//*[#name="__EVENTVALIDATION"]')->item(0)->getAttribute('value');
$viewstate = $xpath->query('//*[#name="__VIEWSTATE"]')->item(0)->getAttribute('value');
$viewstategenerator = $xpath->query('//*[#name="__VIEWSTATEGENERATOR"]')->item(0)->getAttribute('value');
$hwsid = $xpath->query('//*[#name="ctl00$hwsid"]')->item(0)->getAttribute('value');
$pagesessionid = $xpath->query('//*[#name="ctl00$PageSessionId"]')->item(0)->getAttribute('value');
$defaulturl = $xpath->query('//*[#name="ctl00$DefaultUrl"]')->item(0)->getAttribute('value');
$genericerrorurl = $xpath->query('//*[#name="ctl00$GenericErrorUrl"]')->item(0)->getAttribute('value');
$pollingtimeoutsecs = $xpath->query('//*[#name="ctl00$PollingTimeoutSecs"]')->item(0)->getAttribute('value');
$cookies = array_filter(
$http_response_header,
function($v) {return strpos($v, "Set-Cookie:") === 0;}
);
$headers = [
"Accept-language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/x-www-form-urlencoded; charset=utf-8",
"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0",
];
foreach ($cookies as $cookie) {
$headers[] = preg_replace("/^Set-/", "", $cookie);
}
$request = array(
'http' => array(
'method' => 'POST',
'timeout' => 0,
'header'=> $headers,
'content' => http_build_query(array(
'__LASTFOCUS' => '',
'__EVENTTARGET' => '',
'__EVENTARGUMENT' => '',
'__VIEWSTATE' => $viewstate,
'__VIEWSTATEGENERATOR' => $viewstategenerator,
'ctl00$hwsid' => $hwsid,
'ctl00$PageSessionId' => $pagesessionid,
'ctl00$DefaultUrl' => $defaulturl,
'ctl00$GenericErrorUrl' => $genericerrorurl,
'ctl00$PopupElement' => '',
'ctl00$PollingTimeoutSecs' => $pollingtimeoutsecs,
'ctl00$bodyContent$txtUser' => $user,
'ctl00$bodyContent$txtPassword' => $password,
'__CALLBACKID' => '__Page',
'__CALLBACKPARAM' => '"hwsid="'.$hwsid.'"&PageSessionId="'.$pagesessionid.'"&DefaultUrl="'.$defaulturl.'"&GenericErrorUrl="'.$genericerrorurl.'"&PopupElement="'.'"&PollingTimeoutSecs="'.$pollingtimeoutsecs.'"&txtUser="'.$user.'"&txtPassword="'.$password,
'__EVENTVALIDATION' => $eventvalidation,
'ctl00$bodyContent$btnLogin' => 'Conferma'
)),
)
);
echo "<hr/>";
$context = stream_context_create($request);
$data = file_get_contents($url, false, $context);
echo htmlentities($data);
But I get the following output of "Authentication failed":
<Notification><Error Code="" Alert="True" ClosePopup="True" Fatal="False" Message="Autenticazione fallita." /></Notification>
The session will be in the HTTP Headers and file_get_contents only get the HTTP Body so you are losing the "metadata" in which is send your cookie.
I've really recommend to use something a bit more advanced than that. #Tarun Lalwani recommended you curl. Curl which can achieve that, although I prefer to use something more intuitive as Guzzle http://docs.guzzlephp.org/en/stable/ .
Guzzle use the PSR-7 http://www.php-fig.org/psr/psr-7/
This is an Guzzle use example where you can see how easy is to access the headers:
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
I have solved! was easier than expected....in this I simply had to delete the quotes " :
'__CALLBACKPARAM' => '"hwsid="'.$hwsid.'"&PageSessionId="'.$pagesessionid.'"&DefaultUrl="'.$defaulturl.'"&GenericErrorUrl="'.$genericerrorurl.'"&PopupElement="'.'"&PollingTimeoutSecs="'.$pollingtimeoutsecs.'"&txtUser="'.$user.'"&txtPassword="'.$password,
converted to:
'__CALLBACKPARAM' => 'hwsid='.$hwsid.'&PageSessionId='.$pagesessionid.'&DefaultUrl='.$defaulturl.'&GenericErrorUrl='.$genericerrorurl.'&PopupElement='.'&PollingTimeoutSecs='.$pollingtimeoutsecs.'&txtUser='.$user.'&txtPassword='.$password,
It looks like you are trying to parse data directly from a website, have you considered approaching the website owners about building an API? in any event, I recommend using phantomjs, so that the scraper code is simpler and the traffic and other JS countermeasures are solved in an easier manner.
I am sending customer header in AJAX call,
$.ajaxSetup( {
data: {csrf_token : csrf},
headers: {"Csrf_token" : csrf}
});
Below is content which i seen in Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:325
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:ci_session=kd817592v16s0p5b2f502hg39rs7olnu; csrf_cookie=22a1c908f3f036c90c2d0bf0f9b19497
Csrf_token:22a1c908f3f036c90c2d0bf0f9b19497
Host:testurl.com
Origin:http://testurl.com
Pragma:no-cache
Referer:http://testurl.com/xxx
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
X-Requested-With:XMLHttpRequest
But when i print this in PHP it only return below, i could not see my custom header "Csrf_token"
> Array ( [X-Forwarded-For] => 57.73.33.1 [Cookie] =>
> `ci_session=kd817592v16s0p5b2f502hg39rs7olnu;
> csrf_cookie=22a1c908f3f036c90c2d0bf0f9b19497 [Accept-Language] =>
> en-GB,en-US;q=0.8,en;q=0.6 [Accept-Encoding] => gzip, deflate
> [Referer] => http://testurl.com/xxx [X-Requested-With] =>
> XMLHttpRequest [Accept] => */* [Content-Type] =>
> application/x-www-form-urlencoded; charset=UTF-8 [User-Agent] =>
> Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like
> Gecko) Chrome/54.0.2840.99 Safari/537.36 [Origin] =>
> http://testurl.com[Cache-Control] => no-cache [Pragma] => no-cache
> [Content-Length] => 325 [Connection] => close [Host] => testurl.com )`
How can i get that customer header in PHP? I am using codeigniter,
I only got output by below,
$.ajaxSetup( {
data: {csrf_token : csrf},
headers: {"csrf-token" : csrf, "csrf_token1" : csrf}
});
It will not print values with _ name but can print with - names.
Csrf-Token : "22a1c908f3f036werc90c2d0bf0f9b19497"
Use this
$headers = $this->input->request_headers();
link : https://www.codeigniter.com/user_guide/libraries/input.html#CI_Input::get_request_header
Does anyone know how to send an "OPTIONS" request using PHP.
I can't find a curl setopt that does this.
I'm using php 5.6.7
I've figured out GET, POST, DELETE, and PUT. Just need OPTIONS.
I have tried hd's answer below:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"theurl");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "OPTIONS");
$r = curl_exec($ch);
print_r($http_response_header);
curl_close($ch);
and I'm getting the error:
Undefined variable: http_response_header in C:\IIS_Emea\WebRoot\Site01\test\rest1.php on line 7
How do I get the results?
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://stackoverflow.com/',
CURLOPT_CUSTOMREQUEST => 'OPTIONS',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_VERBOSE => true,
));
$r = curl_exec($ch);
echo PHP_EOL.'Response Headers:'.PHP_EOL;
print_r($r);
curl_close($ch);
What it does:
CURLOPT_CUSTOMREQUEST => 'OPTIONS' - defines the HTTP request method.
CURLOPT_RETURNTRANSFER => true - tell curl_exec not to output results but return them.
CURLOPT_HEADER => true - return headers.
CURLOPT_NOBODY => true - do not return body.
CURLOPT_VERBOSE => true - just for debugging, remove it on production. It allows to see the request done by the library and the response received.
The output from the script looks like this
* Trying 104.16.36.249...
* Connected to stackoverflow.com (104.16.36.249) port 80 (#0)
> OPTIONS / HTTP/1.1
Host: stackoverflow.com
Accept: */*
< HTTP/1.1 200 OK
< Date: Wed, 20 Apr 2016 09:02:44 GMT
< Content-Type: text/html; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Set-Cookie: __cfduid=d96e454843a81721eeb77cc4ebb49d2c91461142964; expires=Thu, 20-Apr-17 09:02:44 GMT; path=/; domain=.stackoverflow.com; HttpOnly
< Cache-Control: public, no-cache="Set-Cookie", max-age=60
< Expires: Wed, 20 Apr 2016 09:03:44 GMT
< Last-Modified: Wed, 20 Apr 2016 09:02:44 GMT
< Vary: *
< X-Frame-Options: SAMEORIGIN
< X-Request-Guid: a2f90416-9ec1-4ec9-b2d9-a69e22cc05d5
< Set-Cookie: prov=37be6386-6390-40fb-9f0a-42efdfcf2d71; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
< Server: cloudflare-nginx
< CF-RAY: 29676b4517f92b21-WAW
<
* Excess found in a non pipelined read: excess = 725 url = / (zero-length body)
* Connection #0 to host stackoverflow.com left intact
Response Headers:
HTTP/1.1 200 OK
Date: Wed, 20 Apr 2016 09:02:44 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d96e454843a81721eeb77cc4ebb49d2c91461142964; expires=Thu, 20-Apr-17 09:02:44 GMT; path=/; domain=.stackoverflow.com; HttpOnly
Cache-Control: public, no-cache="Set-Cookie", max-age=60
Expires: Wed, 20 Apr 2016 09:03:44 GMT
Last-Modified: Wed, 20 Apr 2016 09:02:44 GMT
Vary: *
X-Frame-Options: SAMEORIGIN
X-Request-Guid: a2f90416-9ec1-4ec9-b2d9-a69e22cc05d5
Set-Cookie: prov=37be6386-6390-40fb-9f0a-42efdfcf2d71; domain=.stackoverflow.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
Server: cloudflare-nginx
CF-RAY: 29676b4517f92b21-WAW
You get response headers as a string and you need to parse it. But I guess this is out of scope of the question.
You can use curl_setopt to set the custom request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'OPTIONS'); // HTTP request is 'OPTIONS'