简体   繁体   English

php Curl循环从目录下载图像

[英]php Curl loop to download images from a directory

I wanted to download images from an api, it returns a type of '.jpg' when you access the url like this. 我想从api下载图像,当您访问url时,它返回类型为“ .jpg”。

https://www.foo.com/getimage.php?id=??

I found out that the script accepts an encoded id , but with base64_encode only, so I try doing it this way. 我发现该脚本接受一个已编码的id ,但是仅使用base64_encode ,因此我尝试以此方式进行操作。

<?php
$ch = curl_init();
for($i = 1; $i <= 10; $i++) {
 $ch = curl_init();
 $id = base64_encode($i);
 curl_setopt($ch,CURLOPT_URL,"https://www.foo.com/getimage.php?id=$id");
 if(curl_exec($ch)===false){
   file_put_contents('downloads/' . base64_decode($id) . '.jpg', $ch);
 }
}
curl_close($ch);

What do you think is my mistake. 你认为是我的错。

This will work with HTTP connection. 这将与HTTP连接一起使用。 You will need some additional settings to work with HTTPS . 您需要一些其他设置才能与HTTPS

Some important notes are commented in the code. 在代码中注释了一些重要的注释。

<?php

for($i = 1; $i <= 10; $i++) {
    $ch = curl_init();
    $id = base64_encode($i);
    curl_setopt($ch,CURLOPT_URL,"https://www.foo.com/getimage.php?id=$id");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return data as string

    // disable peer verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    // disable host verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 

    // spoof a real browser client string
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 
    $output = curl_exec($ch); // capture data into $output variable

    if( $output != false){
        file_put_contents('downloads/' . base64_decode($id) . '.jpg', $output );
    }
    curl_close($ch);
}

CURLOPT_RETURNTRANSFER CURLOPT_RETURNTRANSFER

TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly. 如果为TRUE,则将传输作为curl_exec()返回值的字符串返回,而不是直接将其输出。

CURLOPT_SSL_VERIFYPEER CURLOPT_SSL_VERIFYPEER

FALSE to stop cURL from verifying the peer's certificate. FALSE阻止cURL验证对等方的证书。 Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. 可以使用CURLOPT_CAINFO选项指定要验证的备用证书,或者可以使用CURLOPT_CAPATH选项指定证书目录。

CURLOPT_SSL_VERIFYPEER CURLOPT_SSL_VERIFYPEER

FALSE to stop cURL from verifying the certificate was issued to the entity we are connected to. FALSE阻止cURL验证证书已颁发给我们连接的实体。

http://www.php.net/curl_setopt http://www.php.net/curl_setopt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM