Sessions do not appear when I make a call by ajax

1

Friends I had a problem with the sessions, because I can not recover them when I call them by ajax from another domain (the ajax calls the previous domain)

I create the sessions in this domain ( link )

and then I call that same domain with ajax but from another domain ( link ) (Put another port is another domain)

$.ajax({
           type: "POST",
           url:'http://localhost/multicode/login/prueba',
           datatype:"json",
           crossDomain: true, 
           contentType: "application/x-www-form-urlencoded", 
           dataType: 'json', 
           processData: false, 
           cache: false, 
           success : function(r){
               console.log(r)
           }
       });
    
asked by Franz 03.01.2017 в 18:00
source

2 answers

0

In PHP, session ids can be passed through cookies or through parameters in the URL. Normally through cookies because it is an optimal and safer method, but it is possible through the URL anyway in case the cookies are not enabled ( source ).

Since your websites are in different domains, the cookie is different and that is why the session is not the same. You will have to pass the session id as a parameter in the URL so that they share a session (something that does not seem to be done in the AJAX request of the code).

Another problem that you will find is that the data of the session will not be the same on different servers (even if you have solved the problem of the cookie). This is because by default the data is stored locally and is not shared between different domains.

One solution for this would be to create your own session id (with session_set_save_handler ) and save the data of the session in a storage system "independent" (eg in a database) associated with that session id.

Then when changes are made or you want to read the data, regardless of the domain from which the request comes, the database will be written / read (with the appropriate session id).

    
answered by 04.01.2017 / 14:37
source
0

I can think of many ways to solve this problem but definitely the simplest would be to use domains and subdomains; You can create a cookie that is valid for ALL subdomains. The files you need to configure are:

  • On Windows C:\WINDOWS\system32\drivers\etc\hosts
  • On Linux: /etc/hosts

This way you can set your domains as:

127.0.0.1  desarrollo.com
127.0.0.1  prueba.desarrollo.com
127.0.0.1  produccion.desarrollo.com
127.0.0.1  me_gusta_bailar.desarrollo.com

And your sessions will be shared among all these subdomains, so you can make a post from link to link and your sessions will last without any problem.

    
answered by 08.01.2017 в 09:25