Home >Backend Development >PHP Tutorial >PHP solves cross-domain issues

PHP solves cross-domain issues

angryTom
angryTomOriginal
2019-08-23 09:05:525365browse

PHP solves cross-domain issues

In the front-end, it always seems so disgusting when solving cross-domain problems. What about jsonp, ajax, CORS, etc. I always feel that I am taking advantage of loopholes to carry out cross-domain. In fact, in You only need to add a piece of code in the PHP file to cross-domain. You can write the front-end however you want. Post and get can be used casually.

Recommended tutorial: PHP video tutorial

PHP solves cross-domain problems by adding them to the PHP file Three request headers are enough.

header("Access-Control-Allow-Origin:*"); // Specify to allow other domain names to access

header('Access -Control-Allow-Methods:POST'); // Response type

header('Access-Control-Allow-Headers:x-requested-with, content-type'); // Response Header settings

<?php
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 响应类型
header(&#39;Access-Control-Allow-Methods:POST&#39;);
// 响应头设置
header(&#39;Access-Control-Allow-Headers:x-requested-with, content-type&#39;);
 
//$callback = isset($_REQUEST[&#39;callback&#39;]) ? trim($_REQUEST[&#39;callback&#39;]) : &#39;&#39;; //jsonp回调参数,必需
function getKey($key,$default=""){
    return trim(isset($_REQUEST[$key])?$_REQUEST[$key]:$default);
}
$id = getKey("id");
$conn = mysqli_connect("localhost","root","","test") or die("连接失败");
$conn->query("set names utf8");
$sql = "select * from data where ".$id." is not null";
$result = $conn->query($sql);
$arr = [];
while($row=$result->fetch_assoc()){
    array_push($arr,json_encode($row));
}
$json = json_encode($arr);  //json 数据
print_r($json);

The above is the detailed content of PHP solves cross-domain issues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn