connect.php — 資料庫連線upload_img.php — 上傳、壓縮、返回路徑test_upload.php — 接收路徑、預處理寫入資料庫set_charset('utf8mb4');
if ($db->connect_errno) {
die('Connect failed: '.$db->connect_error);
}
3,'msg'=>'類型錯誤']));
}
$ext = fileext($_FILES['filename']['name']);
do { $name = randname().'.'.$ext; } while (file_exists($uploaddir.$name));
$uploadfile = $uploaddir.$name;
$uploadfile_resize = $uploaddir_resize.$name;
if (move_uploaded_file($_FILES['filename']['tmp_name'], $uploadfile)) {
// 壓縮邏輯
$im = null;
switch ($_FILES['filename']['type']) {
case 'image/jpeg': case 'image/pjpeg': $im = imagecreatefromjpeg($uploadfile); break;
case 'image/png': case 'image/x-png': $im = imagecreatefrompng($uploadfile); break;
case 'image/gif': $im = imagecreatefromgif($uploadfile); break;
default: $im = imagecreatefromjpeg($uploadfile);
}
if ($im) {
$w = imagesx($im); $h = imagesy($im);
$ratio = 0.5; // 固定縮半
$nw = (int)($w*$ratio); $nh = (int)($h*$ratio);
$thumb = imagecreatetruecolor($nw, $nh);
imagecopyresampled($thumb, $im, 0,0,0,0, $nw,$nh, $w,$h);
imagejpeg($thumb, $uploadfile_resize, 90);
imagedestroy($thumb); imagedestroy($im);
}
die(json_encode(['code'=>0,'original'=>$uploadfile,'thumb'=>$uploadfile_resize]));
}
die(json_encode(['code'=>1,'msg'=>'上傳失敗']));
prepare('INSERT INTO img (real_img, small_img) VALUES (?, ?)');
$stmt->bind_param('ss', $real_img, $small_img);
$stmt->execute();
echo $stmt->affected_rows ? 'ok' : 'fail';
CREATE TABLE `img` ( `id` int(11) NOT NULL AUTO_INCREMENT, `real_img` varchar(255) NOT NULL, `small_img` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
bind_param三文件最小可行實現:connect.php 連線 → upload_img.php 上傳壓縮 → test_upload.php 預處理入庫。核心安全點:mysqli 預處理綁定參數、文件類型白名單、隨機文件名防覆蓋。實際專案請按 MVC 分層重構。