Question

I'm serving content for public websites and I'm wondering whether there would be any implications on using both CORS and JSONP for maximum browser support. For instance, I would be doing this:

<?php

// Simplified example to illustrate

if(isset($_GET['callback'])) {
    header('Content-Type: application/javascript; charset=utf-8');
    echo $_GET['callback'] . '(' . json_encode( ... ) . ')';
    exit;
}

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=utf-8');

echo json_encode( ... );

Obviously I'm not sending the CORS-related headers with the JSONP response as that seems counter-intuitive. Are there any security or other implications with this method?

Was it helpful?

Solution

Considering CORS is here to stay, I'd propose switching the order in which you are sending out data.

  1. Detect CORS support
  2. If CORS is supported, send your application/json response
  3. If CORS is not supported, fallback to JSONP (IE<=7, Opera<12, or Firefox<3.5)

This way you get to redeem the best of the more secure method and fall back to the other for non-compliant clients.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top