php小记

212 阅读3分钟

安装

mac默认安装有php环境

启动

1 创建项目

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php
        echo "Hello world!<br>";
        echo "我要学 PHP!<br>";
    ?>
</body>
</html>

2 配置hosts

vi /etc/hosts 添加 127.0.0.1:xxxx www.php.com

3 配置nginx

vi php.com.conf

server {
    listen xxxx;
    server_name www.php.com;
    charset utf-8;

    error_page 404 /404.html;
    error_page 500 502 503 504  /busy.html;

    client_max_body_size 10m;
    client_body_timeout 900s;

    access_log  /tmp/php.com.log;
    error_log /tmp/php.com.error.log;

    root /Users/zhenghuihuang/Documents/Project/php;
    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

sudo nginx -t
sudo nginx -s reload
sudo php-fqm

如果提示 failed to open configuration file '/private/etc/php-fpm.conf'
1.添加配置 
    cp /private/etc/php-fpm.conf.default /private/etc/php-fpm.conf 
    修改 error_log配置项(默认被注释,需要取消配置) 
    改成  error_log = /usr/local/var/log/php-fpm.log 

2.添加网站配置
    /private/etc/php-fpm.d
    cp www.conf.default www.conf
    给用户名和权限组
    sudo www.conf
    user = zhenghuihuang
    group = staff

laravel框架

安装

1 通过composer安装,先安装composer
curl  -sS  https://getcomposer.org/installer  |  php

2 安装laravel,并创建项目
composer create-project --prefer-dist laravel/laravel laravel

允许跨域

1. 新建一个跨域中间件 /app/http/Middleware/core.php

2. 设定请求头部信息 core.php

<?php
namespace App\Http\Middleware;

use Closure;

class AllowOrigin
{
    /**
     *
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Methods: *");
        header("Access-Control-Allow-Headers: Content-Type,Access-Token");
        header("Access-Control-Expose-Headers: *");

        return $next($request);
    }
}
?>

3. 在Kernel.php中注册新加的中间件

protected $middlewareGroups = [
    'api' => [
        'cors',
    ],
];

protected $routeMiddleware = [
    'cors' => \App\Http\Middleware\AllowOrigin::class,
],

4. 在路由中使用

Route::group(['middleware' => ['cors']], function () {
    Route::get('/get', function () {
        return json_encode(["code" => 200, "data" => []]);
    });
});

php artisan serve 本地启动项目

接口处理

/public/index.html
1. 发送请求
axios.get("/api/user", { params: { name: "我是郑辉煌", age: 25 } })

2. 新建一个控制器 /app/Http/UserController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function getuser(Request $request) 
    {
        $name = $request->get('name');
        return $this->successRes(['name' => $name], '请求成功');
    }
}

successRes() 接口返回格式可以统一在Controllers控制器中定义,全局通用
$this->successRes();返回给客户端处理好的数据

App\Http\Controllers.php

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function successRes(array $data = [], string $msg = "处理成功")
    {
        $data = ['code' => 200, 'data' => $data, 'msg' => $msg];
        return response()->json($data, 200);
    }

    public function failRej(array $data = [], string $msg = "处理错误")
    {
        $data = ['code' => 200, 'data' => $data, 'msg' => $msg];
        return response()->json($data, 200);
    }
}


3. 监听请求 /routes/api.php
Route::get("/user", "UserController@getuser");
参数一 
    接口名称,在spi.php中,默认会带上/api前缀
参数二 
    UserController 新建的处理控制器
    getuser 控制器中的对应处理方法

数据库

创建模型和数据迁移
Xxx 表名首字母需要大写
php artisan make:model Xxx -m

/database/migrations/user_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('age');
            $table->integer('sex');
            $table->string('star');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

运行迁移,会在数据库中生成user表
php artisan migrate
插入字段迁移数据
php artisan make:migration add_xxx_to_yyy_table
xxx 插入的字段
yyy 插入的表
生成迁移表后输入要添加的字段,执行迁移即可
php artisan migrate
在控制器中使用数据库模型
/app/Http/Controllers/UserController
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function postuser(Request $request)
    {
        $user = new User();
        $user->name = $request->get('name');
        $user->age = $request->get('age');
        $user->star = $request->get('star');
        $user->sex = $request->get('sex');
        $user->save();
        return $this->successRes(['user' => $user], '注册成功');
    }

    public function getuser(Request $req)
    {
        $id = $req->get('id');
        $user = new user();
        $data = $user->find($id);
        return $this->successRes(['user' => $data], '查询成功');
    }
}

php标记

<?php 如果全是php代码可以省略结束标记

数据类型

boolean (布尔)  integer (整数) float (浮点数double) string (字符串)
复合类型
array (数组)  object (对象) callable (可调用, callback调用类型)
特殊类型
resource (资源)  NULL (无类型)

var_dump() 打印出对象或表达的类型,无返回值
var_export() 输出或返回一个变量的字符串表示
print_r() 打印出易于理解的变量

echo 只能打印变量类型,无法打印符合类型
var_export() 接收一个变量,可再传入一个true,表示可以有返回值 

数组

数值数组
<?php
    $cars=array("Volvo","BMW","Toyota");
    $arrlength=count($cars);
    
    数值数组遍历
    for($x=0;$x<$arrlength;$x++)
    {
        echo $cars[$x];
        echo "<br>";
    }
?>

关联数组

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

关联数组遍历
foreach($age as $x=>$value)
{
    echo "Key=" . $x . ", Value=" . $value;
    echo "<br>";
}
?>

数组方法

count($arr) 数组长度  sort ($arr) 对数组进行升序   rsort($arr) 对数组进行贾诩
asort($arr) 根据数组的值进行升序   ksort($arr) 根据数组的键进行升序
arsort($arr) 根据数组的值进行降序   krsort($arr) 根据数组的键进行降序

变量检验

gettype() 检验类型
is_type() 检测是否某个类型 
is_int() 整数  is_bool() 波尔  is_string() 字符串   is_float() 浮点数  is_numeric() 数字  is_object() 对象   is_array() 数组

php与js不同,定义变量不需要有声明字符,let var $(变量名)即可

变量作用域

    local 函数内部,可省略
    global 全局范文
    static 函数执行完不删除变量
    parameter 参数使用
在函数中直接使用全局变量可以通过 global 关键字声明或者通过 php 中自定义的 $GLOBALS 数组获取:

超级全局变量

在一个脚本的全部作用域中都可以使用,不需要特别说明
$GLOBALS
是一个包含了全部变量的全局组合数组。变量的名字就是数组的键
```
<?php 
    $x = 75; 
    $y = 25;
     
    function addition() 
    { 
        $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; 
    }
     
    addition(); 
    echo $z; 
?>
实例中 z 是一个$GLOBALS数组中的超级全局变量,该变量同样可以在函数外访问

$_SERVER 
    是一个包含了诸如头信息(header)、路径(path)、以及脚本位置(script locations)等等信息的数组。这个数组中的项目由 Web 服务器创建。
$_REQUEST 用于收集HTML表单提交的数据
$_POST 
    被广泛应用于收集表单数据,在HTML form标签的指定该属性:"method="post"
$_GET 
    同样被广泛应用于收集表单数据,在HTML form标签的指定该属性:"method="get"
    也可以收集URL中发送的数据
    通过$_GET[参数名] 可以获取到url中对应参数的值
$_FILES
$_ENV
$_COOKIE
$_SESSION