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 可实现自动下载

 

 成功示例

 

posted @ 2019-04-03 13:26  。思索  阅读(5658)  评论(0编辑  收藏  举报