如何将没有扩展名的文件从远程网址(应用程序的Google Play商店图片)复制到php中的服务器临时文件夹?

时间:2016-11-18 10:08:42

标签: php

我正在努力应用从Google Playstore抓取结构化数据并将其保存在数据库中。我正在获取所有结构化数据。我正在尝试复制itemprop="image"网址并将图片保存到我的服务器。

我尝试了很多东西,但没有任何作用,因为文件没有扩展名。下面的代码有效,但生成了无效文件或创建了零字节的文件。

我要复制的示例网址

https://lh3.googleusercontent.com/IYZe0LQOUKXpEYOyVOYYMJo4NnqBnDYkkhDgfYTgDCpuxAyy1ziBkOn0b6_LZxQ3qI4=w300-rw

我正在使用的PHP代码

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $useragent);         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);   
    curl_setopt($process, CURLOPT_SSL_VERIFYPEER,false);    
    // curl_setopt($process, CURLOPT_SSL_VERIFYPEER,0); 
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 
$image="https://lh3.googleusercontent.com/IYZe0LQOUKXpEYOyVOYYMJo4NnqBnDYkkhDgfYTgDCpuxAyy1ziBkOn0b6_LZxQ3qI4=w300-rw";
$upload_dir = wp_upload_dir();
$length= strlen($image);
$new_string = substr($image,0,$length-8);
$imagename= basename($new_string);
$image2 = getimg($imgurl); 
$new_image_path = file_put_contents($upload_dir['basedir'].'/custom-temp/'.$imagename,$image2); 

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误,例如$imgurl未被一致命名且wp_upload_dir()未定义。考虑在调试时打开PHP中的错误,以便能够捕获这些错误。

我可以让您的代码像这样工作(只需将路径更改回function getimg($url) { $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; $headers[] = 'Connection: Keep-Alive'; $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; $gim = 'php'; $process = curl_init($url); curl_setopt($process, CURLOPT_HTTPHEADER, $headers); curl_setopt($process, CURLOPT_HEADER, 0); // curl_setopt($process, CURLOPT_USERAGENT, $useragent); curl_setopt($process, CURLOPT_TIMEOUT, 30); curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($process, CURLOPT_SSL_VERIFYPEER,false); // curl_setopt($process, CURLOPT_SSL_VERIFYPEER,0); $return = curl_exec($process); curl_close($process); return $return; } $image="https://lh3.googleusercontent.com/IYZe0LQOUKXpEYOyVOYYMJo4NnqBnDYkkhDgfYTgDCpuxAyy1ziBkOn0b6_LZxQ3qI4=w300-rw"; $upload_dir = "/home/laurent/test/upload"; $length= strlen($image); $new_string = substr($image,0,$length-8); $imagename= basename($new_string); $image2 = getimg($image); $new_image_path = file_put_contents($upload_dir.'/'.$imagename,$image2); ):

LoginController