通过PHP脚本保存数据

时间:2017-10-22 21:41:02

标签: php

我想通过php脚本在我的服务器上保存视频。我传递一个文件名并将其插入我的$ file变量,这是要保存的实际文件路径。 echo是正确的(Videos / 2.mp4),但保存的文件没有文件名(Videos / .mp4)。

<?php


 $filename = $_POST['filename'];

// File Path to save file
$file = 'Videos/'.$filename.'.mp4';

echo $file;

// Get the Request body
$request_body = @file_get_contents('php://input');

// Get some information on the file
$file_info = new finfo(FILEINFO_MIME);

// Extract the mime type
$mime_type = $file_info->buffer($request_body);

// Logic to deal with the type returned
switch($mime_type) 
{
    case "video/mp4; charset=binary":

        // Write the request body to file
        file_put_contents($file, $request_body);

        break;

    default:
        // Handle wrong file type here
}

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

要保存视频或其他文件(照片,文档等),您必须在表单中添加enctype="multipart/form-data"

像这样:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" /> 
    <input type="submit" name="submit" value="Submit" />
</form>

注意:这个问题告诉你如何在Obj-c中实现这个目的。 POST multipart/form-data with Objective-C

之后,您可以通过$_FILES超级全局读取数据。您可以使用以下脚本作为示例。

<?php

if (!isset($_FILES['file'])) {
    // Handle file not submitted
} else {
    $allowedExtensions = array('video/mp4');
    $mimeType = $_FILES['file']['type'];

    $fileName = $_FILES['file']['name'];
    $fileLocation = 'Videos/' . $fileName;

    if (!in_array($mimeType, $allowedExtensions)) {
        // Handle wrong file type here
    } else {
        move_uploaded_file($_FILES['file']['tmp_name'], $fileLocation);
    }
}