yii 控制器中的脚本可以工作,但不能通过 yii 控制台应用程序工作

问题描述 投票:0回答:1

我有一个 yii 控制器,可以使用curl 创建文件夹并在其中下载图像。

如果我从浏览器运行脚本,它会像我需要的那样工作,一切都很好,但是如果我尝试通过 yii 控制台应用程序从终端运行此脚本,我会收到以下错误: mkdir error img error

我尝试向整个项目文件夹授予

chmod 777
权限和
chown www-data
但没有帮助

这是我下载图片的功能:

public function loadImg($id_tovar, $id_post, $file)
{
if (strpos($file, 'swf') === false) {

ini_set('memory_limit', '-1');

set_time_limit(0);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $file);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);

curl_setopt($ch, CURLOPT_HEADER, 0);

$img = curl_exec($ch);

$info = curl_getinfo($ch);

$error = curl_error($ch);

$err = curl_errno( $ch );

curl_close($ch);

if (@imagecreatefromstring($img) !== false) {

$source_image = imagecreatefromstring($img);

}

if (isset($source_image)) {

$exPos = strrpos($file, '.');

$type = substr($file, $exPos);

$filename = 'tov_'.$id_tovar.'_'.substr(md5(uniqid(mt_rand(), true)), 0, 8).$type;

$dirFull = $_SERVER['DOCUMENT_ROOT'].'/nal/img/'.$id_post;

if(!is_dir($dirFull)){

mkdir($dirFull);

}

$fullPath = $dirFull . '/'. $filename;

self::resizeImage($source_image, $type, $filename, $dirFull);

self::resizeImage($source_image, $type, $filename, $dirFull, 280, 280, '/l_', true);

return 'ok';

}

}

return false;

}

public static function resizeImage($source, $tip, $filename, $root, $w = 1080, $h = 1140, $pref = '/b_', $delImg = false){

$max_shir = $w;

$max_vis = $h;

$w_src = imagesx($source);

$h_src = imagesy($source);

$kw = $max_shir/$w_src;

$kh = $max_vis/$h_src;

$k = $kw;

if($kw > $kh){

$k = $kh;

}

if($k>1){

$k = 1;

}

$shir = (int)($w_src * $k);

$vis = (int)($h_src * $k);

$smesh_x = (int) (($max_shir - $shir)/2);

$smesh_y = (int) (($max_vis - $vis)/2);

$dest = imagecreatetruecolor($max_shir, $max_vis);

imageAlphaBlending($dest, false);

imageSaveAlpha($dest, true);

$color = imagecolorallocate ( $dest , 255 , 255 , 255 );

imagefill ( $dest, 0 , 0 , $color );

imagecopyresampled($dest, $source, $smesh_x, $smesh_y, 0, 0, $shir, $vis, $w_src, $h_src);

$PUTH = $root;

$name=$PUTH.$pref.$filename;

if($tip == '.jpg' || $tip == '.jpeg' || $tip == '.JPG'){

imagejpeg($dest, $name, 100);

}

if($tip == '.png'){

imagepng($dest, $name, 8);

}

if($delImg){

imagedestroy($dest);

imagedestroy($source);

}

}

我是编程世界的新手,所以我需要大佬的帮助。非常感谢)

php permissions yii2 console console-application
1个回答
0
投票

当您使用 cli 而不是 Web 服务器运行脚本时,没有文档根目录,因此

$_SERVER['DOCUMENT_ROOT']
为空,最终得到像这样的绝对路径
/nal/img/...
这是错误的。

您可以尝试使用类似的方法来获取根文件夹的绝对路径:

$dirFull = dirname(__DIR__) .'/nal/img/'.$id_post;

Magic const

__DIR__
指向当前脚本的目录,而
dirname()
函数基本上为您提供其参数中给出的路径上方一个文件夹的路径。因此,您可能需要根据需要修改调用
dirname()
函数的次数以匹配您的文件结构。

© www.soinside.com 2019 - 2024. All rights reserved.