在php上传视频和图片

时间:2014-11-29 11:28:59

标签: php mysql file-upload

我正在创建一个博客,在管理员方面我可以上传图像和视频,在用户方面我可以访问它们。现在我想将图像存储在不同目录上的不同目录和视频上,但问题是如何在选择文件时创建逻辑,然后代码知道它是图像还是视频?我试试......

<?php
session_start();
include 'conn.php';
$title=$_POST['title'];
$post=$_POST['post'];
$tag=$_POST['tag'];
$cat='some cat';
$file_name=$_FILES['fileToUpload']['name'];
$file_size=$_FILES['fileToUpload']['size'];
$file_height=200;
$file_width=100;
$duration=24.00;
$target_dir_image = "../posts/images/";
$target_dir_video = "../posts/videos/";
$target_file_image = $target_dir_image . basename($_FILES["fileToUpload"]["name"]);
$target_file_video = $target_dir_video . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;

$imageFileType = pathinfo($target_file_image,PATHINFO_EXTENSION);
$videoFileType = pathinfo($target_file_video,PATHINFO_EXTENSION);

    if ($imageFileType == "jpg" && $imageFileType == "png" && $imageFileType == "jpeg" && $imageFileType == "gif") {
        $uploadOk = 0;
    }

// Check if file already exists
        if (file_exists($target_file_image)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
// Check file size
        if ($_FILES["fileToUpload"]["size"] > 50000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
// Allow certain file formats

// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            $_SESSION['error'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            header('location:new-post.php');
// if everything is ok, try to upload file
        }
    else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file_image)) {
                $conn->beginTransaction();
                $conn->exec("INSERT INTO post(Title,Post,Category,Tag,Post_Date)VALUES ('" . $title . "','" . $post . "','" . $cat . "','" . $tag . "',now())");
                $conn->exec("INSERT INTO images(Image_Name,Image_Size,Image_Width,Image_height,Image_Directory)VALUES ('" . $file_name . "','" . $file_size . "','" . $file_width . "','" . $file_height . "','" . $target_file_image . "')");
                $conn->commit();
                $_SESSION['success'] = 'Post has been successfuly published';
                header('location:new-post.php');
                $conn->rollBack();
                $_SESSION['error'] = 'Fail to publish the post';
                header('location:new-post.php');


            }

    }
if ($videoFileType == "mp4" && $imageFileType == "flv" && $imageFileType == "mpeg" && $imageFileType == "avi")
{
    $uploadOk = 0;
}

// Check if file already exists
        if (file_exists($target_file_video)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
// Check file size
        if ($_FILES["fileToUpload"]["size"] > 50000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
// Allow certain file formats

// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            $_SESSION['error'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            header('location:new-post.php');
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file_video)) {
                $conn->beginTransaction();
                $conn->exec("INSERT INTO post(Title,Post,Category,Tag,Post_Date)VALUES ('" . $title . "','" . $post . "','" . $cat . "','" . $tag . "',now())");
                $conn->exec("INSERT INTO videos(Video_Name,Video_Size,Video_Duration,Video_Dimension,Video_Directory)VALUES ('" . $file_name . "','" . $file_size . "','".$duration."','" . $file_width . "','" . $target_file_video . "')");
                $conn->commit();
                $_SESSION['success'] = 'Post has been successfuly published';
                header('location:new-post.php');
                $conn->rollBack();
                $_SESSION['error'] = 'Fail to publish the post';
                header('location:new-post.php');


            } else {
                echo "Sorry, there was an error uploading your file.";
            }

        }

?>

但上面的代码无法正常工作。如果我只上传图像,那么代码将正常工作,但当我使用if和else语句时,数据只插入图像表?

更新

我尝试下面的代码,但它也无法正常工作......

<?php
session_start();
include 'conn.php';
$title=$_POST['title'];
$post=$_POST['post'];
$tag=$_POST['tag'];
$cat='some cat';
$file=$_FILES['fileToUpload'];
$file_name=$_FILES['fileToUpload']['name'];
$file_size=$_FILES['fileToUpload']['size'];
$file_height=200;
$file_width=100;
$duration=24.00;
$target_dir_image = "../posts/images/";
$target_dir_video = "../posts/videos/";
$target_file_image = $target_dir_image . basename($_FILES["fileToUpload"]["name"]);
$target_file_video = $target_dir_video . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$ext= pathinfo($file_name,PATHINFO_EXTENSION);


    if ($ext == "jpg" && $ext  == "png" && $ext  == "jpeg" && $ext == "gif")
    {


// Check if file already exists
    if (file_exists($target_file_image)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
// Check file size
    if ($_FILES["fileToUpload"]["size"] > 50000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
// Allow certain file formats

// Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        $_SESSION['error'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        header('location:new-post.php');
// if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file_image)) {
            $conn->beginTransaction();
            $conn->exec("INSERT INTO post(Title,Post,Category,Tag,Post_Date)VALUES ('" . $title . "','" . $post . "','" . $cat . "','" . $tag . "',now())");
            $conn->exec("INSERT INTO images(Image_Name,Image_Size,Image_Width,Image_height,Image_Directory)VALUES ('" . $file_name . "','" . $file_size . "','" . $file_width . "','" . $file_height . "','" .$target_file_image. "')");
            $conn->commit();
            $_SESSION['success'] = 'Post has been successfuly published';
            header('location:new-post.php');
            $conn->rollBack();
            $_SESSION['error'] = 'Fail to publish the post';
            header('location:new-post.php');


        }
        else {
            echo "Sorry, there was an error uploading your file.";
        }

    }
}

    if ($ext == "mp4" && $ext == "flv" && $ext == "mpeg" && $ext == "avi") {


// Check if file already exists
        if (file_exists($target_file_video)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
// Check file size
        if ($_FILES["fileToUpload"]["size"] > 50000000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
// Allow certain file formats

// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            $_SESSION['error'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            header('location:new-post.php');
// if everything is ok, try to upload file
        }
    }
    else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file_video)) {
            $conn->beginTransaction();
            $conn->exec("INSERT INTO post(Title,Post,Category,Tag,Post_Date)VALUES ('" . $title . "','" . $post . "','" . $cat . "','" . $tag . "',now())");
            $conn->exec("INSERT INTO videos(Video_Name,Video_Size,Video_Duration,Video_Dimension,Video_Directory)VALUES ('" . $file_name . "','" . $file_size . "','" . $duration . "','" . $file_width . "','" .$target_file_video. "')");
            $conn->commit();
            $_SESSION['success'] = 'Post has been successfuly published';
            header('location:new-post.php');
            $conn->rollBack();
            $_SESSION['error'] = 'Fail to publish the post';
            header('location:new-post.php');


        }     else {
            echo "Sorry, there was an error uploading your file.";
        }

    }

?>

我想要什么

当选择文件时,代码会检查它是图像还是视频,如果文件是图像则会上传到图像目录,与图像相关的数据将存储在图像表中,如果文件是视频然后它将上传到视频目录,与视频相关的数据将存储在视频表中,并建议我获取图像/视频高度和宽度以及视频持续时间的方式。

注意:我正在使用php 5.5,可能是我升级到PHP 5.5x所以请提供这样的解决方案,这不是过时意味着代码支持或不在PHP 5.5及更高版本中弃用。

4 个答案:

答案 0 :(得分:2)

尝试使用getid3()或ffmpeg。这些用于获取文件信息,我已经上传了一个stackoverflow链接,通过它可以了解它们是如何工作的。

答案 1 :(得分:1)

首先,您可以使用具有所需名称的单个浏览按钮。 &#34; my_blog_attachment&#34;

现在上传之前检查mimetype

$_FILES['my_blog_attachment']['type'] - 上传文件的MIME类型。

如果mime类型是image / png,image / jpg等,那么它就是图像

OR

如果mime类型是video / mp4等,则根据if条件进行编码。

答案 2 :(得分:1)

假设您选择了一个名为sample_image.jpg的文件。首先,您需要将此名称与.分开以获取文件扩展名和文件名。在上面的示例中,您将获得如下文件名。

$file_name=$_FILES['fileToUpload']['name'];

所以你必须将其拆分为:

list($fname,$exten) = split('.', $file_name);

现在,您有两个不同变量的文件扩展名和文件名。使用$exten来区分文件类型并根据文件类型在db / file位置上应用条件。

答案 3 :(得分:1)

尝试打印$ _FILES,以便您发现$ _FILES包含上传文件的详细信息,例如name,type,tmp_name (where will be files stored temporarily), size, error (will contain the error message if upload is not successful)

// The uploaded file type [image/jpeg] 
$type = $_FILES["name of the file"]["type"]  

// image format declaring in an array 
$img_type = array('image/jpeg','image/jpg','image/png');

// video format declaring in an array 
$video_type = array('video/mp4','video/avi');

// checking whether the uploaded file is an image type,video type not <br/>
if(in_array($type,$img_type)) { 
    // if it is image type, move to the coresponding directory location
    $target_dir = "images/";
    // move it to the corresponding location
    // code for moving it to the image table

}
elseif(in_array($type,$video_type){
    $target_dir = "videos/";
    // move it to the corresponding location
    // code for moving it to the video table
}
else {
 // the uploaded files is not either image or video
}