使用php在我的服务器上下载图像

Download image on my server using php

本文关键字:下载 图像 服务器 我的 php 使用      更新时间:2023-09-26

我有一个用于图像搜索按钮的div类:

<div class="form-group">
    <button onclick="myFunction()">Click me</button>
    <p id="demo"></p>
    <script>
        var link = "https://source.unsplash.com/all/?";
        var articleTitle = "<?php echo "'" . $article->title . "'"; ?>";
        function myFunction() {
            var d = new Date();
            var c = link + articleTitle + "[" + d.getTime()+"]";
            document.getElementById("demo").innerHTML = "<img src=" + c + " height='100' width='100'/>" ;
        }
    </script>
</div>

每次点击这个按钮都会根据我的关键字($article->title)和一个唯一的http url给我一个新的图像。

我想再做一个按钮,它将保存我的服务器上第一个按钮创建的图像。我想用这样的东西:

<?php 
     $image = file_get_contents("c");
     file_put_contents('C:'xampp'htdocs'test'htdocs'image'image.jpg', $image);
?>

其中"c"是我从第一个按钮开始的链接。

所以问题是:我应该在这里更改什么:file_get_contents("c");,因为我想把我的url从第一个按钮放在file_get_contents中,因为file_get_contents("c");这个方法不起作用。

如果我说得对,您想使用php将使用javascript生成的图像保存到服务器上吗?由于php代码只在页面加载时执行,您必须使用表单提交并将图像保存在目标php文件(当然可以是同一个文件)中,或者您必须使用AJAX请求来保存图像的第二个php文件。

没有AJAX的解决方案可能是这样的:

<form name="save_img_form" action="[target file or same file]" method="[get/post]"
onsubmit="document.save_img_form.img_src = c; return true;">
 <input type="hidden" name="img_src" value="" />
 <input type="submit" value="save image" />
</form>

为了实现这一点,您必须全局定义变量c。将行var c = link ...更改为c = link ...,使变量变为全局变量(此处比较:http://www.w3schools.com/js/js_scope.asp)

在目标页面(或同一页面)上,您可以使用类似的东西来检索图像来源:

<?php 
$img_src = $_GET["img_src"];  //or use $_POST, if you have used this method.
?>

然后,您可以对图像源执行任意操作。