PHP solves cross-domain issues

angryTom
Release: 2023-04-07 09:26:02
Original
5314 people have browsed it

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!