顯示具有 PHP 標籤的文章。 顯示所有文章
顯示具有 PHP 標籤的文章。 顯示所有文章

2024/01/24

Lumen 撰寫類似Laravel 產生序號Command

Console/Kernel配置:
<?php

namespace App\Console;

use App\Console\Commands\GenerateKeyCommand;
use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        GenerateKeyCommand::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //
    }
}

2023/08/30

Laravel 9 Google 2FA(Two-factor authentication)

2FA全名為「Two-factor authentication」,中文稱為「雙重驗證」
兩種不同的元素,合併在一起,來確認使用者的身分。
有兩種密碼演算法
HOTP(HMAC-based One-time Password),RFC4226
金鑰和隨機資訊雜湊後,取N個字作為密碼
TOTP(Time-Based One-Time Password),RFC6238
透過時間來產生一次性密碼
邏輯如下:
呼叫API時先進到Verify2FA這個Middleware
檢查是否有使用帳號密碼登入過,沒有則讓他呼叫API
登入後如果2FA金鑰為空,回傳錯誤訊息,讓Front-End轉跳到顯示QRCode頁面
進入頁面呼叫get2FAQRCodeUrl,Front-End將URL轉成QRCode Image,接著使用者掃完後下一步
開始驗證2FA,驗證通過在Session儲存twoFAChecked為true
登入後如果還沒驗證過2FA,回傳錯誤訊息,讓Front-End轉跳到顯示輸入2FA驗證頁面
登出後將Session清空
首先安裝google2fa-laravel套件
composer require pragmarx/google2fa-laravel

Laravel 9 限制IP登入

之前被要求要做到的功能,後面又棄用了
routes:
<?php
use Illuminate\Support\Facades\Route;
//限制Admin登入時要符合IP
Route::middleware('limitAdminLoginIP')->group(function () {
	//Admin login
	Route::post('/login', [\App\Http\Controllers\v1\admin\UserController::class, 'login']);
});


app/Http/Kernel.php
<?php

namespace App\Http;

use App\Http\Middleware\LimitAdminLoginIP;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array>
     */
    protected $middlewareGroups = [
        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Illuminate\Session\Middleware\StartSession::class,
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'limitAdminLoginIP' => LimitAdminLoginIP::class,
    ];
}



2023/05/16

PHP Enable Opcache JIT

vim /etc/php/8.2/mods-available/opcache.ini
opcache.jit=on
opcache.jit=1205
opcache.jit_buffer_size=512M
參考資料:https://www.laruence.com/2020/06/27/5963.html

2023/05/11

Laravel API V1/V2

/**
* v1
*/
Route::prefix('v1')->middleware('api')->group(function () {
	    //Test
        Route::get('/test', [\App\Http\Controllers\v1\TestController::class, 'test']);
});
https://localhost/api/v1/test

/**
* v2
*/
Route::prefix('v2')->middleware('api')->group(function () {
	    //Test
        Route::get('/test', [\App\Http\Controllers\v1\TestController::class, 'test']);
});

https://localhost/api/v2/test

參考資料:
https://www.mynotepaper.com/laravel-api-versioning-with-api-key-in-simple-method/
https://medium.com/parenting-tw/custom-api-versioning-route-file-in-laravel-b65e637dfbaf
https://stackoverflow.com/questions/51739960/laravel-api-versioning-folders-structure

composer install --ignore-platform-reqs

有時候PHP的專案所使用的PHP版本可能與當前環境不符,導致無法安裝問題 這時候可以透過下方指令強制進行安裝
composer install --ignore-platform-reqs

2023/04/19

macOS Install PHP Swoole

# Install OpenSSL
brew install openssl

export PATH="/opt/homebrew/opt/openssl@3/bin:$PATH" >> ~/.zshrc
export LDFLAGS="-L/opt/homebrew/opt/openssl@3/lib" >> ~/.zshrc
export CPPFLAGS="-I/opt/homebrew/opt/openssl@3/include" >> ~/.zshrc
source ~/.zshrc

# Install PHP
brew install php

# Install Swoole & Compiler
yes | pecl install swoole

2023/04/18

Ubuntu 22.04 LTS Install MongoDB 6.0 & MongoDB Driver for PHP

記得開啟VT-D的功能,因為MongoDB 5.0後都需要使用到AVX指令集
sudo apt install -y php-pear php8.2-dev
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
curl -LO http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1-1ubuntu2.1~18.04.21_amd64.deb
sudo dpkg -i ./libssl1.1_1.1.1-1ubuntu2.1~18.04.21_amd64.deb
sudo apt-get -y install dialog apt-utils
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt install -y mongodb-org
sudo systemctl enable --now mongod
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

# Install MongoDB driver for PHP
sudo pecl install mongodb
sudo apt install -y php8.2-mongodb

2022/01/17

attempt to perform an operation not allowed by the security policy `PDF' @ error/constitute.c/IsCoderAuthorized/421

#編輯Imageick設定檔
vim /etc/ImageMagick-6/policy.xml

#將下面這行註解

#添加這行
<policy domain="coder" pattern="PDF" rights="read | write">

2022/01/13

NextCloud occ操作

//關閉維護模式
sudo -u www-data php occ maintenance:mode --off
//nextcloud修正apcu
sudo -u www-data php --define apc.enable_cli=1 occ  maintenance:repair
//nextcloud上傳速度不限制
sudo -u www-data php occ config:app:set files max_chunk_size --value 0
sudo -u www-data php occ config:app:set files max_chunk_size --value “size”
//nextcloud取得上傳速度
sudo -u www-data php occ config:app:get files max_chunk_size

2021/12/22

Install NextCloud on CentOS 7.9

安裝相依套件
yum install epel-release -y
yum install nginx php-fpm php-curl php-cli php-mysql php-gd php-common php-xml php-json php-intl php-pear php-imagick php-dev php-common php-mbstring php-zip php-soap php-bz2 mysql-server mysql-client unzip zip snapd -y
修改php-fpm

vim /etc/php-fpm.d/www.conf
user = nginx
group = nginx
listen.owner = nginx
listen.group = nginx
env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp
修改db配置

2020/04/03

Laravel 5.5 @php

@php
$a = 2;
@endphp

Laravel 5.5 css/js cache

再.htaccess內加入下方代碼即可,Cache2天

    <FilesMatch "\.(css|js)$">
    Header set Cache-Control "max-age=172800, public, must-revalidate"
    </FilesMatch>

2020/03/07

Laravel 5.5 Install Bootstrap 4.4.1

首先移除原本的Bootstrap
npm uninstall --save-dev bootstrap-sass


接著安裝Bootstrap4以及popper.js
npm install bootstrap@4.4.1 popper.js --save-dev

2019/03/08

CentOS 7 安裝PhpRedisAdmin再Nginx


首先輸入下方命令安裝套件

# Install EPEL
yum install -y epel-release
# Update Package
yum update -y
# Install PHP PHP-FPM PHP-mbstring Nginx Redis
yum install -y git php php-fpm php-mbstring nginx redis


接著用Git下載PhpRedisAdmin

# Download PhpRedisAdmin
cd /var/www
git clone https://github.com/ErikDubbelboer/phpRedisAdmin.git
cd phpRedisAdmin
git clone https://github.com/nrk/predis.git vendor

修改Nginx

# 修改Nginx設定
vi /etc/nginx/nginx.conf
server_name localhost;

location / {
 root /var/www;
 index index.php;
}

location ~ \.php$ {
 root /var/www;
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_index index.php;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 include fastcgi_params;
}



2017/07/23

Windows 安裝Laravel

先至Composer網站下載Windows安裝檔案
安裝時需指定php.exe所在路徑,指定完成就下一步直到安裝完成


完成後,將php所在資料夾路徑加入至電腦環境變數裡的Path

2015/12/21

PHP session_start() Cannot send session cookie / Cannot send session cache limiter

放假回來時朋友說他更換主機商後出現這個錯誤訊息


session_start() Cannot send session cookie是因為呼叫session_start()的時機必須在網頁內容輸出前,多一個空白也不行
<?php 
session_start();
?>
<html>


而Cannot send session cache limiter錯誤則可以將php.ini的session.auto_start值修改為1即可

2015/09/22

PHP Web Output File

<?php

 function FunctionName($file)
 {
  if (file_exists($file)) {
   header('Content-Description: File Transfer');
   header('Content-Type: application/octet-stream');
   header('Content-Disposition: attachment; filename="' . basename($file) . '"');
   header('Expires: 0');
   header('Cache-Control: must-revalidate');
   header('Pragma: public');
   header('Content-Length: ' . filesize($file));
   readfile($file);
   exit;
  }
 }
?>