How to send an OPTIONS request using PHP - php

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'

Related

setcookie() always removes cookie (or don't remove because it was never set)

Server sends Thu, 01-Jan-1970 00:00:01 GMT even if I set expires to 2147483647:
if(!setcookie("auth-data", $data, [
'expires' => 2147483647,
'samesite' => 'Lax',
'path' => '...'
]))
{
http_response_code(405);
echo "{\"status\":\"failed to set cookie\"}";
exit;
}
Not worked: setting expires to 0, -1, time() + 60*60*24*40, time() + another value, ...
Server response:
HTTP/1.1 200 OK
Date: Sat, 24 Oct 2020 10:38:58 GMT
Server: Apache/2.4.41 (Ubuntu)
Set-Cookie: auth-data=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=...; SameSite=Lax
...

Session Swapping after Checkpoint Firewall implemenation

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

Php Twitter Web services curl and file_get_contents converting string response to JSON

I am trying to use twitter API with PHP CURL (previously I used file_get_contents which I had to abandon due to file_get_content not able to respond effectively to twitter rate limits).
When I run the code using file_get_content, I get a string in response, on which I can easily use json_decode() and my work is done. But...
When I run the code using curl, in the response i get a one huge string that has the same data that I obtained using the above method plus some additional information. And because of that I cant use json_decode() on that response. Following are the two responses.
Response From file_get_content
string(1964) "{"id":2988119635,"id_str":"2988119635","name":"Michael Jackson","screen_name":"Yahoo6464","location":"","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":false,"followers_count":4,"friends_count":2,"listed_count":2,"created_at":"Sun Jan 18 07:18:41 +0000 2015","favourites_count":6,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":144,"lang":"en","status":{"created_at":"Tue Mar 15 07:09:21 +0000 2016","id":709637592510308352,"id_str":"709637592510308352","text":"noooooooooooooooooooo"}"
Response From CURL
string(2942) "HTTP/1.1 200 OK
cache-control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
content-disposition: attachment; filename=json.json
content-length: 1964
content-type: application/json;charset=utf-8
date: Wed, 16 Mar 2016 06:58:18 GMT
expires: Tue, 31 Mar 1981 05:00:00 GMT
last-modified: Wed, 16 Mar 2016 06:58:18 GMT
pragma: no-cache
server: tsa_f
set-cookie: lang=en; Path=/
set-cookie: guest_id=v1%3A145811149839783410; Domain=.twitter.com; Path=/; Expires=Fri, 16-Mar-2018 06:58:18 UTC
status: 200 OK
strict-transport-security: max-age=631138519
x-access-level: read-write
x-connection-hash: e23e2992def7a3837cdbb3a3201bf7de
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-rate-limit-limit: 15
x-rate-limit-remaining: 12
x-rate-limit-reset: 1458112290
x-response-time: 171
x-transaction: 3fca373925e5f65b
x-twitter-response-tags: BouncerExempt
x-twitter-response-tags: BouncerCompliant
x-xss-protection: 1; mode=block
{"id":2988119635,"id_str":"2988119635","name":"Michael Jackson","screen_name":"Yahoo6464","location":"","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":false,"followers_count":4,"friends_count":2,"listed_count":2,"created_at":"Sun Jan 18 07:18:41 +0000 2015","favourites_count":6,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":144,"lang":"en","status":{"created_at":"Tue Mar 15 07:09:21 +0000 2016","id":709637592510308352,"id_str":"709637592510308352","text":"noooooooooooooooooooo"}"
Here is my curl options
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CUSTOMREQUEST => 'GET',
);
$ci = curl_init();
$d = curl_setopt_array($ci, $options);
$response = curl_exec($ci);
Just set CURLOPT_HEADER to false.

file_get_contents: get full response (PHP)

I'm using the following code to post information to a URL.
$query = http_build_query($myvars);
$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);
$response = file_get_contents($url, false, $context);
Is it possible to show the complete header information of the response.
First I used curl, but this took to much cpu.
With curl I used the following option:
curl_setopt($ch, CURLOPT_HEADER, 1);
And I received the following header information:
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Mon, 21 Sep 2015 07:06:35 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.11
Content-Description: File Transfer
Content-Disposition: attachment; filename=File.txt
Content-Transfer-Encoding: binary
Content-Length: 333
Cache-Control: must-revalidate, post-check=0, pre-check=0
Expires: 0
Pragma: public
Vary: Accept-Encoding
Content-Type: text/plain
Is the with file_get_contents also possible?
file_get_contents("http://example.com");
var_dump($http_response_header);
http://php.net/manual/en/reserved.variables.httpresponseheader.php

Confusion with mail.google.com, cURL and http://validator.w3.org/checklink

I am building a basic link checker at work using cURL. My application has a function called getHeaders() that returns an array of HTTP headers:
function getHeaders($url) {
if(function_exists('curl_init')) {
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => true );
curl_setopt_array($ch, $options);
// grab URL and pass it to the browser
curl_exec($ch);
$headers = curl_getinfo($ch);
// close cURL resource, and free up system resources
curl_close($ch);
} else {
echo "Error: cURL is not installed on the web server. Unable to continue.";
return false;
}
return $headers;
}
print_r(getHeaders('mail.google.com'));
Which yields the following results:
Array
(
[url] => http://mail.google.com
[content_type] => text/html; charset=UTF-8
[http_code] => 404
[header_size] => 338
[request_size] => 55
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.128
[namelookup_time] => 0.042
[connect_time] => 0.095
[pretransfer_time] => 0.097
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0.128
[redirect_time] => 0
)
I've tested it with several long links, and the function acknowledges redirects, all apart from mail.google.com it seems.
For fun, I passed the same URL (mail.google.com) to the W3C link checker, which produced:
Results
Links
Valid links!
List of redirects
The links below are not broken, but the document does not use the exact URL, and the links were redirected. It may be a good idea to link to the final location, for the sake of speed.
warning Line: 1 http://mail.google.com/mail/ redirected to
https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=zpwhtygjntrz&scc=1&ltmpl=default&ltmplcache=2
Status: 302 -> 200 OK
This is a temporary redirect. Update the link if you believe it makes sense, or leave it as is.
Anchors
Found 0 anchors.
Checked 1 document in 4.50 seconds.
Which is correct, as the address above is where I am redirected to when I enter mail.google.com into my browser.
What cURL options would I need to use to make my function return 200 for mail.google.com?
Why is it that the function above returns 404 status code as opposed to 302 status code?
TIA
The problem is that the redirect is specified through methods that cURL won't follow.
Here is the response from http://mail.google.com:
HTTP/1.1 200 OK
Cache-Control: public, max-age=604800
Expires: Mon, 22 Jun 2009 14:58:18 GMT
Date: Mon, 15 Jun 2009 14:58:18 GMT
Refresh: 0;URL=http://mail.google.com/mail/
Content-Type: text/html; charset=ISO-8859-1
X-Content-Type-Options: nosniff
Transfer-Encoding: chunked
Server: GFE/1.3
<html>
<head>
<meta http-equiv="Refresh" content="0;URL=http://mail.google.com/mail/" />
</head>
<body>
<script type="text/javascript" language="javascript">
<!--
location.replace("http://mail.google.com/mail/")
-->
</script>
</body>
</html>
As you can see, the page uses both a Refresh header (and HTML meta equivalent) and javascript in the body to change location to http://mail.google.com/mail/.
If you then request http://mail.google.com/mail/, you will be redirected (with the Location header, which cURL follows) to the page you had previously mentioned W3C correctly identifies.
HTTP/1.1 302 Moved Temporarily
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Date: Mon, 15 Jun 2009 15:07:56 GMT
Location: https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=zpwhtygjntrz&scc=1&ltmpl=default&ltmplcache=2
Content-Type: text/html; charset=UTF-8
X-Content-Type-Options: nosniff
Transfer-Encoding: chunked
Server: GFE/1.3
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Cache-control: no-cache, no-store
Pragma: no-cache
Expires: Mon, 01-Jan-1990 00:00:00 GMT
Set-Cookie: GALX=B8zH60M78Ys;Path=/accounts;Secure
Date: Mon, 15 Jun 2009 15:07:56 GMT
X-Content-Type-Options: nosniff
Content-Length: 19939
Server: GFE/2.0
(HTML page content here, removed)
Perhaps you should add an additional step in your script to check for a Refresh header.
Another possible error is that you have open_basedir set in your PHP configuration, which would disable CURLOPT_FOLLOWLOCATION - you can check this quickly by turning on error reporting, as a message is generated as either a warning or notice.
The results above were all obtained with the following cURL setup:
$useragent="Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
Could it be that
mail.google.com -> mail.google.com/mail is a 404 and then a hard redirect
and
mail.google.com/mail -> https://www.google.com/accounts... etc is a 302 redirect

Categories