Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 有关CURL 将图片上传去远程服务器

有关CURL 将图片上传去远程服务器

Jun 20, 2016 pm 12:31 PM

我自己东拼西拼的弄了个功能

是把编辑器中有远程图片就下载到本地主机的一个小功能

正正常常的,好好的可以用,可是图片越来越多,需要把网页服务器 和 附件服务器分开保存

所以需要上传到远程的服务器中

本来我自动下载的类里面是用了最基本的fopen等等来保存,如下

$write_fd = fopen($pic_name,"wb");  fwrite($write_fd, $this->CurlGet($pic_item));  fclose($write_fd);
Copy after login


可是要如何才能实现远程的呢?

我试了下把这一段改成:
header('content-type:text/html;charset=utf8'); $curl = curl_init(); $data = array('img'=>'@'. $this->CurlGet($pic_item)); curl_setopt($curl, CURLOPT_URL, "http://xxxx.com/autodl.php?dir=$this->folder"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $result = curl_exec($curl); curl_close($curl); echo json_decode($result);
Copy after login


但却完全没效
有关autodl.php的内容,大概是:
<?phpheader("Access-Control-Allow-Origin: http://www.gamertb.com");header("Content-Type: applicaton/json");    if($_FILES)    {    	// print_r($_FILES);        $filename = $_FILES['img']['name'];        $tmpname = $_FILES['img']['tmp_name'];        $dir = $_GET['dir'];        if(move_uploaded_file($tmpname, dirname(__FILE__).$dir.$filename))        {            echo json_encode('上传成功');        }         else        {            $data = json_encode($_FILES);            echo $data;        }    }?>
Copy after login


仍然失败,诚心救肋,望高手相助

整个类的代码好像太多,我放在二楼


回复讨论(解决方案)

整个自动下载的类

class AutoImgDL {private $content;private $folder;private $home_url;private $loacl_host;public function __construct($content,$folder,$dir_level="../../"){    $this->content = $content;    $this->folder = $folder;    $this->dir_level = $dir_level;    $this->loacl_host = "abc.com";    $this->get_unique = $this->get_unique();    $this->home_url = 'http://data.abc.com/'.$this->folder;}//create microtime to set unique idprivate function get_unique(){      list($msec, $sec) = explode(" ",microtime());      return $sec.intval($msec*1000000);  } private function get_pic($content) {    $pattern_src = '/< *img[^>]*src *= *["\']?([^"\']*)/i';      $num = preg_match_all($pattern_src, $content, $match_src);      //get all images    $arr_src_remote=$match_src[1];    //img type    $pattern_type = '/(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)/';     //foreach images file name   123456789.img_type    $arr = "";    foreach($arr_src_remote as $pic_item){        preg_match("/^(http:\/\/)?([^\/]+)/i",$pic_item, $matches);        $host = $matches[2];        preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);        if ( $matches[0] != $this->loacl_host ) {                           $num = preg_match_all($pattern_type, $pic_item, $match_type);              $unique_name = $this->get_unique().$match_type[1][0];            $pic_name = $this->dir_level.$this->folder.$unique_name;            $img_url = $this->home_url.$unique_name;            //save images            $write_fd = fopen($pic_name,"wb");              fwrite($write_fd, $this->CurlGet($pic_item));              fclose($write_fd);        }else{            $img_url = $pic_item;        }        $arr .= $img_url.'-';    }    //chage img new url    $new_arr = explode('-',$arr);    array_pop($new_arr);    return $op = str_replace($arr_src_remote,$new_arr,$content);}    // CURL  private function CurlGet($url){    $url=str_replace('&','&',$url);    $curl = curl_init();    curl_setopt($curl, CURLOPT_URL, $url);      curl_setopt($curl, CURLOPT_HEADER, false);       curl_setopt($curl, CURLOPT_REFERER,$url);      curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; SeaPort/1.2; Windows NT 5.1; SV1; InfoPath.2)");      curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookie.txt');      curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookie.txt');      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);      $values = curl_exec($curl);      curl_close($curl);      return $values;  }// output and run public function output(){    return $this->get_pic($this->content);}}
Copy after login


调用时:
    $folder = 'data/'.$id.'/';    $dlimg = new AutoImgDL($content,$folder);    $content = $dlimg -> output();
Copy after login


有需要的朋友也可以拿去用~本地下载没问题

求高手助一臂之力

请问要如何作出调整及修改才能变成上传去远程?

甚至放弃到想用ftp function 来完成,也没成效
Warning: ftp_put() expects parameter 3 to be a valid path, string given 这错误网上很少~也没找到确认答案到底是错什么

$host = 'ftp.XXXX.com';$usr = 'xxxx@xxxx.com';$pwd = 'xxxxxxx';$local_file=$this->CurlGet($pic_item);$ftp_path = '/'.$this->folder.$pic_name;$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");ftp_login($conn_id, $usr, $pwd) or die("Cannot login");$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);ftp_close($conn_id);
Copy after login



一直说错误~所以还是想从curl 这好像高效一点的地方入手

我能试的都试过了,不是伸手党,希望大家能协助一下

$data = array('img'=>'@'. $this->CurlGet($pic_item));

$this->CurlGet($pic_item) 返回的是什么?

$data = array('img'=>'@'. $this->CurlGet($pic_item));

$this->CurlGet($pic_item) 返回的是什么?


一大堆的乱码
估计就是图片档案吧  (为什么说估计?这类已经是1年多前拼凑起来的,看了下代码,应该是图片)

$data = array('img'=>'@'.  $this->CurlGet($pic_item));
这里需要绝对路径的文件名

$data = array('img'=>'@'.  $this->CurlGet($pic_item));
这里需要绝对路径的文件名


你是指远程图片的直接网址?

文件名和网址还是有区别的吧?

文件名和网址还是有区别的吧?


你好,先谢谢你几次的回应及帮助

我的意思是$data = array('img'=>'@'.  $this->CurlGet($pic_item));

要用上的是远程还是别家人我没下载时的网址吧?  还是目标的 绝对路径的文件名 (附件服务器上将会保存的位置)? 

其实我这段CURL都只是参考手册而生成的,不知道这段CURL本身有没有问题?

或者整个思路是否有更好的走向?

我每篇文章一般不会超过15~20张图片~用CURL比较好还是用ftp_connect比较好?

啊对了~版主我明白你的意思

你说我要加上类似这样的句子
$data = array('img'=>'@'. dirname(__FILE__).'/img/login.gif');

但问题是....

我在作操时根本还未有绝对路径
我原来的代码(整体) 在#1 
63行开始~用CURL下载

所以我才会试用CURL的$this->CurlGet($pic_item)才填在这位置

如果我是不在自己主机上的话,等于远程再上传去远程的话我该如何是好?

你自己的服务器为 A,远程服务器为 B
那么 $this->CurlGet($pic_item) 取回的是 B 中的图片数据
需要保存成文件于 A,然后再 $data = array('img'=>'@'. '保存的文件名');
才可以通过 curl 上传

如果想直接发送数据可话,可见我 blog 中的另类做法  http://blog.csdn.net/xuzuning/article/details/7444709

图片需要使用绝对地址,不是网址
例如 获取当前目录的图片绝对地址,可以这样写: dirname(__FILE__).'/文件名';

谢谢两位版主的意见

我试了xuzuning大哥的blog中的那个做法
加入了在我的类中,试了好多次都不成功

我的案例是否建立个临时目录再上去会更简单?
在我的类中再加多一个FUNCTION(步骤)做 需要保存成文件于 A,然后再 $data = array('img'=>'@'. '保存的文件名');  ?

能否跟少少提示?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

See all articles