画像をアップロードするフォームのまとめ

これまでファイルをアップロードをする為のフォームを機能を書きましたが、ここでまとめておきます。




アップロードするフォームのまとめ

例1:test12_1.php

<form action="test12_2.php" method="post" enctype="multipart/form-data">
画像ファイル<br>
<input type="file" name="pic">
<br>
<input type="submit" name="botan" value="送信">
</form>
<BR>

<?php
print '<font color="#ff0000">';
print $_GET["err"];
print '</font>';

$typelist=array( ".png",".gif",".jpg",".jpeg" );

for($count=0;$count<10;$count++)
{
     $ext="";
     for($type=0;$type<4;$type++)
     {
          if(file_exists("pic".$count.$typelist[$type]))
          {
               $ext=$typelist[$type];
               break;
          }
     }
     if(strlen($ext)>0)
     {
          print "<IMG src='pic".$count.$ext."?".date("YmdHis")."'><br>";
     }
}
?>
<BR>



例2:test12_2.php

<?php
if(!isset($_POST["botan"]))
{
     header("location: test12_1.php?err=".urlencode("送信ボタンを押してください"));
     exit;
}

$file=pathinfo($_FILES["pic"]["name"]);

if(
   strcasecmp("png",$file["extension"])!=0
&& strcasecmp("gif",$file["extension"])!=0
&& strcasecmp("jpeg",$file["extension"])!=0
&& strcasecmp("jpg",$file["extension"])!=0
   )
{
     header("location: test12_1.php?err=".urlencode("画像ファイルを送信してください"));
     exit;
}
if(strlen($_FILES["pic"]["name"])==0)
{
     header("location: test12_1.php?err=".urlencode("ファイル名がありません"));
     exit;
}

if(file_exists("pic9.png"))
{
     unlink("pic9.png");
}
if(file_exists("pic9.gif"))
{
     unlink("pic9.gif");
}
if(file_exists("pic9.jpg"))
{
     unlink("pic9.jpg");
}
if(file_exists("pic9.jpeg"))
{
     unlink("pic9.jpeg");
}

for($count=8;$count>=0;$count--)
{
     if(file_exists("pic".$count.".png"))
     {
          @rename("pic".$count.".png","pic".($count+1).".png");
     }
     if(file_exists("pic".$count.".gif"))
     {
          @rename("pic".$count.".gif","pic".($count+1).".gif");
     }
     if(file_exists("pic".$count.".jpg"))
     {
          @rename("pic".$count.".jpg","pic".($count+1).".jpg");
     }
     if(file_exists("pic".$count.".jpeg"))
     {
          @rename("pic".$count.".jpeg","pic".($count+1).".jpeg");
     }
}

if(! move_uploaded_file($_FILES["pic"]["tmp_name"],"pic0.".$file["extension"]) )
{
     header("location: test12_1.php?err=".urlencode("アップロードに失敗しました"));
     exit;
}
header("location: test12_1.php");
exit;
?>



「参照…」を押して送るファイルを選択します。
ファイルを選択した状態で送信を押すとアップロードします。

アップロードされた画像ファイルは上から下へ順番に10個表示するようになっていて
10個を超えると最も古いファイルを削除して10個以上にならないようになっています。

そして、ファイルを選択していない状態で送信を押すと「ファイル名がありません」、
画像ファイルではない場合は「画像ファイルを送信してください」と
エラーが表示されます。

このプログラムでのポイントは削除以外での画像交換処理では
ブラウザの状況によってはキャッシュされてしまう為
更新した後に画像が更新前の状態で画像の表示に変更が行われない事です。

これを防ぐ為に画像表示部分のurlの後に「?」とdate()による時刻を追加しています。

■print “<IMG src=’pic”.$count.$ext.”?”.date(“YmdHis”).”‘><br>”;


こうする事でキャッシュに記録された画像を参照する事もなく新しい画像リストを表示させています。

clearstatcache()を使えばページのキャッシュをクリア出来るそうですが、使い方がイマイチ判らないのでコレが安定です。

スポンサーリンク







シェアする

  • このエントリーをはてなブックマークに追加

フォローする

関連記事



スポンサーリンク