How to fetch RSS feed data in angular2 [duplicate] - google-api

I'm making an Ajax.request to a remote PHP server in a Sencha Touch 2 application (wrapped in PhoneGap).
The response from the server is the following:
XMLHttpRequest cannot load http://nqatalog.negroesquisso.pt/login.php. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.
How can I fix this problem?

I wrote an article on this issue a while back, Cross Domain AJAX.
The easiest way to handle this if you have control of the responding server is to add a response header for:
Access-Control-Allow-Origin: *
This will allow cross-domain Ajax. In PHP, you'll want to modify the response like so:
<?php header('Access-Control-Allow-Origin: *'); ?>
You can just put the Header set Access-Control-Allow-Origin * setting in the Apache configuration or htaccess file.
It should be noted that this effectively disables CORS protection, which very likely exposes your users to attack. If you don't know that you specifically need to use a wildcard, you should not use it, and instead you should whitelist your specific domain:
<?php header('Access-Control-Allow-Origin: http://example.com') ?>

If you don't have control of the server, you can simply add this argument to your Chrome launcher: --disable-web-security.
Note that I wouldn't use this for normal "web surfing". For reference, see this post: Disable same origin policy in Chrome.
One you use Phonegap to actually build the application and load it onto the device, this won't be an issue.

If you're using Apache just add:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
in your configuration. This will cause all responses from your webserver to be accessible from any other site on the internet. If you intend to only allow services on your host to be used by a specific server you can replace the * with the URL of the originating server:
Header set Access-Control-Allow-Origin: http://my.origin.host

If you have an ASP.NET / ASP.NET MVC application, you can include this header via the Web.config file:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<!-- Enable Cross Domain AJAX calls -->
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>

This was the first question/answer that popped up for me when trying to solve the same problem using ASP.NET MVC as the source of my data. I realize this doesn't solve the PHP question, but it is related enough to be valuable.
I am using ASP.NET MVC. The blog post from Greg Brant worked for me. Ultimately, you create an attribute, [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")], that you are able to add to controller actions.
For example:
public class HttpHeaderAttribute : ActionFilterAttribute
{
public string Name { get; set; }
public string Value { get; set; }
public HttpHeaderAttribute(string name, string value)
{
Name = name;
Value = value;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AppendHeader(Name, Value);
base.OnResultExecuted(filterContext);
}
}
And then using it with:
[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
return Json( "Some public result" );
}

As Matt Mombrea is correct for the server side, you might run into another problem which is whitelisting rejection.
You have to configure your phonegap.plist. (I am using a old version of phonegap)
For cordova, there might be some changes in the naming and directory. But the steps should be mostly the same.
First select Supporting files > PhoneGap.plist
then under "ExternalHosts"
Add a entry, with a value of perhaps "http://nqatalog.negroesquisso.pt"
I am using * for debugging purposes only.

This might be handy for anyone who needs to an exception for both 'www' and 'non-www' versions of a referrer:
$referrer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referrer);
$domain = $parts['host'];
if($domain == 'google.com')
{
header('Access-Control-Allow-Origin: http://google.com');
}
else if($domain == 'www.google.com')
{
header('Access-Control-Allow-Origin: http://www.google.com');
}

If you're writing a Chrome Extension and get this error, then be sure you have added the API's base URL to your manifest.json's permissions block, example:
"permissions": [
"https://itunes.apple.com/"
]

I will give you a simple solution for this one. In my case I don't have access to a server. In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple:
Create a Chrome browser shortcut
Right click short cut icon -> Properties -> Shortcut -> Target
Simple paste in "C:\Program Files\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security.
The location may differ. Now open Chrome by clicking on that shortcut.

I've run into this a few times when working with various APIs. Often a quick fix is to add "&callback=?" to the end of a string. Sometimes the ampersand has to be a character code, and sometimes a "?": "?callback=?" (see Forecast.io API Usage with jQuery)

This is because of same-origin policy. See more at Mozilla Developer Network or Wikipedia.
Basically, in your example, you to need load the http://nqatalog.negroesquisso.pt/login.php page only from nqatalog.negroesquisso.pt, not localhost.

if you're under apache, just add an .htaccess file to your directory with this content:
Header set Access-Control-Allow-Origin: *
Header set Access-Control-Allow-Headers: content-type
Header set Access-Control-Allow-Methods: *

In Ruby on Rails, you can do in a controller:
headers['Access-Control-Allow-Origin'] = '*'

If you get this in Angular.js, then make sure you escape your port number like this:
var Project = $resource(
'http://localhost\\:5648/api/...', {'a':'b'}, {
update: { method: 'PUT' }
}
);
See here for more info on it.

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS' responses.
In Chrome, use this extension. If you are on Mozilla check this answer.

We also have same problem with phonegap application tested in chrome.
One windows machine we use below batch file everyday before Opening Chrome.
Remember before running this you need to clean all instance of chrome from task manager or you can select chrome to not to run in background.
BATCH: (use cmd)
cd D:\Program Files (x86)\Google\Chrome\Application\chrome.exe --disable-web-security

In Ruby Sinatra
response['Access-Control-Allow-Origin'] = '*'
for everyone or
response['Access-Control-Allow-Origin'] = 'http://yourdomain.name'

When you receive the request you can
var origin = (req.headers.origin || "*");
than when you have to response go with something like that:
res.writeHead(
206,
{
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': origin,
}
);

Related

SignalR responses overwriting headers

I've built a simple SignalR hub that lives within a WebAPI service, I've included all the required CORS attributes on both WebAPI and SignalR. My WebAPI endpoints are all working as expected but SignalR isn't.
I've tried all I can think of and all I can find online but nothing works, I already tried this answer, and this other to no solution.
My SignalR extension method looks like this
public static IAppBuilder UseSignalrNotificationService(this IAppBuilder app)
{
var config = new HubConfiguration();
config.Resolver = new HubDependencyResolver();
config.EnableDetailedErrors = true;
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR(config);
return app;
}
And I even tried adding the response headers on all requests using the Web.config but I allways get the same error:
XMLHttpRequest cannot load https://MyApplicationServer/notifications/signalr/negotiate?clientProtocol=1.5&access_token=&connectionData=. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'MyOriginService' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.
After more research and fiddling with the server side of the problem, I ran into this answer and found the error to be with the client side of the request. according to this GitHub issue, the "withCredentials" parameter of the request is always set to 'true'. The solution was to call on the client the start method as follows:
$.connection.hub.start({ withCredentials: false }).done(function () { //... }
Are you changing the request somewhere with some kind of global interceptor? For some reason, the XMLHttpRequest starts with withCredentials:true and this is forbidden when the Access-Control-Allow-Origin is set to *.
What about setting the 'Access-Control-Allow-Origin' to 'http://MyApplicationServer'? It's safer than * and will remove your problem at source.

The 'Access-Control-Allow-Origin' header contains multiple values

I'm using AngularJS $http on the client side to access an endpoint of a ASP.NET Web API application on the server side. As the client is hosted on a different domain as the server, I need CORS. It works for $http.post(url, data). But as soon as I authenticate the user and make a request via $http.get(url), I get the message
The 'Access-Control-Allow-Origin' header contains multiple values 'http://127.0.0.1:9000, http://127.0.0.1:9000', but only one is allowed. Origin 'http://127.0.0.1:9000' is therefore not allowed access.
Fiddler shows me that there are indeed two header entries in the get request after a successful options request. What and where am I doing something wrong?
Update
When I use jQuery $.get instead of $http.get, the same error message appears. So this seems no issue with AngularJS. But where is it wrong?
We ran into this problem because we had set up CORS according to best practice (e.g. http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api) AND ALSO had a custom header <add name="Access-Control-Allow-Origin" value="*"/> in web.config.
Remove the web.config entry, and all is well.
Contrary to #mww's answer, we still have EnableCors() in the WebApiConfig.cs AND an EnableCorsAttribute on the controller. When we took out one or the other, we ran into other issues.
I added
config.EnableCors(new EnableCorsAttribute(Properties.Settings.Default.Cors, "", ""))
as well as
app.UseCors(CorsOptions.AllowAll);
on the server. This results in two header entries. Just use the latter one and it works.
I'm using Cors 5.1.0.0, after much headache, I discovered the issue to be duplicated
Access-Control-Allow-Origin & Access-Control-Allow-Header headers from the server
Removed config.EnableCors() from the WebApiConfig.cs file and just set the [EnableCors("*","*","*")] attribute on the Controller class
Check this article for more detail.
Add to Register WebApiConfig
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Or web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
BUT NOT BOTH
Apache Server:
I spend the same, but it was because I had no quotation marks (") the asterisk in my file that provided access to the server, eg '.htaccess.':
Header add Access-Control-Allow-Origin: *
Header add Access-Control-Allow-Origin "*"
You may also have a file '.htaccess' in a folder with another '.htaccess' out, eg
/
- .htaccess
- public_html / .htaccess (problem here)
In your case instead of '*' asterisk would be the ip (http://127.0.0.1:9000) server that you give permission to serve data.
ASP.NET:
Check that there is no 'Access-Control-Allow-Origin' duplicate in your code.
Developer Tools:
With Chrome you can verify your request headers. Press the F12 key and go to the 'Network' tab, now run the AJAX request and will appear on the list, click and give all the information is there.
I too had both OWIN as well as my WebAPI that both apparently needed CORS enabled separately which in turn created the 'Access-Control-Allow-Origin' header contains multiple values error.
I ended up removing ALL code that enabled CORS and then added the following to the system.webServer node of my Web.Config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://stethio.azurewebsites.net" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
</customHeaders>
</httpProtocol>
Doing this satisfied CORS requirements for OWIN (allowing log in) and for WebAPI (allowing API calls), but it created a new problem: an OPTIONS method could not be found during preflight for my API calls. The fix for that was simple--I just needed to remove the following from the handlers node my Web.Config:
<remove name="OPTIONSVerbHandler" />
Hope this helps someone.
Actually you cannot set multiple headers Access-Control-Allow-Origin (or at least it won't work in all browsers). Instead you can conditionally set an environment variable and then use it in Header directive:
SetEnvIf Origin "^(https?://localhost|https://[a-z]+\.my\.base\.domain)$" ORIGIN_SUB_DOMAIN=$1
Header set Access-Control-Allow-Origin: "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
So in this example the response header will be added only if a request header Origin matches RegExp: ^(https?://localhost|https://[a-z]+\.my\.base\.domain)$ (it basically means localhost over HTTP or HTTPS and *.my.base.domain over HTTPS).
Remember to enable setenvif module.
Docs:
http://httpd.apache.org/docs/2.2/mod/mod_setenvif.html#setenvif
http://httpd.apache.org/docs/2.2/mod/mod_headers.html#header
BTW. The }e in %{ORIGIN_SUB_DOMAIN}e is not a typo. It's how you use environment variable in Header directive.
This happens when you have Cors option configured at multiple locations. In my case I had it at the controller level as well as in the Startup.Auth.cs/ConfigureAuth.
My understanding is if you want it application wide then just configure it under Startup.Auth.cs/ConfigureAuth like this...You will need reference to Microsoft.Owin.Cors
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
If you rather keep it at the controller level then you may just insert at the Controller level.
[EnableCors("http://localhost:24589", "*", "*")]
public class ProductsController : ApiController
{
ProductRepository _prodRepo;
if you are in IIS you need to activate CORS in web.config, then you don't need to enable in App_Start/WebApiConfig.cs Register method
My solution was, commented the lines here:
// Enable CORS
//EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
//config.EnableCors(cors);
and write in the web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
just had this problem with a nodejs server.
here is how i fixed it.
i run my node server through a nginx proxy and i set nginx and node to both allow cross domain requests and it didnt like that so i removed it from nginx and left it in node and all was well.
This can also happen of course if you've actually set your Access-Control-Allow-Origin header to have multiple values - For example, a comma separated list of values, which is kind of supported in the RFC but isn't actually supported by most major browsers. Note that the RFC talks about how to allow more than one domain without using '*' as well.
For example, you can get that error in Chrome by using a header like so:
Access-Control-Allow-Origin: http://test.mysite.com, http://test2.mysite.com
This was in Chrome Version 64.0.3282.186 (Official Build) (64-bit)
Note that if you're considering this because of a CDN, and you use Akamai, you may want to note that Akamai wont cache on the server if you use Vary:Origin, the way many suggest to solve this problem.
You'll probably have to change how your cache key is built, using a "Cache ID Modification" response behavior. More details on this issue in this related StackOverflow question
So stupid and simple:
This problem occurred for me when having two time Header always set Access-Control-Allow-Origin * inside my Apache config file. Once withing the VirtualHost tags and once inside a Limit tag:
<VirtualHost localhost:80>
...
Header set Access-Control-Allow-Origin: *
...
<Limit OPTIONS>
...
Header set Access-Control-Allow-Origin: *
...
</Limit>
</VirtualHost>
Removing one entry resolved the issue.
I guess in the original post it would have been two times:
Header set Access-Control-Allow-Origin: "http://127.0.0.1:9000"
The 'Access-Control-Allow-Origin' header contains multiple values
when i received this error i spent tons of hours searching solution for this but nothing works, finally i found solution to this problem which is very simple.
when ''Access-Control-Allow-Origin' header added more than one time to your response this error occur, check your apache.conf or httpd.conf (Apache server), server side script, and remove unwanted entry header from these files.
For only Spring Boot :
This occurs because u might be using the
#CrossOrigin(origins = "http://localhost:4200")
twice in the application or else, you might be using :
#CrossOrigin(origins = "*")
The browsers do not support it.Check here for more details on it
please specify the Url even in the security config :
#Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE"));
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Then Add this in the Http security configure :
.and().cors().configurationSource(corsConfigurationSource());
I have faced the same issue. The reason in my case was that I had the wrong NGINX configuration for reverse proxy (which I used for the Docker container with node.js app).
add_header 'Access-Control-Allow-Origin' '*'
So for those who are using VMs and docker, there are more places where issues are possible to occur.
I have faced the same issue and this is what I did to resolve it:
In the WebApi service, inside Global.asax I have written the following code:
Sub Application_BeginRequest()
Dim currentRequest = HttpContext.Current.Request
Dim currentResponse = HttpContext.Current.Response
Dim currentOriginValue As String = String.Empty
Dim currentHostValue As String = String.Empty
Dim currentRequestOrigin = currentRequest.Headers("Origin")
Dim currentRequestHost = currentRequest.Headers("Host")
Dim currentRequestHeaders = currentRequest.Headers("Access-Control-Request-Headers")
Dim currentRequestMethod = currentRequest.Headers("Access-Control-Request-Method")
If currentRequestOrigin IsNot Nothing Then
currentOriginValue = currentRequestOrigin
End If
If currentRequest.Path.ToLower().IndexOf("token") > -1 Or Request.HttpMethod = "OPTIONS" Then
currentResponse.Headers.Remove("Access-Control-Allow-Origin")
currentResponse.AppendHeader("Access-Control-Allow-Origin", "*")
End If
For Each key In Request.Headers.AllKeys
If key = "Origin" AndAlso Request.HttpMethod = "OPTIONS" Then
currentResponse.AppendHeader("Access-Control-Allow-Credentials", "true")
currentResponse.AppendHeader("Access-Control-Allow-Methods", currentRequestMethod)
currentResponse.AppendHeader("Access-Control-Allow-Headers", If(currentRequestHeaders, "GET,POST,PUT,DELETE,OPTIONS"))
currentResponse.StatusCode = 200
currentResponse.End()
End If
Next
End Sub
Here this code only allows pre-flight and token request to add "Access-Control-Allow-Origin" in the response otherwise I am not adding it.
Here is my blog about the implementation: https://ibhowmick.wordpress.com/2018/09/21/cross-domain-token-based-authentication-with-web-api2-and-jquery-angular-5-angular-6/
for those who are using IIS with php,
on IIS it server side update web.config file it root directory (wwwroot) and add this
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<directoryBrowse enabled="true" />
<httpProtocol>
<customHeaders>
<add name="Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
after that restart IIS server,
type IISReset in RUN and enter
Here's another instance similar to the examples above that you may only have one config file define where CORS is: There were two web.config files on the IIS server on the path in different directories, and one of them was hidden in the virtual directory.
To solve it I deleted the root level config file since the path was using the config file in the virtual directory.
Have to choose one or the other.
URL called: 'https://example.com/foo/bar'
^ ^
CORS config file in root virtual directory with another CORS config file
deleted this config other sites using this
I had this issue because I add in the my webconfig project and also webconfig endpoint this config:
<add name="Control-Allow-Origin" value="*"/>.
When I remove <add name="Control-Allow-Origin" value="*"/> from webconfig endpoint the problem was solved.

CORS issue with SignalR - Origin not allowed

So I've read up on all the previous questions on this, but following the steps don't seem to be working for me. I'm getting the "Origin * is not allowed by Access-Control-Allow-Origin", but that doesn't make sense to me. If I open the same request in Chrome in it's own tab, and look at the network tab, I see the following CORS headers intact. Also, the hubs generate just fine. I'm using Web API, .NET 4.5, and the rc2 of SignalR. I also tried removing the Allow-Credentials in the web.config, but that didn't help either.
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:x-requested-with,X-CustomAuth,Content-Type,X-Impersonate
Access-Control-Allow-Methods:GET,OPTIONS,PUT,DELETE,HEADER
Access-Control-Allow-Origin:*
I've also set jQuery.support.cors to true, even though it was already as true, I'm using JQuery 1.9, and here's my connection to the server and hub:
jQuery.support.cors = true;
$.connection.hub.url = 'http://myserver/api/signalr';
$.connection.hub.start({ transport: 'longPolling', xdomain: true });
I've also tried this to connect, both with same issue.
$.connection('http://myserver/api/signalr/echo').start(function () {
console.log('Connected');
$.connection.hub.start().done(function() {
$log.info('Connected to hub.');
});
});
The * value cannot be used with the Access-Control-Allow-Origin header if Access-Control-Allow-Credentials is true. Try either one of the following:
Drop the Access-Control-Allow-Credentials header entirely.
Change the value of the Access-Control-Allow-Origin from * to the actual value of the Origin header.
#1 might be easier to do, but #2 is required if you need to support cookies.
According to the official doc, you should NOT be using jQuery.support.cors
Don't set jQuery.support.cors to true in your code.
Link to the official doc: official doc

Refused to set unsafe header "Origin" when using xmlHttpRequest of Google Chrome

Got this error message:
Refused to set unsafe header "Origin"
Using this code:
function getResponse() {
document.getElementById("_receivedMsgLabel").innerHTML += "getResponse() called.<br/>";
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", "http://L45723:1802", true, "server", "server123"); //must use L45723:1802 at work.
receiveReq.onreadystatechange = handleReceiveMessage;
receiveReq.setRequestHeader("Origin", "http://localhost/");
receiveReq.setRequestHeader("Access-Control-Request-Origin", "http://localhost");
receiveReq.timeout = 0;
var currentDate = new Date();
var sendMessage = JSON.stringify({
SendTimestamp: currentDate,
Message: "Message 1",
Browser: navigator.appName
});
receiveReq.send(sendMessage);
}
}
What am I doing wrong? What am I missing in the header to make this CORS request work?
I tried removing the receiveReq.setRequestHeader("Origin", ...) call but then Google Chrome throws an access error on my receiveReq.open() call...
Why?
This is just a guess, as I use jquery for ajax requests, including CORS.
I think the browser is supposed to set the header, not you. If you were able to set the header, that would defeat the purpose of the security feature.
Try the request without setting those headers and see if the browser sets them for you.
In CORS the calling code doesn't have to do any special configuration. Everything should be handled by the browser. It's the server's job to decide if request should be allowed or not. So any time you are making a request which breaks SOP policy, the browser will try to make a CORS request for you (it will add Origin header automatically, and possibly make a preflight request if you are using some unsafe headers/methods/content types). If the server supports CORS it will respond properly and allow/disallow the request by providing CORS specific response headers like
Access-Control-Allow-Origin: *
Keep in mind that Chrome is very restrictive about 'localhost' host name. (At least it was when I was working with it). Instead use your computer name or assign it another alias in 'hosts' file. So for example don't access your site like:
http://localhost:port/myappname
Instead use:
http://mymachinename:port/myappname
or
http://mymachinealias:port/myappname
For more details please check specification.
Are you working cross-domain?
Try Brian S solution or try this:
instead of setting to localhost just pass anything... and see what happens.
receiveReq.setRequestHeader("Origin", "*");

Code Igniter Login, Session and Redirect Problem in Internet Explorer?

I'm still new to code igniter and I'm having problems getting the login system to work.
The login always works when I use Firefox. The login consistently works on some IE7 browsers but consistently fails on other IE7 browsers.
When tracing the code, I see that the models/redux_auth_model.php does successfully authenticate the user, it writes user information into the $this->session->set_userdata() and it redirect them to a member's page of my choosing. Here's the code:
public function login($identity = false, $password = false)
{
$identity_column = $this->config->item('identity');
$users_table = $this->tables['users'];
if ($identity === false || $password === false || $this->identity_check($identity) == false)
{
return false;
}
$query = $this->db->select($identity_column.', email, password, group_id')
->where($identity_column, $identity)
->where('active', 'Active')
->limit(1)
->get($users_table);
$result = $query->row();
if ($query->num_rows() == 1)
{
//$password = $this->hash_password_db($identity, $password);
if (!empty($result->activation_code)) { return false; }
if ($result->password === $password)
{
$this->session->set_userdata($identity_column, $result->{$identity_column});
$this->session->set_userdata('email', $result->email);
$this->session->set_userdata('group', $result->group_id);
return true;
}
}
return false;
}
I did a variable dump of $this->session in both IE7 and FF and confirmed that all the userdata is intact before the redirect. The session had my email information, group information and $identity_column information.
However, after the redirect, the session data is empty on some IE7 browsers, which is why CI keeps booting me out of the system. It's fully intact on other IE7 browsers and always intact in Firefox.
Why would session data be browser dependent?
Any ideas on how to troubleshoot this further? I am baffled...
It is a frustrating problem with the Codeigniter database session class, in the end I resorted to using native sessions using the drop-in replacement found here: https://github.com/EllisLab/CodeIgniter/wiki/Native-session
I was having the same problem while using CI Session in IE. Then I use the below header in controller constructor and it works for me.
Here is the header:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
I faced the same problem while using IE8 with browser mode. I've found the problem is in matching the user agent. In session database it saves useragent as IE7 but from cookie it gets IE8. I've set $config[sess_match_useragent] = FALSE and the problem is solved.
The session class works fine in several of my projects including IE6/7/8 support (including multiple releases of CI). There are a few things that might be causing this, outside of the code pasted above:
Calling $this->session->sess_create(); from a baseclass (or elsewhere in your class's code) would reset your session.
Try combining your set_userdata calls to one call by passing it an array.
Make sure your data does not have any unexpected characters in it (this can cause issues in certain browsers).
Make sure your session class settings in the config are not rolling over the cookie every request.
Alternatively, consider an alternate session class like Native sessions
This is an issue that someone made a 3rd party fix for, it patches the session controller. Let me dig it up. I have used it in my codeigniter setups since it was first noted.
This issue is IE7/IE8 specific with redirects or frames.
EDIT
Here is the reference that I have found before, it helped me with the IE issue. Hopefully this is what is causing you headaches:
http://www.philsbury.co.uk/blog/code-igniter-sessions
It's a problem with browsers. I put this in MY_Controller in constructor:
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
for example:
if($this->uri->segment(1)=='admin') header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
We were developing an app involving a Facebook tab when we ran into this problem. We tried the above to no avail. Here's what we found out:
IE privacy settings seem to have to be medium or less
If your running a page app, make sure BOTH URL's have HTTPS protocol in them
Also, look into the Compact Privacy Policy for cookies.
config file application config.php
// 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
$config['cookie_secure'] = FALSE;
I solved this by using native php session instead of cookies (Storing codeigniter session_id in php native session).
You can grab library here: https://github.com/staskus/codeigniter-2.--native-session.
Just copy MY_Session.php file into applications/libraries
The problem is IE denying the cookie CI is trying to set. Native sessions is one way, however if you want to keep using CI sessions I have had success with the following troubleshooting:
Check that setting $config['cookie_domain'] in config.php is not empty
Remove the underscore from $config['sess_cookie_name'], for example change "ci_session" to "cisession"
Check that the server time is correct
I hate IE !!!
its working now giving P3P to our controllers fix the problem :
class Chupacabra extends CI_Controller {
function __construct() {
parent::__construct();
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
This issue plagued me when I was trying get a login page to work in CodeIgnitor. The session would not save.
It turns out that it was due to a domain name that I created from FREEDNS that contained an underscore (_). I renamed the domain name using a period (.) and reverted all the code changes that were suggested in this post, and Voila, it worked.
Thanks for all the comments and contributions on this page because they really led me down the road of investigating that darn underscore.

Resources