允许指定ip或域名

    $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
    $allow_origin = array(
        'http://XXX',
        'http://YYY',
        'http://ZZZ',
        'http://GGG',
    );
    if(in_array($origin, $allow_origin)){
        header('Access-Control-Allow-Origin:'.$origin);
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }

跨域上传文件

    $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
    header('Access-Control-Allow-Origin:'.$origin);
    //判断请求,options是浏览器的跨域运行判断请求,只发送header
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
//            print_r($_SERVER);
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Headers: X-Requested-With');
        header('Access-Control-Allow-Headers: Content-Type');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
        header('Access-Control-Max-Age: 86400');
        exit; //结束,只需要返回头部即可
    }