search
HomeBackend DevelopmentPHP Tutorial有关CURL 将图片上传去远程服务器

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

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

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

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

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

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


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

我试了下把这一段改成:
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);


但却完全没效
有关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;        }    }?>


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

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


回复讨论(解决方案)

整个自动下载的类

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);}}


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


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

求高手助一臂之力

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

甚至放弃到想用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);



一直说错误~所以还是想从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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use