簡體   English   中英

PHP:從base64字符串中獲取圖像並將其存儲在路徑中

[英]PHP: get image from base64 string and store it in the path

這是PHP函數,它將新數據添加到MySQL數據庫中。

**我想在Web服務器上傳圖像。 **

public function addNewCategory($category_title, $strImage) {

    // get the image from the base64 string.
    $strImage = base64_decode($strImage);
    $image = imagecreatefromstring($strImage);
    if($image !== false) {
        header('Content-Type: image/png');
        imagepng($image);
        imagedestroy($image);
    }

    // set the path name of where the image is to be stored.
    $path = $_SERVER['SERVER_NAME']."/uploads/".$category_title.".png";

    // save the image in the path.
    file_put_contents($path, $image);

    // insert category and the image path into the MySQL database.
    $result = mysqli_query($this->db->connect(), "INSERT INTO category(category_title, path, created_at) VALUES ('$category_title', '$path', NOW())");

    if ($result) {
        return mysqli_fetch_array($result);
    } else {
        return false;
    }
}

使用該函數, path變量存儲在數據庫中,但圖像實際上並未存儲在路徑中。 上面的代碼有什么問題?

編輯后我將路徑名改為$path = $_SERVER['SERVER_NAME']."/MyProject/uploads/".$category_title.".png"; 現在數據庫中的路徑值證明是我所期望的,但似乎圖像本身並沒有實際放入路徑中。

我向數據庫添加了一個新行,在瀏覽器中手動鍵入路徑以檢查我發送的圖像是否正確存儲在路徑中,但Web服務器返回錯誤404。

要在服務器上寫入文件,您需要相對於服務器上的文件夾系統設置路徑。 要在數據庫中存儲數據,您需要指向圖像的Web路徑:

//__DIR__ - path to your current script folder
$server_path = __DIR__."/uploads/".$category_title.".png";

// save the image in the server path.
file_put_contents($server_path, $image);

//Web path to your image
$web_path = $_SERVER['SERVER_NAME']."/uploads/".$category_title.".png";

//Write to DB web path of the image
$result = mysqli_query($this->db->connect(), "INSERT INTO category(category_title, path, created_at) VALUES ('$category_title', '$web_path', NOW())");

暫無
暫無

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

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