【问题标题】:How do I insert an image into a file using PHP如何使用 PHP 将图像插入到文件中
【发布时间】:2016-01-12 02:01:15
【问题描述】:

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

<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("无法打开文件!")

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

【问题讨论】:

  • 插入DOM还是上传文件?
  • 可能是权限相关问题。 echo file_get_contents($_FILES["image"]["tmp_name"]; 有输出吗?

标签: php image file


【解决方案1】:

如果您想将图像保存到文件中,您可以使用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

【讨论】:

  • 我真的相信这会起作用,但我的文件目录是否正确:$img = "This PC/Desktop/New folder(2)/PHP/htdocs/blog/images".$title; PHP 只是 xxamp 重命名,它位于一个名为 New folder(2) 的文件夹中。我不确定我需要 PC 和台式机。图片是我想要图片所在的文件夹。
  • 尝试使用 $_SERVER['DOCUMENT_ROOT'] 获取路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
  • 2013-03-16
  • 2021-09-20
  • 2012-03-24
  • 1970-01-01
  • 2013-06-18
相关资源
最近更新 更多