Set a cookie on another domain using ajax and php - FAILS - php

Domain-Being-Browsed.com has a javascript function, which when triggered makes an ajax call to a php file on another domain: another-domain.com/set-cookie.php
set-cookie.php contains code like this:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
$cookie_set = FALSE;
$cookie_set = setcookie( 'cookie_name', 'cookie_value', $a_big_number, '/' );
if( $cookie_set ){ echo 'cookie set!'; }
The javascript function is like this:
var url = 'http://another-domain.com/set-cookie.php';
$.ajax({
'url': url,
'xhrFields': {
withCredentials: true
}
}).done(function(resp){
console.log(resp);
});
If I visit http://another-domain.com/set-cookie.php in my browser, it sets the cookie.
If I trigger the javascript function, I get a response in the console, 'cookie set!', but when I load http://another-domain.com in my browser, I find that the cookie is not there.
I found this post: Can't set cookie on different domain, which seems exactly like mine, but the answer given I've incorporated already and it doesn't help. What am I missing?

As directed by Barmar, I checked the Network tab in dev tools for the Set-Cookie header in the response. It seems that I needed to set 'SameSite' to 'None'. If you set 'Samesite' to none, you have to set 'secure' also. And if you set secure, you have to load the page over https. So the answer, as found in the answer here: How to fix "set SameSite cookie to none" warning?
is to change the php file like this:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
$cookie_options = array(
'expires' => time() + 60*60*24*30,
'path' => '/',
'secure' => true,
'samesite' => 'None'
);
$cookie_set = FALSE;
$cookie_set = setcookie( 'cookie_name', 'cookie_value', $cookie_options );
if( $cookie_set ){ echo 'cookie set!'; }
and to load the page over https. Works!

Related

setcookie() working on localhost but not working on production (domain.com)

I have been facing some issues regarding setcookie() in php. setcookie() is working fine on local host
but not on live domain. here's how i am setting in localhost.
Localhost
setcookie("private_token",$jwt,$expire_claim,"/","",false,true);
Domain
setcookie("private_token",$jwt,$expire_claim,"/","domain.com",false,true);
Ajax Call
$.ajax({
url: "includes/api/userAPI.php",
type: 'POST',
data: data,
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (res, text, code) {
if (code.status == 200) {
window.location.replace("landing.php");
} else {
alert("something went wrong");
}
},
error: function (res) {
if (res.status == 401) {
alert("failed to authorize");
}
}
});
Header's in PHP
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
P.S: i think i have already searched entire site. but haven't found anything regarding this matter
Edit:
These are the lines before setcookie . these are excuted after setting header which i already mentioned earlier
SELF::$connection = Parent::getConnection();
$str = "select * from user where col=?";
$query = SELF::$connection->prepare($str);
$array = array($user->__get('col'));
$query->execute($array);
$row = $query->fetch(PDO::FETCH_ASSOC);
$session = new session();
$session->set_session($row['id']);
$id = $row["id"];
$username = $row["user"];
$password = $user->__get("pass");
$email = $user->__get("mail");
$hash = $row['pass'];
if(password_verify($password,$hash))
{
$secret_key = "dummy";
$issuer_claim = "THE_ISSUER"; // this can be the servername
$audience_claim = "THE_AUDIENCE";
$issuedat_claim = time(); // issued at
$expire_claim = strtotime('+1 day', $issuedat_claim);; // expire time in seconds
$token = array(
"iss" => $issuer_claim,
"aud" => $audience_claim,
"iat" => $issuedat_claim,
//u "nbf" => $notbefore_claim,
"exp" => $expire_claim,
"data" => array(
"id" => $id,
"username" => $username,
"email" => $email
));
now i just got following error in response
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at <file directory where setcookie has been called>:74) in <b><file directory where setcookie has been called></b> on line <b>77</b><br />
line 74 "expireAt" => $expire_claim
line 77 setcookie("private_token",$jwt,$expire_claim,"/","domain.com",false,true);
setcookie is failing to actually set the cookie because the headers have already been sent. Cookies are set in HTTP responses using the Set-Cookie header.
You have PHP script outputting content prior to your setcookie call. Without seeing your entire project, it is not possible to identify exactly where. Typically the cause of this is having files saved with extra characters after closing PHP tags at the end of a file(this is a common problem). You will need to locate and remove these extra characters(assuming they are extraneous). Otherwise, you will need to refactor your logic so that setcookie can be called earlier.
The only other option would be to enable output buffering. This will prevent the output from being sent immediately; it will be buffered in memory and send when the request is complete unless you explicitly send it earlier. This is useful in various cases, but would really only be a workaround for the root problem here.
In your case, since this is happening only in one environment, I would start with reviewing any environment specific code/configuration(which it sounds like you have). It may also be your deployment/build process is adding extra characters when deploying to the problematic environment.

How to create cookie or session through jquery ajax?

I'm trying to build own javascript API for a chat online. This API is intended to get css file and javascript file and after loading the website it must create a conversation window. I want to share this API for other users.
e.g. If my domain is mydomain.com and includes in html code my javascript API, which downloads css file and javascript file from example.com, what is the best practice to create cookie or session on the user side?
Below is my API:
<div id="fb-dialog"></div>
<script async defer src="http://coders.localhost/api/fb-dialog.js">
var apiConf = {
key: 'YOUR_API_KEY',
language: {
/* Your language codes and default greeting */
"pl" : "Dzień dobry, jestem online. W czym mogę pomóc?",
"en" : "Hello, I'm online. How can I help you?"
}
}
</script>
I want share this chat but any conversation must be save on my server.
I want to use a database which will to have a website's ID on the which is installed the API. Before starting a conversation in cookie I want get website ID on the which can I will return response. How can I to do?
My javascript:
<script>
$.ajax({
xhrFields: {
withCredentials: true
},
type: "GET",
url: "http://coders.localhost/modules/fb-dialog/heading.php"
}).done(function (data) {
alert("OK");
});
</script>
My PHP script:
<?php
if (!isset($_SERVER['HTTP_ORIGIN'])) {
// This is not cross-domain request
exit;
}
$wildcard = false; // Set $wildcard to TRUE if you do not plan to check or limit the domains
$credentials = true; // Set $credentials to TRUE if expects credential requests (Cookies, Authentication, SSL certificates)
$allowedOrigins = array('http://firma.localhost', 'http://jsfiddle.net');
if (!in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins) && !$wildcard) {
// Origin is not allowed
exit;
}
$origin = $wildcard && !$credentials ? '*' : $_SERVER['HTTP_ORIGIN'];
header("Access-Control-Allow-Origin: " . $origin);
if ($credentials) {
header("Access-Control-Allow-Credentials: true");
}
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Origin");
header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies
// Handling the Preflight
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit;
}
if(!isset($_COOKIE['fb-dialog'])) {
setcookie("fb-dialog", "true", time()+3600, "/");
}else{
if(!isset($_POST['data'])) {
if($_COOKIE['fb-dialog'] == 'true') {
setcookie('fb-dialog', 'false', 0, '/');
} else {
setcookie("fb-dialog", "true", time()+3600, "/");
}
}
}
// Response
header("Content-Type: application/json; charset=utf-8");
echo json_encode(array('status' => 'OK'));
?>
The above code is working. I'm getting a status 200 but a cookie is not for proper domain because the script create a cookie for domain coders.localhost
I have two domains:
http://firma.localhost - this is my website
http://coders.localhost - this is remote domain from who I get API
I want create cookie by coders.localhost domain for firma.localhost.
You can also use plain javascript:
document.cookie = "username=admin";
or
var x = document.cookie;
Probably you have figured already the answer, It would be great if you shared how you resolved it.
I think the issue maybe due to your / configuration in the setcookie
Your config:
setcookie("fb-dialog", "true", time()+3600, "/");
Try this:
setcookie("fb-dialog", "true", time()+3600, "http://coders.localhost");

Cookie doesn't get deleted with xml callback jquery php

I'm not sure if somebody asked this already, at least i cant find the answer so i'm wondering what i'm doing wrong with my script.
I'm trying to delete a cookie with a callback done by Jquery that calls a php script on the background, BUT, whatever i try i cannot get this to properly work (deleting the cookie).
I've checked the php website and even looked at the RFC 2109 memo to find out how browsers and php try to accomplish that the cookie will be deleted.
So, my question here is; How can this fail?
Edit: i don't get any error message, deleting the cookie manually works and creating the cookie with the same type of callback done by jquery does also work. It just doesn't get deleted when i try the same callback with jquery to run the PHP script in the background in order to delete the cookie.
Code for that JQ callback action:
$(document).ready(function() {
var alert = $('#Cmessage');
$(".delete").on('click', function(){
$.ajax({
url: 'http://www.oostpijl.nl/shop/offerte/deletecookie.php',
type: 'get', // form submit method get/post
dataType: 'json', // request type html/json/xml
beforeSend: function() {
alert.fadeOut();
},
success: function(result) {
if(result.error){
alert.html(result.html).fadeIn();
console.log(e)
}else{
alert.html(result.html).fadeIn();
}
}
});
});
});
PHP script:
<?php
include("_offertesettings.php");
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
setcookie('offerte', '', time() - 3600, '/' , '.oostpijl.nl' );
setcookie('offerteC', '', time() - 3600, '/', '.oostpijl.nl' );
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<script type='text/javascript'>setTimeout(function() { window.location='" . $config["BURL"] . "'; }, 10);</script>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error; Neem contact op met de webmaster</h3>";
}
echo json_encode($result);
exit;
?>
Make sure you get inside your isset condition. You should test it by printing something as a test then exit.
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
echo json_encode('test');
exit;
}
also make sure there is no error in your included file "_offertesettings.php". You can check if there are PHP errors by adding those lines at the top of your PHP script.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
to delete your cookies you just need this:
setcookie('offerte', '', time() - 3600);
setcookie('offerteC', '', time() - 3600);

Why won't my cookie delete?

I have a cookie, that I set with the following command:
setcookie( 'auth', 'cookie data' , time() + 3600, '/', '.mydomain.com', true, true );
when I log out, I call a function to clear it, which does this:
setcookie( 'auth', "", time() - 3600, '/', '.mydomain.com', true, true );
However, if I then refresh the page, $_COOKIE['auth'] is still set, and returns the old 'cookie data' value that should be gone!
What am I missing?
unset($_COOKIE['auth']);
setcookie('auth', '');
make sure you haven't already sent headers
http://www.php.net/manual/en/function.headers-sent.php
make sure you are sending headers. Are you outputting anything else? If not, echo anything to make sure headers are sent before exit.
remove from cookie global array also
if(isset($_COOKIE['auth'])) {
unset($_COOKIE['auth']);
}
if your session name is 'auth', any change to session data may rewrite the session cookie

Cant set cookie for remote domain with AJAX (CORS)

I have two domains:
login.com and site.com
On the page login.com/ajax.htm I have the following code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function() {
$.get('http://site.com/setCookie.php', {}, function(text) {alert(text);});
});
</script>
setCookies.php on site.com contains only:
header('Access-Control-Allow-Origin: *');
setcookie('Cookie', 'Cookie', time()+60*60*24*30, '/', 'example.com');
setcookie('Cookie3', 'Cookie3', time()+60*60*24*30, '/', '.example.com');
setcookie('Cookie4', 'Cookie4', time()+60*60*24*30, '/', '');
setcookie('Cookie5', 'Cookie5');
echo 'Cookies set';
All I want is that setCookies.php will set cookies for site.com, when requested from ajax.htm.
Actually, when I visit login.com/ajax.htm, I get JS alert "Cookies set", but none of them are set, in fact :)
So the question is, how I can make a script set cookie for its own domain (not for the domain from which its being requested), when it is requested with AJAX?

Categories