处理 PHP Shell_exec 中的空格的函数escapeshellarg

php的exec的参数里面如果有空格会导致执行失败,用escapeshellarg()即可(实际上是加了引号)

下面这里例子是使用php遍历pdf并且转化为txt的例子
[php]<?php
/*
* 递归获取指定路径下的所有文件或匹配指定正则的文件(不包括“.”和“..”),结果以数组形式返回
* @param string $dir
* @param string [$pattern]
* @return array
*/
function file_list($dir,$pattern="")
{
$arr=array();
$dir_handle=opendir($dir);
if($dir_handle)
{
// 这里必须严格比较,因为返回的文件名可能是“0”
while(($file=readdir($dir_handle))!==false)
{
if($file==='.' || $file==='..')
{
continue;
}
$tmp=realpath($dir.'/'.$file);
if(is_dir($tmp))
{
$retArr=file_list($tmp,$pattern);
if(!empty($retArr))
{
$arr[]=$retArr;
}
}
else
{
if($pattern==="" || preg_match($pattern,$tmp))
{
$arr[]=$tmp;
}
}
}
closedir($dir_handle);
}
return $arr;
}

function convert($list){
print 'fucking:'.$list.'<br />';
$dest=substr($list,0,count($list)-5);
$list=escapeshellarg($list);
$dest=escapeshellarg($dest);
#print $list.$dest;
exec("pdftotext -enc UTF-8 $list $dest.txt",$out);
print '<br />'.'done'.'<br />';
return $out;
}

function de_array($array){
static $result_array=array();
foreach($array as $value)
{
if(is_array($value))
{
de_array($value);
}
else
$result_array[]=$value;
}
return $result_array;
}

set_time_limit(0);

$lists=file_list(getcwd().'\pdf',"/\.pdf$/i");
$lists=de_array($lists);
#print_r($lists);
foreach ($lists as $key=>$list){
convert($list);
}
?>[/php]

尤其是这个函数de_array(),使用递归来把多维数组转化成一维数组。
[php]function de_array($array){
static $result_array=array();
foreach($array as $value)
{
if(is_array($value))
{
de_array($value);
}
else
$result_array[]=$value;
}
return $result_array;
}
[/php]

Author Info :
  • From:处理 PHP Shell_exec 中的空格的函数escapeshellarg
  • URL:https://blog.ihipop.com/2010/11/1818.html
  • Please Reserve This Link,Thanks!
  • 《处理 PHP Shell_exec 中的空格的函数escapeshellarg》上有1条评论

    回复 sunyzc 取消回复

    您的电子邮箱地址不会被公开。 必填项已用 * 标注