exif_imagetype

is_int
Find whether the type of a variable is integer

$_FILES[”][‘error’]
PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP.
UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION

exif_imagetype
Determine the type of an image
IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG

sprintf
Return a formatted string

image_type_to_extension
Get file extension for image type

<?php
if (isset($_FILES&#91;'upfile'&#93;&#91;'error'&#93;) && is_int($_FILES&#91;'upfile'&#93;&#91;'error'&#93;)){
  try {
    // $_FILES&#91;'upfile'&#93;&#91;'error'&#93;の値を確認
    switch ($_FILES&#91;'upfile'&#93;&#91;'error'&#93;){
      case UPLOAD_ERR_OK:
        break;
      case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('ファイルが選択されていません');
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
        throw new RuntimeException('ファイルサイズが大きすぎます');
      default:
        throw new RuntimeException('その他のエラーが発生しました');
    }

    // $_FILES&#91;'upfile'&#93;&#91;'mime'&#93;の値はブラウザ側で偽装可能なので、MIMEタイプを自前でチェック
    $type = @exif_imagetype($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;);
    if(!in_array($type, &#91;IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG&#93;, true)) {
      throw new RuntimeException('画像形式が未対応です');
    }

    // ファイルデータからSHA-1ハッシュを取ってファイル名を決定し、ファイルを保存する
    $path = sprintf('./img/%s%s', sha1_file($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;), image_type_to_extension($type));
    if (!move_uploaded_file($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;, $path)){
      throw new RuntimeException('ファイル保存時にエラーが発生しました');
    }
    chmod($path, 0644);

    $msg = &#91;'green', 'ファイルは正常にアップロードされました'&#93;;
  } catch (RuntimeException $e){
    $msg = &#91;'red', $e->getMessage()];
  }
}

// XTHMLとしてブラウザに認識させる
// (IE8以外はサポート対象外)
header('Content-Type: application/xhtml+xml; charset=utf-8');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>画像アップロード</title>
</head>
<body>
<?php if (isset($msg)): ?>
  <fieldset>
    <legend>結果</legend>
    <span style="color:<?=$msg&#91;0&#93;?>;"><?=$msg&#91;1&#93;?></span>
  </fieldset>
<?php endif; ?>
  <form enctype="multipart/form-data" method="post" action="">
    <fieldset>
      <legend>画像ファイルを選択(GIF, JPEG, PNGのみ対応)</legend>
      <input type="file" name="upfile" /><br />
      <input type="submit" value="送信" />
    </fieldset>
  </form>
</body>
</html>