圖片儲存與瀏覽一例(Linux+Apache+PHP+MySQL)_php基礎
來源:互聯網
上載者:User
注意本程式使用的表結構為:
use test;
create table image(
id int unsigned auto_increment primary key,
description text,
filename varchar(50),
filesize int,
filetype varchar(50),
filedata longblob
);
*/
//?cmd={read|list|form|store}
//檢查cmd參數的合法性
switch($cmd){
case 'read':
break;
case 'list':
break;
case 'form':
break;
Case 'store':
break;
default:
$cmd = 'list';
break;
}
switch($cmd){
case 'read':
//?cmd=read&id={}
//讀一個圖片
$server = mysql_connect("localhost","test","") or die("無法串連資料庫伺服器");
mysql_select_db("test",$server) or die("無法串連資料庫");
$sql = "select filetype,filedata from image where id='$id'";
$rst = mysql_query($sql,$server) or die("$sql查詢出錯");
if($row=mysql_fetch_row($rst)){
header("Content-Type:" . $row[0]);
echo $row[1];
}
else{
echo "沒有找到該記錄";
}
mysql_free_result($rst);
mysql_close($server) or die("無法與資料庫伺服器中斷連線");
break;
case 'list':
//?cmd=list
//顯示所有圖片
echo '<html>';
echo '<head><title>圖片儲存與瀏覽一例</title></head>';
echo '<body>';
echo '<a href="' . $PHP_SELF . '?cmd=list">顯示所有圖片</a>';
echo " ";
echo '<a href="' . $PHP_SELF . '?cmd=form">上傳圖片</a>';
$server = mysql_connect("localhost","test","") or die("無法串連資料庫伺服器");
mysql_select_db("test",$server) or die("無法串連資料庫");
$sql = "select id,description,filename,filetype,filesize from image";
$rst = mysql_query($sql,$server) or die("$sql查詢出錯");
while($row=mysql_fetch_row($rst)){
echo "<hr>";
echo "描述:" . $row[1] . "<br>";
echo "檔案名稱:" . $row[2] . "<br>";
echo "類型:" . $row[3] . "<br>";
echo "大小:" . $row[4] . "<br>";
echo '<img src="' . $PHP_SELF . '?cmd=read&id=' . $row[0] . '">';
}
mysql_free_result($rst);
mysql_close($server) or die("無法與資料庫伺服器中斷連線");
echo '</body>';
echo '</html>';
break;
case 'form':
?>
<html>
<head><title>圖片儲存與瀏覽一例</title></head>
<body>
<form action="<?echo $PHP_SELF;?>?cmd=store" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2097152">
描述:<br>
<textarea name="description" rows="5" cols="100"></textarea><br>
檔案:<input type="file" name="file"><br>
<input type="submit" value="上傳">
</form>
</body>
</html>
<?
break;
case 'store':
//?cmd=store&description={}&file={}&file_size={}&file_type={}&file_name={}
//儲存圖片
echo '<html>';
echo '<head><title>圖片儲存與瀏覽一例</title></head>';
echo '<body>';
echo '<a href="' . $PHP_SELF . '?cmd=list">顯示所有圖片</a>';
echo " ";
echo '<a href="' . $PHP_SELF . '?cmd=form">上傳圖片</a>';
$server = mysql_connect("localhost","test","") or die("無法串連資料庫伺服器");
mysql_select_db("test",$server) or die("無法串連資料庫");
$data = addslashes(fread(fopen($file,"r"),filesize($file)));
$sql = "insert into image(description,filename,filetype,filesize,filedata)
values('$description','" . basename($file_name) . "','$file_type',$file_size,'$data')";
mysql_query($sql,$server) or die("$sql執行出錯");
$id = mysql_insert_id();
echo "<hr>你上傳的圖片效果:<br>";
echo '<img src="' . $PHP_SELF . '?cmd=read&id=' . $id . '">';
mysql_close($server) or die("無法與資料庫伺服器中斷連線");
echo '</body>';
echo '</html>';
break;
}
?>