
imagecreatefromstring
Create a new image from the image stream in the string
<?php
if (isset($_FILES['upfile']['error']) && is_int($_FILES['upfile']['error'])){
try {
// $_FILES['upfile']['error']の値を確認
switch ($_FILES['upfile']['error']){
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('その他のエラーが発生しました');
}
// GD画像リソースの生成を試みる
if (!$img = @imagecreatefromstring(file_get_contents($_FILES['upfile']['tmp_name']))){
throw new RuntimeException('有効な画像ファイルを指定してください');
}
// ファイルデータからSHA-1ハッシュを取ってファイル名を決定し、保存する
if (!imagepng($img, sprintf('./uploads/%s.png', sha1_file($_FILES['upfile']['tmp_name'])))){
throw new RuntimeException('ファイル保存時にエラーが発生しました');
}
$msg = ['green', 'ファイルは正常にアップロードされました'];
} catch (RuntimeException $e){
$msg = ['red', $e->getMessage()];
}
if (isset($img) && is_resource($img)){
imagedestroy($img);
}
}
// 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[0]?>;"><?=$msg[1]?></span>
</fieldset>
<?php endif; ?>
<form enctype="multipart/form-data" method="post" action="">
<fieldset>
<legend>画像ファイルを選択</legend>
<input type="file" name="upfile" /><br />
<input type="submit" value="送信" />
</fieldset>
</form>
</body>
</html>