21

我希望用户能够将视频文件上传到我的网站,并且我希望它们被安排在适当的文件夹和数据库条目中,以便稍后我可以知道上传每个特定文件的人。

我的 HTML 表单在这里:

<form method="post" enctype="multipart/form-data">
    <div><?php echo $message; ?></div>
    <?php echo $max_file_size_tag; ?>
    <input type="file" accept="video/*" ID="fileSelect" runat="server" size="20" name="filename" action="/vids/file-upload.php">
    <select name="course">
        <option value="select" selected>Select</option>
        <option value="java">Java</option>
        <option value="python">Python</option>
        <option value="vb">Visual Basic</option>
        <option value="c">C/C++</option>
        <option value="ruby">Ruby</option>
    </select>
    <input type="submit" value="Upload" name="submit">
</form>

我的 PHP 在这里:

<?php

$folder  = isset($_POST["course"]);
$message = "1";

define('DESTINATION_FOLDER','/$folder);

define('MAX_FILE_SIZE', 0);

// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','learn.learnbrix.com');

// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array();

// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', true);

$message = "renamed";
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '~');

$message = "string append";
// Need uploads log? Logs would be saved in the MySql database.
define('DO_LOG', false);

// MySql data (in case you want to save uploads log)
define('DB_HOST','  '); // host, usually localhost
define('DB_DATABASE','  '); // database name
define('DB_USERNAME','  '); // username
define('DB_PASSWORD','  '); // password

/* NOTE: when using log, you have to create MySQL table first for this script.
Copy-paste following into your MySQL admin tool (like PhpMyAdmin) to create a table
If you are on cPanel, then prefix _uploads_log on line 205 with your username, so it would be like myusername_uploads_log

CREATE TABLE _uploads_log (
  log_id int(11) unsigned NOT NULL auto_increment,
  log_filename varchar(128) default '',
  log_size int(10) default 0,
  log_ip varchar(24) default '',
  log_date timestamp,
  PRIMARY KEY  (log_id),
  KEY (log_filename)
);

*/

####################################################################
###  END OF SETTINGS.   DO NOT CHANGE BELOW
####################################################################

// Allow script to work long enough to upload big files (in seconds, 2 days by default)
@set_time_limit(172800);

// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");

function showUploadForm($message='') {
  $max_file_size_tag = '';
  if (MAX_FILE_SIZE > 0) {
    // convert to bytes
    $max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
  }

  // Load form template
  include ('upload.html');
}

// errors list
$errors = array();

$message = '';

// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
  if (strpos($ini_maxsize, 'M') !== false)
    $ini_maxsize = intval($ini_maxsize)*1024*1024;
  elseif (strpos($ini_maxsize, 'K') !== false)
    $ini_maxsize = intval($ini_maxsize)*1024;
  elseif (strpos($ini_maxsize, 'G') !== false)
    $ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
  $errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}

// show upload form
if (!isset($_POST['submit'])) {
  showUploadForm(join('',$errors));
}

// process file upload
else {

  while(true) {

    // make sure destination folder exists
   if (!@file_exists(DESTINATION_FOLDER)) {
     $errors[] = "Destination folder does not exist or no permissions to see it.";
     break;
   }

   // check for upload errors
   $error_code = $_FILES['filename']['error'];
   if ($error_code != UPLOAD_ERR_OK) {
     switch($error_code) {
       case UPLOAD_ERR_INI_SIZE: 
        // uploaded file exceeds the upload_max_filesize directive in php.ini
        $errors[] = "File is too big (1).";
        break;
      case UPLOAD_ERR_FORM_SIZE: 
        // uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
        $errors[] = "File is too big (2).";
         break;
       case UPLOAD_ERR_PARTIAL:
         // uploaded file was only partially uploaded.
         $errors[] = "Could not upload file (1).";
         break;
       case UPLOAD_ERR_NO_FILE:
         // No file was uploaded
         $errors[] = "Could not upload file (2).";
         break;
       case UPLOAD_ERR_NO_TMP_DIR:
         // Missing a temporary folder
         $errors[] = "Could not upload file (3).";
         break;
       case UPLOAD_ERR_CANT_WRITE:
      // Failed to write file to disk
      $errors[] = "Could not upload file (4).";
      break;
    case 8:
      // File upload stopped by extension
      $errors[] = "Could not upload file (5).";
      break;
  } // switch

  // leave the while loop
  break;
}

// get file name (not including path)
$filename = @basename($_FILES['filename']['name']);

// filename of temp uploaded file
$tmp_filename = $_FILES['filename']['tmp_name'];

$file_ext = @strtolower(@strrchr($filename,"."));
if (@strpos($file_ext,'.') === false) { // no dot? strange
  $errors[] = "Suspicious file name or could not determine file extension.";
  break;
}
$file_ext = @substr($file_ext, 1); // remove dot

// check file type if needed
if (count($exts)) {   /// some day maybe check also $_FILES['user_file']['type']
  if (!@in_array($file_ext, $exts)) {
    $errors[] = "Files of this type are not allowed for upload.";
    break;
  }
}

// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
  $dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
// append predefined string for safety
$dest_filename = $dest_filename . APPEND_STRING;

// get size
$filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);

// make sure file size is ok
if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
  $errors[] = "File is too big (3).";
  break;
}

if (!@move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
  $errors[] = "Could not upload file (6).";
  break;
}

if (DO_LOG) {
  // Establish DB connection
  $link = @mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD);
  if (!$link) {
    $errors[] = "Could not connect to mysql.";
    break;
  }
  $res = @mysql_select_db(DB_DATABASE, $link);
  if (!$res) {
    $errors[] = "Could not select database.";
    break;
  }
  $m_ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
  $m_size = $filesize;
  $m_fname = mysql_real_escape_string($dest_filename);
  $sql = "insert into _uploads_log (log_filename,log_size,log_ip) values ('$m_fname','$m_size','$m_ip')";
  $res = @mysql_query($sql);
  if (!$res) {
    $errors[] = "Could not run query.";
    break;
  }
  @mysql_free_result($res);
  @mysql_close($link);
} // if (DO_LOG)


// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();

break;

 } // while(true)

 // Errors. Show upload form.
 $message = join('',$errors);
 showUploadForm($message);

}
?>

我对PHP一无所知,所以我不知道出了什么问题。我还想添加接受姓名及其电子邮件地址的功能。

4

4 回答 4

58

“你能建议一个更简单的代码主要是上传文件数据库条目是次要的”

^---根据 OP 的要求。---^

图片和视频上传代码(用PHP 5.4.17测试)

HTML 表单

<!DOCTYPE html>

<head>
<title></title>
</head>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

PHP 处理程序 (upload_file.php)

将上传文件夹更改为首选名称。目前保存到upload/

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))

&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>
于 2013-08-13T21:37:54.800 回答
3
HTML Code

<html>
<body>

<head>
<title></title>
</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file"><span>Filename:</span></label>
    <input type="file" name="file" id="file" /> 
    <br />
<input type="submit" name="submit" value="Submit" />
</form>



<?php

    //============================= DATABASE CONNECTIVITY d ====================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    //============================= DATABASE CONNECTIVITY u ====================
    //============================= Retrieve data from DB d ====================
    $sql = "SELECT name, size, type FROM videos";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) 
        {
        $path = "uploaded/" . $row["name"];

            echo $path . "<br>";

        }
    } else {
        echo "0 results";
    }
    $conn->close();
    //============================= Retrieve data from DB d ====================

?>


</body>
</html>
于 2014-11-13T04:07:10.170 回答
2
PHP file (name is upload.php)    

<?php
    // =============  File Upload Code d  ===========================================
    $target_dir = "uploaded/";

    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

     // Check file size -- Kept for 500Mb
    if ($_FILES["fileToUpload"]["size"] > 500000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($imageFileType != "wmv" && $imageFileType != "mp4" && $imageFileType != "avi" && $imageFileType != "MP4") {
        echo "Sorry, only wmv, mp4 & avi files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    // ===============================================  File Upload Code u  ==========================================================


    // =============  Connectivity for DATABASE d ===================================
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "test";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    else

    $vidname = $_FILES["fileToUpload"]["name"] . "";
    $vidsize = $_FILES["fileToUpload"]["size"] . "";
    $vidtype = $_FILES["fileToUpload"]["type"] . "";

    $sql = "INSERT INTO videos (name, size, type) VALUES ('$vidname','$vidsize','$vidtype')";

    if ($conn->query($sql) === TRUE) {} 
    else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        }

    $conn->close();
    // =============  Connectivity for DATABASE u ===================================

    ?>
于 2014-11-13T04:12:09.847 回答
1
sample code:

<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>

<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder 
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
 //Allow Certain File Format To Upload
 if($type!='mp4' && $type!='3gp' && $type!='avi'){
  echo "Only mp4,3gp,avi file format are allowed to Upload";
  $errors=0;
 }
 //checking for Exsisting video Files
  if(file_exists($target)){
   echo "File Exist";
   $errors=0;
   }
  $filesize=$_FILES['video']['size'];
  if($filesize>250*2000000){
  echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a     href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to   upload large file in php</a>'; 
    $errors=0;
    }
   if($errors == 0){
   echo ' Your File Not Uploaded';
    }else{
 //Moving The video file to Desired Directory
  $uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
  if($uplaod_success){
  //Getting Selected video Information
    $name=$_FILES['video']['name'];
    $size=$_FILES['video']['size'];
    $result=mysqli_query($con,"INSERT INTO VIdeos           (name,size,type)VALUES('".$name."','".$size."','".$type."')");
    if($result==TRUE){
    echo "Your video '$name' Successfully Upload and Information Saved Our  Database";
    }
   }
  }
  }
 ?>
于 2018-10-26T09:34:36.913 回答