dougou6727 2016-05-26 10:44
浏览 27
已采纳

cakePHP中的递归函数

In a controller action, I handle the file upload like following (in short):

$originalFileName = $meetingsTask['submitted_file']['name'];    

$file = $meetingsTask['submitted_file'];

    $ext = substr(strtolower(strrchr($file['name'], '.')), 1);

    $arr_ext = array('jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xlsx', 'xls', 'xlt', 'xlm', 'ods','ppt', 'pot', 'pps' );

      if(!in_array($ext, $arr_ext)){
       ...code omitted...
      }

    $newFileName = $this->generateFileName( $originalFileName );

    ...logic continues...

The problem is that generateFileName function always returns empty when file name already exists. Here is the function itself:

public function generateFileName( $fileName ){

    if( $this->Tasks->checkFileName( $fileName ) ){

        $prefix = rand(1, 1000);

        $fileName = $prefix . '_' . $fileName;

        $this->generateFileName( $fileName );

    }else{

        return $fileName;

    }

}

checkFileName() only returns true/false depending on the existance of filename in the database.

What could be causing the trouble?

Any help or guidance is much appreciated.

  • 写回答

1条回答 默认 最新

  • dongmu2026 2016-05-26 10:48
    关注

    If I understand correctly what you want, the recursion in not needed

    public function generateFileName( $fileName ) {
        // Start with source filename
        $new = $fileName;
        while( $this->Tasks->checkFileName( $new ) ) {
            // If file exist try new prefix
            $prefix = rand(1, 1000);
            $new = $prefix . '_' . $fileName;
        }
        return $new;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services