PHP中tempnam函数dir参数不可访问却取系统tmp目录

项目中需要将LaTex公式转为图片传给前端,实现方式是利用exec分别调用系统的latex/dvips/convert命令,最终生成png文件.

...

error_reporting(0); # not checking existence myself, that would be double.
if (chdir("tmp")===FALSE) { return '[directory access error, fix permissions]'; } #I should chech whether file creation is allowed to give a nice error for that problem case
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); # TODO: set old value

$tfn = tempnam(getcwd(), 'PTX'); #file in tmp dir

#write temporary .tex file
if ( ($tex = fopen($tfn.'.tex', "w"))==FALSE) {
    return '[file access error] '.phplatex_cleantmp($tfn,$heredir);
}
fwrite($tex, $totex); 
fclose($tex);

# Run latex to create a .dvi.  Have it try to fix minor errors instead of breaking/pausing on them.
exec($path_to_latex.' --interaction=nonstopmode '.$tfn.'.tex');
if (!file_exists($tfn.".dvi")) {
    $log = file_get_contents($tfn.'.log'); #The log always exists, but now it's actually interesting since it'll contain an error
    return '[latex error, code follows]<pre>'.$totex.'</pre><p><b>Log file:</b><pre>'.$log.'</pre></p> '.phplatex_cleantmp($tfn,$heredir);
}

...

某次出问题,报错一直都是’[latex error, code follows…]’,即执行完latex命令转换tex的代码后检查dvi文件是否存在,打印出exec执行的代码,’/usr/bin/latex –interaction=nonstopmode /tmp/PTXBmQJee.tex’,上文有 chdir(“tmp”) 已经切换到当前目录下的tmp目录,而此tex却在/tmp下,打印发现getcwd()确实是当前目录的tmp,WTF,搜了下tempnam:

tempnam

Description string tempnam ( string $dir , string $prefix )

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist or is not writable, tempnam() may generate a file in the system’s temporary directory, and return the full path to that file, including its name.

dir不存在或者不可写的时候会取系统的临时目录,而前面的chdir的判断并没有确保tmp可写.给tmp加写权限即解决问题.

坚持原创技术分享,您的支持将鼓励我继续创作!