0

I've been trying to retrieve cookie from php for awhile. post

from php I have this method:

public function created()
{
  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  var_dump($json);
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==""){
    $cookie=$random = rand(1,1000);
    setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost" );
  }
  else{
    $cookie=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie,
        ];
  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);
  //return response()->json($cookie);
}

which creates cookie if none exists and I see it in my response headers. (Don't pay attention to how I create cookie for now, I now rand() function is not the right way, it's just for testing)

In my angular side I have :

function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"

                },

            })
                .then(function (data) {

                    console.log(data.headers('Set-cookie'));

                }, function (data) {
                    console.log(data.headers('Set-cookie'));
                });
        }

    }

I would like to post my JSON object and recieve cookie with response. However I am quite stuck. I tried with .success() but it's deprecated, so I am using .then() , but then I print console.log(data.headers('Set-cookie')); I get null result. Does anybody ever had similar problem?

I also tried:

.then(function (data, status, headers, config) {

                    console.log(headers('Set-cookie'));

                }, function (data, status, headers, config) {
                    console.log(headers('Set-cookie'));
                });

and:

.then(function(response) {
                    if (response.data == 'ok') {
                        $cookies['X-AUTH-TOKEN']=response.headers('X-AUTH-TOKEN');
                        // below put,put,putObject Cookies value is valid for Angular version >= 1.4
                       var $cookie= $cookies.putObject('X-AUTH-TOKEN',response.headers('X-AUTH-TOKEN'));
                        console.log($cookie);
                        debugger;

                    }

                });

but none of them worked. What problem could it be?


My client side:

function PostReview(JSONObject) {
        if (JSONObject != null) {
            debugger;

            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json"
                }

            })
        }
    }

in my controllers:

$scope.Cookie = $cookies.get('cookie');
    $scope.$watch('Cookie', function() {
        $scope.Cookie = $cookies.get('cookie');
    });

WHhat about cross-domain cookies?

6
  • to get the cookie you've defined, just inject $cookies in your controller and then use $cookies.get("cookie");...you need to post exactly how your client-side looks like and where you're using the $cookies.get("cookie"); so it will be easier to help you Commented Jul 3, 2017 at 21:14
  • @ElmerDantas I updated my answer, I tried adding $cookies.get("cookie"); in various places, though I suppose i should be watching it. But nothing seems to work Commented Jul 3, 2017 at 21:26
  • could you put a console.log on the controller to print $cookies.get("cookie"); make the request and then refresh the page? probably you'll see the value. I'm afraid you cannot access the value the way you're trying Commented Jul 3, 2017 at 21:43
  • just now that I noticed that you're not using the same domain,,,why is that? Commented Jul 3, 2017 at 22:07
  • because my php server is in localhost:8000 and my front side in angular on localhost/ Commented Jul 4, 2017 at 3:52

2 Answers 2

1

set-cookie is an instruction to your client app (e.g. the browser your code is running on) - not for your code. it should be automatically saving the cookie to your client, then it'll be sent automatcally to the server in wach call. to get the current cookies you can use $cookies.

if the cookie doesn't saved, there could be veriety of reasons why, e.g. maybe the domain-name do not match, basically, in order to read the cookie, all the parameters of the set-cookie should match the current page, and also the expiration-date should be in the future (or omited).

ok, find your problem, you should add the port number, like so:

setcookie( "cookie", "$cookie", time() + (10 * 365 * 24 * 60 * 60), "/", "http://localhost:8000" );
Sign up to request clarification or add additional context in comments.

5 Comments

I am getting undefined. Not sure if it is because I'm not returning anything from php side from my created() function or I call $cookies.get("cookie"); incorrectly
I don't think it should be with port number, because my api is localhost:8000 and my client side is localhost/
if so, then your api can't plant cookies to your client-side because they're treated as a totally different domains, the request to localhost:8000/creation can only send cookies to localhost:8000 hosted page. if you want to get the cookies in your client-side you should either move it under localhost:8000, or move your api to localhost
Is it really impossible to have api on localhost:800 and front-end on localhost and retrieve cookies there?
that's the rules, see: en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Path why won't you put them both as a two diferent virtual path's on the same port? e.g. localhost/api/creation localhost/guestbookstorage/ang
0

I found a way to my problem, it may be not the best way to solve it, but if anyone runs into the same problem it will probably help.

function PostReview(JSONObject) {
        if (JSONObject != null) {
            $http({

                url: 'http://localhost:8000/creation',
                method: "POST",
                data: JSONObject,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;",
                    "Accept": "application/json",
                    "crossDomain": true,
                    "withCredentials": true 
                }

            }).then(function (response) {
            if(response.data.cookie_value===undefined){
                var info = JSON.parse(JSONObject);
                console.log(info.cookie);
                $cookies.put('userCookie', info.cookie);

            }
            else{
                console.log(response.data.cookie_value);
                $cookies.put('userCookie', response.data.cookie_value);
            }
            $rootScope.savedInfo=JSON.parse(JSONObject);
        });
        }
    }

I set cookie from response method if none exists, if it exists, then I use value from my json object.

In php side I check if cookie which I sent is empty, if it is, then I create cookie. Doesn't seem that hard, but I spent so much time on this.

public function created()
{
    $date = new DateTime();
    $date->setTimeZone(new DateTimeZone("Europe/Vilnius"));
    $get_datetime = $date->format('d.m.Y H:i:s');

  $datetime = date_create()->format('Y-m-d H:i:s');
  $json =file_get_contents('php://input');
  $decoded = json_decode($json, true);
  $cookie="";
  $obj=new \stdClass();

  if($decoded['cookie']==" "){
    $cookie_name = "user";
    $cookie_value =$random = md5(rand(1,1000));
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
    $_COOKIE[$cookie_name]=$cookie_value;
    $obj->cookie_value=$cookie_value;
  }
  else{
   $cookie_value=$decoded['cookie'];
  }

        $user=[
            'name'=>$decoded['name'],
            'surname'=>$decoded['surname'],
            'email'=>$decoded['email'],
            'review'=>$decoded['review'],
            'time'=>$datetime,
            'cookie'=>$cookie_value,
        ];
//  $obj->cookie=$cookie;
  DatabaseModel::newuser($user);

     return response()->json( $obj);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.