
使用PHP 上傳視訊檔案並將其保存在適當(dāng)?shù)馁Y料夾中並建立資料庫條目
此PHP 腳本允許使用者將視訊檔案上傳到指定資料夾並建立對(duì)應(yīng)的資料庫條目資料庫項(xiàng)目:
<code class="php"><?php
// Upload settings
define('DESTINATION_FOLDER', '/uploads/'); // Folder to save uploaded videos
define('MAX_FILE_SIZE', 10485760); // Maximum file size allowed in bytes (10MB)
define('ALLOWED_EXTENSIONS', ['avi', 'mov', 'mp4']); // Allowed file extensions
// Database settings
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'my_database');
// Initialize variables
$errors = [];
$message = '';
$uploadSuccess = false;
// Process form submission
if (isset($_POST['submit'])) {
// Fetch form data
$filename = $_FILES['filename']['name'];
$tmp_filename = $_FILES['filename']['tmp_name'];
$file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$filesize = $_FILES['filename']['size'];
// Validate file
if (!$tmp_filename) {
$errors[] = 'Error: No file selected.';
} elseif (!in_array($file_ext, ALLOWED_EXTENSIONS)) {
$errors[] = 'Error: File type not allowed.';
} elseif ($filesize > MAX_FILE_SIZE) {
$errors[] = 'Error: File size exceeds limit.';
}
// Upload file if no errors
if (empty($errors)) {
$newFilename = uniqid() . '.' . $file_ext;
$uploadPath = DESTINATION_FOLDER . $newFilename;
// Move uploaded file to the specified folder
if (move_uploaded_file($tmp_filename, $uploadPath)) {
$uploadSuccess = true;
$message = 'File uploaded successfully.';
} else {
$errors[] = 'Error: Unable to move uploaded file.';
}
}
// Create database entry if upload was successful
if ($uploadSuccess) {
try {
// Establish database connection
$conn = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL query
$stmt = $conn->prepare("INSERT INTO uploads (`name`, `path`) VALUES (?, ?)");
$stmt->execute([$filename, $uploadPath]);
} catch (PDOException $e) {
$errors[] = 'Error: Database connection failed: ' . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Video Files</title>
</head>
<body>
<h1>Upload Video Files</h1>
<form method="post" enctype="multipart/form-data">
<label for="filename">Filename:</label>
<input type="file" name="filename">
<input type="submit" name="submit" value="Upload">
</form>
<?php if (!empty($message)): ?>
<div><?php echo $message; ?></div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</body>
</html></code>
提交後,此腳本執(zhí)行以下任務(wù):
- 驗(yàn)證上傳的檔案類型、大小和副檔名。
- 移動(dòng)上傳檔案到指定資料夾。
- 建立資料庫連線並在上傳表中插入包含影片檔案名稱和路徑的條目。
以上是如何使用 PHP 將視訊檔案上傳到資料夾、建立資料庫條目並執(zhí)行驗(yàn)證?的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!