如何使用php将图像上传到服务器上的文件夹目录中


How to Upload images into folder directory on the server using php

我正在尝试将图像上传到服务器上。

在服务器上的文件夹名称:{photo}

我检查了文件夹的权限,它目前在0755上。

当我运行php代码时,我得到以下错误代码:

"上传文件时出错-检查目标是否可写。"

与我的问题类似的帖子是:如何将照片上传到我的托管服务器文件夹目录

但我的代码中已经有了这些功能:

这里是我的php代码:

<?php
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filesize = $_FILES["file_img"]["size"];
$fileinfo = getimagesize($_FILES["file_img"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../photo/".$filename;
$filepath_thumb = "../photo/thumb/".$filename;


if($_POST['btn_upload'])
{
    $sPhotoFileName = $filename;
    $nPhotoSize = $filesize;
    $sTempFileName = $filetmp;
    chmod($filepath_thumb,0755);
    chmod($filepath,0755);
if(file_exists('photo/' . $_FILES['file_img']['name'])){
    die('File with that name already exists.');
}else{
if ($sPhotoFileName) // file uploaded
{   $aFileNameParts = explode(".", $sPhotoFileName);
    $sFileExtension = end($aFileNameParts); // part behind last dot
    if ($sFileExtension != "jpg"
        && $sFileExtension != "png"
        && $sFileExtension != "gif")
    {   die ("Choose a JPG for the photo");
    }
}
if($_FILES['file_img']['error'] > 0){
    die('An error ocurred when uploading.');
}
    if ($nPhotoSize == 0)
    {   die ("Sorry. The upload of $sPhotoFileName has failed.
Search a photo smaller than 300K, using the button.");
    }
    if ($nPhotoSize > 30240000000)
    {   die ("Sorry.
The file $sPhotoFileName is larger than 300K.
Advice: reduce the photo using a drawing tool.");
    }
    // read photo
    $oTempFile = fopen($sTempFileName, "r");
    $sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
    // Try to read image
    $nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
    $oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
    error_reporting($nOldErrorReporting);
    if (!$oSourceImage) // error, image is not a valid jpg
    { die ("Sorry.
It was not possible to read photo $sPhotoFileName.
Choose another photo in JPG format.");
    }
}
 $nWidth = imagesx($oSourceImage); // get original source image width
        $nHeight = imagesy($oSourceImage); // and height
        // create small thumbnail
        $nDestinationWidth = 80;
        $nDestinationHeight = 60;
    //$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
        $oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
    /*$oResult = imagecopyresampled(
        $oDestinationImage, $oSourceImage,
        0, 0, 0, 0,
        $nDestinationWidth, $nDestinationHeight,
        $nWidth, $nHeight); // resize the image
    */
        imagecopyresized($oDestinationImage, $oSourceImage,0, 0, 0, 0,$nDestinationWidth, $nDestinationHeight,$nWidth, $nHeight); // resize the image
        ob_start(); // Start capturing stdout.
        imageJPEG($oDestinationImage); // As though output to browser.
        $sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
        ob_end_clean(); // Dump the stdout so it does not screw other output.
    // attempt insert query execution
    $sql = "INSERT INTO UploadImg (img_name, img_path, img_type) VALUES ('$sPhotoFileName', '$filepath', '$filetype')";
        if(mysqli_query($link, $sql)){
                    echo "Records added successfully.";
                } else{
                    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
                }

    if(!move_uploaded_file($_FILES["file_img"]["tmp_name"],"../photo/".$_FILES["file_img"]["name"])){
           die('Error uploading file - check destination is writeable.');
       echo "Error Code: " .$_FILES["file_img"]["name"] . "<br>";
    }else{

    $sBinaryThumbnail = addslashes($sBinaryThumbnail);
    $oDatabase = $link;
    mysqli_select_db("upload", $oDatabase);
    $sQuery = "insert into Uploadimg (thumbnail) VALUES ('$sBinaryThumbnail')";
    echo $sQuery;
    mysqli_query($sQuery, $oDatabase);
    die('File uploaded successfully.');
    mysqli_close($link);
    }
}
    ?>

现在我读到一篇文章说,即使你的文件夹权限设置起来,也要做到读、写、执行三个级别。根据服务器上的设置,代码仍然无法读取。

所以我很困惑,希望澄清。请帮帮我?

您可以通过二进制数据编码上传图像,并将图像格式的文件保存在服务器上。

755表示它不可全局写入。您可以使用777将其设置为可写和可执行。

这仍然很容易受到攻击,因为任何有权访问您的服务器操作系统的人都可以写入文件夹,所以您可能只需要让web服务器用户成为文件夹的所有者,并保持权限不变。如果您运行的是apache,那么用户通常是www data或apache。

我想你必须设置GID和UID权限权限权限

设置组标识GID允许所有者执行所有应用程序以读取、写入和拉入文件夹。

用户标识UID也是如此。问题是你的文件夹会被陌生人打开来操作,但它是有效的。

我的图像正在上传到文件夹中。告诉我你怎么想?

首先在php.ini中放入

file_uploads = On 

接下来,创建一个HTML表单,允许用户选择他们想要上传的图像文件:

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">

确保表单使用方法="post"然后使用下面的php代码上传图像

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>