在php中上传图片/文件

时间:2018-05-14 13:12:20

标签: php file-handling

 <?php

if (isset($_FILES['image']))
    {
    $filename = $_FILES['image']['name'];
    $filetmp = $_FILES['image']['tmp_name'];
    move_uploaded_file($filetmp, "uploads/" . $filename);
    echo "Upload Successfully!";
    }

?>

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

在html部分,表单有三个部分(方法,动作和enctype)。我将在“行动”中写下什么?一部分?

2 个答案:

答案 0 :(得分:0)

 <?php

   if (isset($_POST['uploadimage']))
     {
     $filename = $_FILES['image']['name'];
     $filetmp = $_FILES['image']['tmp_name'];
     move_uploaded_file($filetmp, "uploads/" . $filename);
     echo "Upload Successfully!";
     }

 ?>

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

您可以使用此类型。 thisfilename.php,即您的php文件的名称。

答案 1 :(得分:0)

这是您可以用来上传文件的脚本。

$target_dir = "your directory";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$target_file = preg_replace('/\s+/', '_', $target_file);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image

// Check if file already exists
if (file_exists($target_file)) {
    $uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
    $uploadOk = 0;
}
// Allow certain file formats
if($FileType == "wav" OR $FileType == "jpg" OR $FileType == "png" ) {
    $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["file"]["tmp_name"], $target_file)) {
     // do something when the file is uploaded
    } else {
       // do something when the file is not uploaded
    }
}

您的操作可以为空,以转到相同文件或在需要发布到的文件名中输入文件名
您的HTML

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