>  기사  >  백엔드 개발  >  비디오 파일을 폴더에 업로드하고, 데이터베이스 항목을 생성하고, PHP로 유효성 검사를 수행하는 방법은 무엇입니까?

비디오 파일을 폴더에 업로드하고, 데이터베이스 항목을 생성하고, PHP로 유효성 검사를 수행하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-21 14:01:30634검색

How to Upload Video Files to a Folder, Create a Database Entry, and Perform Validation with PHP?

PHP로 비디오 파일을 업로드하고 적절한 폴더에 저장한 후 데이터베이스 항목을 생성하세요

이 PHP 스크립트를 사용하면 사용자가 비디오 파일을 지정된 폴더에 업로드하고 해당 폴더를 만들 수 있습니다. 데이터베이스 항목:

<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>

제출 시 이 스크립트는 다음 작업을 수행합니다.

  • 업로드된 파일 형식, 크기 및 확장자를 확인합니다.
  • 지정된 폴더에 업로드된 파일.
  • 데이터베이스 연결을 생성하고 업로드 테이블에 동영상의 파일 이름 및 경로가 포함된 항목을 삽입합니다.

위 내용은 비디오 파일을 폴더에 업로드하고, 데이터베이스 항목을 생성하고, PHP로 유효성 검사를 수행하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.