phpはファイルのアップロード機能を実現
ファイルをアップロードし、名前を変更し、関連情報をデータベースに書き込んでいます.
(1)htmlページ
(2)phpコード
(1)htmlページ
<html>
<head>
<title>upload test - 2012/12/29</title>
<meta charset="utf-8" />
</head>
<body>
<form action="uploadProc.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="submit" value=" " />
</form>
</body>
</html>
(2)phpコード
<?php
$name = isset($_FILES['file_upload']['name']) ? $_FILES['file_upload']['name'] : '';
$tmp_name = isset($_FILES['file_upload']['tmp_name']) ? $_FILES['file_upload']['tmp_name'] : '';
$type = isset($_FILES['file_upload']['type']) ? $_FILES['file_upload']['type'] : '';
$size = isset($_FILES['file_upload']['size']) ? $_FILES['file_upload']['size'] : 0;
$error = isset($_FILES['file_upload']['error']) ? $_FILES['file_upload']['error'] : 0;
$filename = trim($name);
$uploadtime = time(); //
$filecode = md5($filename.$uploadtime.rand(100,999)); // ,
$ret = uploadfile($name, $tmp_name, $type, $size, $error, $filecode); //
if ($ret > 0) { //
recfile($filename, $filecode, $uploadtime); //
} else {
echo "error:$ret";
}
function uploadfile($name, $tmp_name, $type, $size, $error, $filecode) {
$uploaddir = 'uploads/';
if (!$name || !$tmp_name) {
return -1000;
}
$maxsize = 1024*1024*3; // 3m
if ($size > $maxsize || !$size) {
return -1001;
}
$filetypes = array(
'doc' => 'application/vnd.ms-word',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'pdf' => 'application/pdf',
'xml' => 'text/xml',
'rar' => 'application/octet-stream',
'zip' => 'application/octet-stream'); // , 6
$fileexts = explode('.', $name);
if (!isset($filetypes[end($fileexts)]) || in_array($type, $filetypes) == false) {
return -1002;
}
$filename = "$uploaddir/$filecode";
move_uploaded_file($tmp_name,$filename);
chmod($filename, 0644);
return 1;
}
function recfile($filename, $filecode, $uploadtime) {
$host = 'localhost:';
$port = 3306;
$username = 'root';
$password = 'abc123';
$dbname = 'test';
try {
$mysql = mysql_connect($host.$port, $username, $password, true);
if (!$mysql) {
die("connect error to mysql : ".mysql_error());
}
mysql_select_db($dbname);
$sql = "insert into upload(filename, filecode, uploadtime) values ('$filename', '$filecode', $uploadtime)";
$ret = mysql_query($sql);
$affected_rows = mysql_affected_rows($mysql);
mysql_close($mysql);
if ($affected_rows) {
return $filecode;
}
return false;
} catch (Exception $e) {
echo $e->getMessage();
return false;
}
}
?>