Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created August 14, 2018 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/f474e159680842b2c06825d68d00b3a4 to your computer and use it in GitHub Desktop.
Save yano3nora/f474e159680842b2c06825d68d00b3a4 to your computer and use it in GitHub Desktop.
[cakephp: Folder/File] Folder / File class on CakePHP3. #php #cakephp

Folder / File

exec() よりも Folder/File クラス が便利だね。

ファイルアップロード

if ($this->request->data('file.size')) {
  try {
    $fileName = $this->request->data('file.name');
    $fileTmp  = $this->request->data('file.tmp_name');
    $FileApi  = new File($fileTmp);
    $fileExt  = pathinfo($fileName, PATHINFO_EXTENSION);
    $filePath = $fileName.'.'.$fileExt;
    $fileDest = FILE_DEST.'/'.$filePath;
    // Verify it that allowed extension.
    if (!in_array($fileExt, ALLOW_EXTENSIONS)) throw new \Exception('Denied file extensions.');
    if (UPLOAD_MAX < $FileApi->size()) throw new \Exception('File size exceeded the upload limit.');
    $FileApi->safe();
    $FileApi->copy($fileDest, true);
    $FileApi->close();
    $this->Flash->success('Upload was success.');
  } catch (\Exception $e) {
    if (!empty($FileApi)) $FileApi->close();
    $this->Flash->error($e->getMessage());
  }
  return $this->redirect($this->referer());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment