重命名文件名并立即读取php中存在问题的文件

时间:2015-06-30 11:25:43

标签: php file-rename file-read

我有pdf文件,是学生的成绩单。报告卡名称格式为<student full name(which can have spaces)><space><studentID>。我需要下载文件。为此,我使用了以下代码。

if(file_exists($folder_path.'/') && is_dir(folder_path)) { 
    $report_files = glob(folder_path.'/*'.'_*\.pdf' ); 
    if(count($report_files)>0)
    {
        $result_data = '';
        $result_data = rename_filenamespaces($report_files);
        var_dump($result_data);//this shows the edited filename

        foreach ($result_data as $file) { 
            if (strpos($file,$_GET['StudentID']) !== false) {
                 //code for showing the pdf docs to download
            }
        }
    }
}

//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
    $new_location = $location; 
    foreach ($location as $file) {
       //check file has spaces and filename has studentID
       if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
       {
           $new_filename = str_replace(" ","-",$file);
           rename($file,$new_filename);
           $new_location = $new_filename;
       }
    }
    return $new_location;
}

变量$result_data为我提供了没有空格的文件名,但是每个循环都显示Warning:Invalid argument supplied for foreach()。但运行该函数后,文件名立即在服务器目录中更改。此警告仅在第一次显示。我无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

$new_location = $new_filename;

$ new_location是一个数组

$ new_filename是一个字符串

你必须使用$ new_location [$ index]

或尝试

foreach ($new_location as &$file) {
...
...
$file = $new_filename;