dongyi1748 2015-12-08 10:08
浏览 35

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

I have a div class for an image search button:

<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>

Each click on this button gives me a new image by my keyword ($article->title) with a unique http url.

And I want to do one more button, which will save the image founded by first button on my server. I want to use something like this:

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

Where "c" is my link from first button.

So the question is: What should I change here: file_get_contents("c"); as I want place my url from first button into file_get_contents , because file_get_contents("c"); this method didnt work.

  • 写回答

1条回答 默认 最新

  • doutusheng5879 2015-12-08 10:44
    关注

    If I get you right, you want to save an image which is generated using javascript to your server, using php? As php code is only executed on page load, you have to use a form submit and save the image in the target php file (which of course can be the same file) or you have to use an AJAX request to a second php file, which saves the image.

    A solution without AJAX could look something like that:

    <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>
    

    In order for this to work, you have to define the variable c globally. Change the line var c = link ... to c = link ..., so the variable becomes global (compare here: http://www.w3schools.com/js/js_scope.asp)

    On the target page (or same page) you use something like this to retrieve the image source:

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

    Then you can do whatever you want with the image source.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法