簡體   English   中英

PHP上傳圖片腳本不起作用

[英]PHP upload image script isn't working

<?
if(isset($_POST['upload'])) {
    if(empty($_FILES['image'])) {
        echo "<p class=\"error\">Please upload an image...</p>\n";
    } else {
    $file_name= $_FILES['image']['name']; // original name
    $file_type = $_FILES['image']['type'];
    $file_size = $_FILES['image']['size'];
    $file_tmp = $_FILES['image']['tmp_name']; // temporary location on server
    $file_error = $_FILES['image']['error']; // reference to future error
    $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);

    if($file_ext != "jpeg" || "jpg" || "gif" || "png") {
        echo "<p class=\"error\">Please upload an image that has the extension .jpg/jpeg, .gif, or .png.</p>\n";
    } else {
        if($file_size > (10000000)) {
            echo "<p class=\"error\">Please upload an image that does not exceed the file size of 10MB.</p>\n";
        } else {
            if($file_error) {
                echo "<p class=\"error\">Sorry, an unexpected error occurred: ".$file_error."</p>\n";
            } else {
                $f_rename = "pfp/".time().".png";
                move_uploaded_file($file_tmp,$f_rename);
                }
            }
       }
    }
}
?>
<!doctype html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="upload_test_image.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="submit" name="upload" value="Upload"/>
</form>
</body>
</html>

我無法上傳任何圖片,因為無法通過文件擴展名檢查。 在撰寫本文時,我還試圖剖析問題是否在於擴展驗證確實是問題所在(可能是因為它只是打印出我發布的錯誤聲明,原因是它首先出現在... else語句)。 任何人都可以在該代碼或此代碼中幫助找到問題嗎?

pathinfo()將需要文件的路徑而不僅僅是文件名。 要擴展,您可以嘗試以下操作:

$extension = preg_replace('@.+\.@', '', $_FILES['image']['name'])

另外,您可以檢查$ _FILES ['image'] ['type'],因為其中可能包含您要查找的類型。 finfo可能也有幫助: http ://php.net/manual/en/function.finfo-file.php

我不認為您可以在PHP中執行這樣的布爾條件。

怎么樣,聲明一個允許的擴展數組:

$extensions = array("jpeg", "jpg", "gif","png");

然后檢查文件擴展名是否在數組中:

if(!in_array($file_ext, $extensions)) {
    //Please upload an image that has the extension .jpg/jpeg, .gif, or .png.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM