php上傳圖片到指定位置路徑儲存到資料庫__資料庫
來源:互聯網
上載者:User
1.conn.php
<?
$host="localhost"; //資料庫伺服器名稱
$user="root"; //使用者名稱
$pwd="1721"; //密碼
$conn=mysql_connect($host,$user,$pwd);
mysql_query("SET
character_set_connection=gb2312,
character_set_results=gb2312,
character_set_client=binary",$conn);
if ($conn==FALSE)
{
echo "<center>伺服器串連失敗。<br>請重新整理後重試。</center>";
return true;
}
$databasename="database";//資料庫名稱
do
{
$con=mysql_select_db($databasename,$conn);
}while(!$con);
if ($con==FALSE)
{
echo "<center>開啟資料庫失敗。<br>請重新整理後重試。</center>";
return true;
}
?>
2.upload.php
<?php
if ($_GET['act ion'] == "save"){
include_on ce('conn.php');
include_on ce('uploadclass.php');
$title=$_POST['title'];
$pic=$uploadfile;
if($title == "")
echo"<Script>window.alert('對不起。你輸入的資訊不完整!');history.back()</Script>";
$sql="insert into upload(title,pic) values('$title','$pic')";
$result=mysql_query($sql,$conn);
//echo"<Script>window.alert('資訊添加成功');location.href='upload.php'</Script>";
}
?>
<html>
<head>
<title>檔案上傳執行個體</title>
</head>
<body>
<form method="post" act ion="?act ion=save" enctype="multipart/form-da ta">
<table border=0 cellspacing=0 cellpadding=0 align=center width="100%">
<tr>
<td width=55 height=20 align="center"> </TD>
<td height="16">
<table width="48%" height="93" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>標題:</td>
<td><input name="title" type="text" id="title"></td>
</tr>
<tr>
<td>檔案: </td>
<td><label>
<input name="file" type="file" value="瀏覽" >
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
</label></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="上 傳" name="upload"></td>
</tr>
</table></td>
</tr>
</table>
</form>
</body>
</html>
3.uploadclass.php
<?php
$uploaddir = "upfiles/";//設定檔案儲存目錄 注意包含/
$type=array("jpg","gif","bmp","jpeg","png");//設定允許上傳檔案的類型
$patch="upload/";//程式所在路徑
//擷取檔案尾碼名函數
function fileext($filename)
{
return substr(strrchr($filename, '.'), 1);
}
//產生隨機檔案名稱函數
function random($length)
{
$hash = 'CR-';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$max = strlen($chars) - 1;
mt_srand((double)microtime() * 1000000);
for($i = 0; $i < $length; $i++)
{
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
$a=strtolower(fileext($_FILES['file']['name']));
//判斷檔案類型
if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type))
{
$text=implode(",",$type);
echo "您只能上傳以下類型檔案: ",$text,"<br>";
}
//產生目標檔案的檔案名稱
else{
$filename=explode(".",$_FILES['file']['name']);
do
{