PHP——運行shell命令|腳本


內置函數

PHP | 系統程序執行

 

 

 

 exec

 

 shell_exec

 

 passthru

 

 system

 

配置

打開php.ini配置文件,並從disable_function將用到的函數從禁用中刪除,然后重新載入或重啟服務

 

 腳本

腳本和小程序代碼均位於public目錄下

#!/bin/bash

source /etc/profile

time=`date +%Y-%m-%d-%H:%M:%S`

cd /data/wwwroot/虛擬域名/public/miniprogram/

if [ 0 -eq $? ] ; then
         echo "$time INFO 進入目錄成功" >> build_log.log
else
         echo "$time ERROR 進入目錄失敗" >> build_log.log
                exit 1
fi

#刪除之前編譯文件

rm -rvf *.zip  dist >> build_log.log

if [ 0 -eq $? ] ; then
         echo "$time INFO 刪除成功" >> build_log.log
else
         echo "$time ERROR 刪除失敗" >> build_log.log
                exit 1
fi

#編譯

npm run build wx $1 $2 >> /dev/null

if [ 0 -eq $? ] ; then
         echo "$time INFO 編譯成功" >> build_log.log
else
         echo "$time ERROR 編譯失敗" >> build_log.log
                exit 1
fi

#打包

zip -r $1-$time.zip dist >> /dev/null

if [ 0 -eq $? ] ; then
         echo "$time INFO 打包成功" >> build_log.log
else
         echo "$time ERROR 打包失敗" >> build_log.log
                exit 1
fi

 

配置權限

通過ps aux | grep nginx 可以知道nginx的用戶為www

 

修改所屬組和用戶

chown -R www:www miniprogram/
chown -R www:www mini.sh

 

修改權限

chmod -R 775 miniprogram/
chmod -R 775 mini.sh

 

賦予權限

usermod -s /bin/bash www

 

 

PHP代碼

shell腳本執行成功后會返回0

<?php

namespace app\common\model;

use think\Db;

class WeixinShell extends Common
{

    /**
     * 打包小程序
     * @param array $params
     * @return array
     */
   public function build($params = [])
    {
        $result = [
            'status' => true,
            'msg'    => '編譯成功',
            'data'   => [],
        ];

        $version = $params['mini_version'];
        $area = $params['mini_area'];
        system("sh mini.sh {$version} {$area} ", $status);
        $mini = glob("./miniprogram/*.zip");
        $file = $mini['0'];

        $url = $_SERVER['HTTP_HOST'].'/';
        if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
            $http = 'https://';
        }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
            $http = 'https://';
         }else {
            $http = 'http://';
        }

        if(file_exists($file)){
          $result['data']['url'] = $http.$url.$file;
        }else{
           header("HTTP/1.1 404 Not Found");
        }

        if($status){
           $result['msg'] = '編譯失敗';
            return $result;
        }else{
            return $result;
        }

     }


}

編譯成功后返回URL地址,然后前端直接用window.location.href 可實現自動下載

 

 成功示例

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM