WpDoe
WpDoe

Reputation: 474

Recursive function in 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.

Upvotes: 0

Views: 496

Answers (1)

splash58
splash58

Reputation: 26153

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;
}

Upvotes: 1

Related Questions