2025-06-18

在sites/default/settings.php中加入

$config['system.logging']['error_level'] =  'verbose';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('error_reporting', E_ALL);
$settings['http_client_config']['verify'] = false;
标签: Drupal
2025-06-03
// 自动加载 Command 目录下的所有命令
$commandPath = __DIR__.'/../src/Command';
$namespace = 'App\\Command\\';

foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($commandPath)) as $file) {
    if ($file->isFile() && $file->getExtension() === 'php') {
        $class = $namespace . str_replace(
            ['/', '.php'],
            ['\\', ''],
            substr($file->getPathname(), strlen($commandPath) + 1)
        );

        if (class_exists($class)) {
            $reflection = new ReflectionClass($class);
            if (!$reflection->isAbstract() && $reflection->isSubclassOf('Symfony\\Component\\Console\\Command\\Command')) {
                $application->add(new $class());
            }
        }
    }
}
标签: PHP
2025-05-16

https://github.com/P3TERX/GeoLite.mmdb?tab=readme-ov-file

下载GeoLite2-Country.mmdb

$ mkdir ip
$ cd ip
$ composer init
$ composer require geoip2/geoip2
$ touch index.php

<?php

include './vendor/autoload.php';
use GeoIp2\Database\Reader;

$ip = $_GET['ip'] ?? '';
if ($ip) {
    $geoip = new Reader('GeoLite2-Country.mmdb');
    $reader = $geoip->country($ip);
    print_r(json_encode($reader->jsonSerialize()));
} else {
    print_r(json_encode([]));
}
标签: PHP
2025-04-14

方法1

将downloads目录下面的reviews.csv插入到reviews表. 并忽略第一行. 以\r\n为换行

LOAD DATA LOCAL INFILE
'Users/xiukun/Downloads/reviews.csv'INTO TABLE steam reviews
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\r\n"
IGNORE 1 LINES
(afield, bfield, cfield)

 

方法2

使用mysqlimport

mysqlimport --ignore-lines=1 \
            --fields-terminated-by=, \
            --local -u root \
            -p Database \
             TableName.csv
 

 

标签: mysql
2025-04-14

当我们需要1000万条测试数据 导入到mysql昨办?我们可以直接从这里来找到想要的测试数据,有几十GB的

https://www.kaggle.com/datasets

 

标签: 其它
2025-04-14

创建一个新项目

$ laravel new api_example

 

添加认证包,在用户登陆成功以后返回一个token. 

$ composer require laravel/sanctum

 

创建一个api的Controller

$ php artisan make:controller api/UserController --api

 

创建登陆接口

use App\Http\ApiBase;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends ApiBase
{
   /**
     * User login api.
     *
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request) {
        if (Auth::attempt([
            'username' => $request->get('username'),
            'password' => $request->get('password')
        ])) {
            $authUser = Auth::user();
            $success['token'] =  $authUser->createToken('example')->plainTextToken;
            $user_info = $authUser->toArray();
            $success['info'] = $user_info;

            return $this->responseSuccess($success);
        } else {
            return $this->responseError('Unauthorised', 401);
        }
    }

}

 

创建用户模型models/User.php

<?php

namespace App\Models;

use App\Http\BaseModel;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

/**
 * Class User.
 */
class User extends BaseModel implements AuthenticatableContract
{
    use Authenticatable;
    use HasApiTokens, HasFactory, Notifiable;

    public $timestamps = false;
    public $hidden = ['password'];

    protected $fillable = ['password', 'grade', 'name', "gender", "mobile", "email", "wechat", "qq", "url", "remark", "setting"];

    protected $primaryKey = 'user_id';

    protected $table = 'user';

}

 

创建路由routers/api.php.

use Illuminate\Support\Facades\Route;

// 不需要权限
Route::post('/user/login', [\App\Http\Controllers\api\UserController::class, 'login']);

// 以下接口都需要权限
Route::group(['namespace' => 'App\Http\Controllers\api', 'middleware' => 'auth:sanctum'], function() {

    // user.
    Route::post('/user/update/{id}', 'UserController@update');
    Route::post('/user/update_self', 'UserController@update_self');
    Route::get('/user/show/{id}', 'UserController@show');
    Route::get('/user/info', 'UserController@info');
    Route::get('/user/list', 'UserController@index');

});

 

 

 

标签: Laravel
2025-04-14

遇到一个问题。老系统的密码是用md5加密。现在要用Laravel读取老系统数据库并编写API. 这就需要修改密码验证器了。

打开config/auth.php

将users.driver 修改为custom

    'providers' => [
        'users' => [
            'driver' => 'custom',
            'model' => env('AUTH_MODEL', App\Models\User::class),
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

进入bootstrap/providers.php 增加一个providers

<?php

return [
    ....,
    App\Providers\AuthServiceProvider::class,
];

 

创建文件app/Providers/AuthServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application authentication / authorization services.
     *
     * @return  void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('custom', function ($app, array $config) {

            // Return an instance of Illuminate\Contracts\Auth\UserProvider...
            return new AuthProvider();
        });
    }
}

 

然后再创建AuthProvider.app/Providers/AuthProvider.php

<?php
namespace App\Providers;

use App\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;

class AuthProvider implements UserProvider
{
    public function retrieveById($identifier) {
        return Administrator::find($identifier)->first();
    }
    public function retrieveByToken($identifier, $token) {
    }
    public function updateRememberToken(Authenticatable $user, $token) {
        return $user->setRememberToken($token);
    }
    public function retrieveByCredentials(array $credentials) {
        if (empty($credentials)) {
            return;
        }
        $user = User::where('username', $credentials['username'])->first();
        return $user;
    }
   // 此处为自定义认证
    public function validateCredentials(Authenticatable $user, array $credentials) {
        return md5($credentials['username'] . md5($credentials['password'])) == $user->getAuthPassword();
    }
    public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false) {
    }

}

 

标签: Laravel
2025-04-14

也可以使用此包: https://github.com/symfony/mime

function check_is_img($file) {
    $maps = [
        'jpeg' => ['image/jpeg', 'image/pjpeg'],
        'jpg' => ['image/jpeg', 'image/pjpeg'],
        'png' => ['image/png', 'image/apng', 'image/vnd.mozilla.apng'],
        'gif' => ['image/gif'],
    ];

    // get mime type.
    $image_mime = mime_content_type($file);

    // get ext.
    $ext = pathinfo($file, PATHINFO_EXTENSION);

    if (!isset($maps[$ext])) {
        return false;
    }

    $file_mine = $maps[$ext];
    return in_array($image_mime, $file_mine);
}

$file = './test_php.png';
var_dump(check_is_img($file));

 

标签: PHP
2025-04-14

定义一个类

$obj = new class() {
    public function getUser($id) {
        if ($id == 2) {
            return $this;
        }
        return null;
    }
    public function getName() {
        return 'xiukun';
    }
};

 

像以前的做法想要获取name会一层一层的判断下来

if (is_null($obj)) {
    $name = null;
} else {
    $user = $obj->getUser(5);

    if (is_null($user)) {
        $name = null;
    } else {
        $name = $user->getName();
    }
}

 

使用空运算符

$name = $obj?->getUser(1)?->getName();

 

 

标签: PHP
2025-04-14
$ composer require symfony/http-foundation

Drupal自带这个包并不需要安装

 

include_once "./vendor/autoload.php";
$header = [
    'Content-Encoding'    => 'UTF-8',
    'Content-Type'        => 'text/csv;charset=UTF-8',
    'Content-Disposition' => "attachment;filename=\"mycsv.csv\"",
];
$response = new \Symfony\Component\HttpFoundation\StreamedResponse(function() {
    $handle = fopen('php://output', 'w');
    // 这里查询你的数据库和设置csv记录.
    while (true) {
        fputcsv($handle, ['a', 'b', 'c']);
    }
    fclose($handle);
}, 200, $header);
$response->send();
exit();

 

方法2原生的PHP

header('Content-Encoding: UTF-8');
header('Content-Type: text/csv;charset=UTF-8');
header('Content-Disposition: attachment;filename="mycsv.csv"');
$handle = fopen('php://output', 'w');
// 这里查询你的数据库和设置csv记录.
while (true) {
    fputcsv($handle, ['a', 'b', 'c']);
}
fclose($handle);

 

标签: PHP