如何使用PHP将图像插入到文件中


How do I insert an image into a file using PHP

我正在尝试将图像插入到我的"博客"文件中的"图像"文件中。我的代码文件也在"博客"文件中,这就是代码。

<html>
    <form method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="upload" value="upload"/>
</form>
    <?php

include('blogconnect.php');
include('header.php');
    if(isset($_POST['upload']))
    {
        $imagename = mysqli_real_escape_string($_FILES["image"] ["name"]);
        $imagedata = mysqli_real_escape_string(file_get_contents($_FILES["image"] ["tmp_name"]));
        $imagetype = mysqli_real_escape_string($_FILES["image"] ["type"]);

$myfile = fopen("images" , "w") or die("Unable to open file!");
$imagename = mysqli_real_escape_string($_FILES["image"] ["name"]);
$imagedata = mysqli_real_escape_string(file_get_contents($_FILES["image"] ["tmp_name"]));
$imagetype = mysqli_real_escape_string($_FILES["image"] ["type"]);
fwrite($myfile, $imagename, $imagedata, $imagetype );
fclose($myfile);

    if($_FILES["image"]["type"] == "image/jpeg" || $_FILES["image"]["type"] == "image/png") {
    }
    }
?>
</html>

当我试图插入时,我在这里做错了什么。显示的错误显示

die("无法打开文件!")

所以它甚至不会打开。如果有人看到任何其他错误,请告诉我。

如果您想将图像保存到文件中,可以使用file_put_contents

请尝试此代码:

<html>
<head></head>
<body>
<form action="post_image.php" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit" name="submit">
</form>
</body>
</html>

这是PHP代码,文件名post_image.php:

<?php
    if (isset($_POST['submit'])) {
        $title = $_FILES['image']['name'];
        $data = $_FILES['image']['tmp_name'];
        $content = file_get_contents($data);
        $img = "/xampp/htdocs/whatever/".$title;
        file_put_contents($img, $content);
        if ($content)
        {
            $img = imagecreatefromstring($content);
            header("Content-Type: image/jpeg");
            imagejpeg($img);
        } else {
            echo 'Image not found...!!!';
        }
    }
?>

有关信息,allow_url_fopen需要设置为true才能使用file_put_contents`。希望这能帮助你D