PHP搭建服务器
1.phpstudy创建PHP项目
启动Apache和MySQL
点击左侧网站,创建网页。注意到程序类型就是PHP,这里是创建PHP项目。
<!-- 域名可以任意填写 -->
www.test02.com
//端口号最好改8082以免撞了
<!-- 根目录是自动创建的,也可以自己选择 -->
点击创建数据库,如果现在不选,可以到数据库去新建。
点击高级配置,网站首页设置成index.php。然后就可以点击确认了。
网站首页: index.php index.html error/index.html
<!-- 改为 -->
index.php index.html error/index.php
<!-- 设置完成后可以点击phpstudy的页面管理打开页面。 -->
<!-- 也可以复制路径,本地接口+路径在浏览器打开 -->
http://localhost/error/index.php
http://localhost/ + error/index.php//不知道可以从phpstudy网站首页设置复制
2.配置php文件
打开index.php,设置跨域配置,完成后前端才能访问。
跨域配置
header('Content-type:text/html;charset=utf-8');// 配置json
header("Access-Control-Allow-Origin:true");// 跨域配置允许访问,Access-Control-Allow-Origin:
// header("Access-Control-Allow-Origin: *");使用通配符允许所有站点访问私有API是显而易见的坏主意。
header("Access-Control-Allow-Origin: http://localhost:8080");// 指定域名,写入域名头,只让本地8080端口访问,为了安全
测试运行和访问
<?php
header('Content-type:text/html;charset=utf-8');
header("Access-Control-Allow-Origin:true");
header("Access-Control-Allow-Origin: http://localhost:8080");
//测试用的数组
$res = array(
"name" => "tom",
"age" => "18"
);
echo json_encode($res);//返回给前端的
<!-- 如果未设置跨域访问会返回报错: -->
已拦截跨源请求:同源策略禁止读取位于 http://localhost/error/index.php 的远程资源。(原因:CORS 头 'Access-Control-Allow-Origin' 不匹配 'true')。
链接指定数据库进行操控
<?php
header('Content-type:text/html;charset=utf-8');
header("Access-Control-Allow-Origin:true");
header("Access-Control-Allow-Origin: http://localhost:8080");
$link=@mysqli_connect('localhost','root','密码','test01',3306)or die('数据库连接失败');
mysqli_set_charset($link,'utf8');
// 接口测试
$sql = "select * from students";//SQL语句赋值给变量sql
$select = mysqli_query( $link, $sql );//执行SQL语句函数复制给变量select
$data = array();//用于返回前端的数组,也以防报错
while($getsel = mysqli_fetch_assoc($select)){
$data[] = $getsel;
}
//mysqli_fetch_assoc函数获取数据
echo json_encode($data);//返回给前端
// 操作结束关闭数据库
mysqli_close($link);