0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPで保守性高くファイルをアップロードする方法

Last updated at Posted at 2021-03-13

自分のアウトプット用です。
何かありましたらバシバシ詰めてください。

inputのnameは『file』とする。

qiita.php

if(isset($_FILES['file']['error'])){

try{
switch($_FILES['file']['error']){
  case UPLOAD_ERR_OK:  //OKの時だけ処理をそのまま進める
    break;
  case UPLOAD_ERR_FORM_SIZE:
    throw new RuntimeException('ファイルサイズオーバー');
      break;
  case UPLOAD_ERR_NO_FILE:
    throw new RuntimeException('ファイルがありません');
      break;
  case UPLOAD_ERR_NO_FILE:
    throw new RuntimeException('ファイルがありません');
      break;
  case UPLOAD_ERR_PARTIAL:
    throw new RuntimeException('一部しかアップロード出来ません');
      break;
}//ここまではマニュアルに載ってるのでコピペ。その他必要なエラーコードがあれば追加

$img_type = @exif_imagetype($FILES['file']['tmp_name']);
//これがあまりググっても出てこない。
//exif_imagetypeは『imagetype_jpeg』や『imagetype_png』などの定数を返す。mimeタイプを自力でチェック

//in_arrayは第一引数には検索したい値を渡し、第二引数では検索対象の配列を渡す。
//第三引数にはtrueを必ず渡す。じゃないと型まで合ってるか判断してくれない。
if(!in_array($img_type,[imagetype_jpeg,imagetype_png,imagetype_gif]),true){
    throw new RuntimeException('ファイル形式が違います');
    }
$path = 'ディレクトリ名/'.sha1_file($_FILES['tmp_name']).image_type_to_extension($img_type);
//『sha1_file』でハッシュ化。いっぱいファイル保存する場合はファイル名ダブル場合があるので。md5_fileとかでも良いかと
//image_type_to_extensionはファイルの拡張子取得。これもググってもあまり出て来てくれない。

//ここまでやれば結構良い感じ。と信じたい。
//いざファイル場所移動
   move_upload_file($_FILES['file']['tmp_name']),$path);
//パーミッション変更
   chmod($path,0644);

}catch(RuntimeException $e){
  error_log('エラーです:'.$e->getMessage());
}
}

プログラミングってどれもそうですが動作にすると数秒なのに
とてつもなく長いコード書きますよね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?