PHP中的简单文件上传代码

时间:2017-01-18 12:13:21

标签: php

这个问题可能已多次讨论,但我想要一个简单的PHP脚本来上传文件,没有任何单独的操作文件,也没有任何检查。以下是我的书面代码: -

<html>
 <head>
  <title>PHP Test</title>
  <form action="" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="upload file" name="submit">
  </form>
 </head>
 <body>
 <?php echo '<p>FILE UPLOAD</p><br>'; 
 $tgt_dir = "uploads/";
 $tgt_file = $tgt_dir.basename($_FILES['fileToUpload']['name']);
 echo "<br>TARGET FILE= ".$tgt_file;
 //$filename = $_FILES['fileToUpload']['name'];
 echo "<br>FILE NAME FROM VARIABLE:- ".$_FILES["fileToUpload"]["name"];
 if(isset($_POST['submit']))
 {
 if(file_exists("uploads/".$_FILES["fileToUpload"]["name"]))
    { echo "<br>file exists, try with another name"; }
 else   {   
         echo "<br>STARTING UPLOAD PROCESS<br>";
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $tgt_file))
        { echo "<br>File UPLOADED:- ".$tgt_file; }

          else  { echo "<br>ERROR WHILE UPLOADING FILE<br>"; }
    }
 }
?> 
 </body>
</html>

我将其保存在 / var / www / html / phps / 位置。但每次我尝试上传文件时,都会出现 ERROR WHILE UPLOADING FILE 错误。我在这做错了什么。附:我以前没有PHP的经验,我刚开始使用bit&amp;互联网件。

感谢
KRISS

2 个答案:

答案 0 :(得分:0)

<?php
$target_dir = "uploads/"; 
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);


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.";
}
?>

我希望这件事能够奏效,这就是你所需要的。

答案 1 :(得分:0)

 <?php
$name = $_POST['name'];
$image = $_FILES['fileToUpload']['name'];
$tempname = $_FILES['fileToUpload']['tmp_name'];
move_uploaded_file($tempname, "foldername/$image");?>