PHP - 使用CURL将图像文件上传到其他域 [英] PHP - Upload an image file to other domain with CURL

查看:150
本文介绍了PHP - 使用CURL将图像文件上传到其他域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个域,例如 site1.loc site2.loc 。在 site1.loc 中,我有一个如下所示的php表单文件:

 <?php 
$ c_name =;
$ c_phone =;

if($ _ SERVER ['REQUEST_METHOD'] ==POST){

$ c_name = $ _POST ['c_name'];
$ c_phone = $ _POST ['c_phone'];
$ c_pic = $ _FILES ['c_pic'] ['name']; // Image file

//提交目标网址
$ url ='http://site2.loc/handler.php';

$ fields = array(
'field1'=> $ c_name,
'field2'=> $ c_phone,
'field3'=> $ c_pic
);

$ postvars ='';
$ sep ='';
foreach($ fields as $ key => $ value)
{
$ postvars。= $ sep.urlencode($ key)。'='。urlencode($ value);
$ sep ='&';
}


//打开连接
$ ch = curl_init();

//设置url,POST变量的数量,POST数据
curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_POST,count($ fields));
curl_setopt($ ch,CURLOPT_POSTFIELDS,$ postvars);

//执行post
$ result = curl_exec($ ch);

if(curl_errno($ ch)){
echo'Error:'。 curl_error($ ch);
}
else {
echo $ result;
}

//关闭连接
curl_close($ ch);

}


echo'
< form action =method =postenctype =multipart / form-data>
名称:< input type =textname =c_namevalue ='。$ c_name。'/> < br />
电话:< input type =textname =c_phonevalue ='。$ c_phone。'/> < br />
图片:< input type =filename =c_pic/> < br />
< input type =submit/>
< / form>
';
?> site2.loc 中的

handler.php >像这样:

 <?php 
ob_start
if(!isset($ _ SESSION)){session_start(); }

//连接到DB
$ db_con = mysql_connect(localhost,root,root); //或die(Could not connect to db。 ;
if(!mysql_select_db(site2,$ db_con))die(No database selected。

// POST
if(isset($ _ POST)){
$ c_name = $ _POST ['field1'];
$ c_phone = $ _POST ['field2'];
$ c_pic = $ _POST ['field3'];

//上传文件
/ *上传图片代码在这里* /

//插入到DB
if(mysql_query(INSERT INTO kontak nama,telpon)VALUES('$ c_name','$ c_phone'))){
echoINSERT SUCCESS;
} else {
echoINSERT FAILED;
}
}

?>

此脚本适用于将数据存储到数据库,但不能上传图像文件。任何人都可以帮助我修改上面的脚本,以便上传图片文件?



感谢之前。

解决方案

在这个答案中没有代码,只是一个工作流示例将绕过 curl



<
  • site 1处理表单和上传的文件。

  • 在网站1上,一旦检查了上传的文件,请创建一个 file_get_contents ://site2.loc/pullfile.php?f = filename& sec = checkcode')调用。 pullfile.php 的内容会做到这一点,将文件从site 1拉到site 2。

  • 可以检查从 file_get_contents()返回的错误从site 2 pullfile.php ,处理它。没有错误,请删除临时文件。

  • & sec = checkcode 可用于确认文件已成功上传site 2。

  • 只是一个想法。



    编辑:一些示例代码有助于使事情更加清晰,也许:]

      // ----网站1,formprocess.php ---- 

    //你的表单处理在这里,包括
    //将上传的文件保存到临时目录。

    //一旦上传的文件检查错误,
    //你需要将它移动到一个已知的临时文件夹名为
    //'tmp'。

    //这是上传的文件名(您将
    //从$ _FILES
    中的已处理表单数据获得)对于此示例代码,它很简单硬编码
    $ site1File ='test.jpg';

    $ site1FileMd5 = md5_file('./ tmp /'.$ site1File);

    / /现在向site 2发起远程请求
    $ site2Result = file_get_contents('http://'SITE_2_URL.'/pullfile.php?f ='。$ site1File。'& md5 ='。$ site1FileMd5);

    if($ site2Result =='done'){
    unlink('./ tmp /'.$ site1File);
    } else {
    echo'< p>
    上传的文件无法传输到.SITE_2_URL。
    - 但稍后处理。
    < / p>';
    }

    这将是站点2上的'pullfile.php'

      // -----网站2,pullfile.php ----- 

    //此脚本将从站点1和
    //放在/ upload'

    //用于交叉检查上传的文件
    $ fileMd5 = $ _GET ['md5'];
    $ fileName = basename($ _ GET ['f']);

    //我们需要从站点1的'./tmp/'目录中拉取文件
    $ pullingFile = file_get_contents('http://'.SITE_1_URL.'/tmp/ '。$ fileName);

    //将该文件保存到磁盘
    $ result = file_put_contents('./ uploaded /'.$ fileName,$ pullingFile);
    if(!$ result){
    echo'错误:将文件写入磁盘时出现问题';
    exit;
    }

    $ pulledMd5 = md5_file('./ uploaded /'.$ fileName);
    if($ pullingMd5!= $ fileMd5){
    echo'Error:md5 mis-match';
    exit;
    }

    //在这一点上,一切都应该是正确的。
    //我们将完成传回网站1,所以我们知道
    //一切顺利。这样,一个'blank'
    //返回也可以被当作错误。
    echo'done';
    exit;


    I have two domain, as example site1.loc and site2.loc. In site1.loc i have a php form file like this:

    <?php
    $c_name = "";
    $c_phone = "";
    
    if($_SERVER['REQUEST_METHOD']=="POST"){
    
        $c_name = $_POST['c_name'];
        $c_phone = $_POST['c_phone'];
        $c_pic = $_FILES['c_pic']['name']; // Image file
    
            // submit target URL
            $url = 'http://site2.loc/handler.php';
    
            $fields = array(
               'field1'=>$c_name,
               'field2'=>$c_phone,
               'field3'=>$c_pic
            );
    
            $postvars='';
            $sep='';
            foreach($fields as $key=>$value) 
            { 
               $postvars.= $sep.urlencode($key).'='.urlencode($value); 
               $sep='&'; 
            }
    
    
            //open connection
            $ch = curl_init();
    
            //set the url, number of POST vars, POST data
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_POST,count($fields));
            curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
    
            //execute post
            $result = curl_exec($ch);
    
            if(curl_errno($ch)) {
                echo 'Error: ' . curl_error($ch);
            }
            else {
                echo $result;
            }
    
            //close connection
            curl_close($ch);
    
    }
    
    
    echo '
    <form action="" method="post" enctype="multipart/form-data">
        Name : <input type="text" name="c_name" value="'.$c_name.'" /> <br />
        Phone : <input type="text" name="c_phone" value="'.$c_phone.'" /> <br />
        Image : <input type="file" name="c_pic" /> <br />
        <input type="submit" />
    </form>
        ';
    ?>
    

    and handler.php in site2.loc like this:

    <?php
    ob_start();
    if (!isset($_SESSION)) { session_start(); }
    
        // CONNECT TO DB
        $db_con = mysql_connect("localhost", "root", "root");// or die("Could not connect to db.");
        if(!mysql_select_db("site2",$db_con)) die("No database selected.");
    
        // POST
        if(isset($_POST)){
            $c_name = $_POST['field1'];
            $c_phone = $_POST['field2'];    
            $c_pic = $_POST['field3'];  
    
            // UPLOAD FILE
            /* UPLOAD IMAGE CODE HERE */
    
            // INSERT TO DB
            if(mysql_query("INSERT INTO kontak (nama, telpon) VALUES ('$c_name','$c_phone')")){
                echo "INSERT SUCCESS";
            } else {
                echo "INSERT FAILED";
            }
        }
    
    ?>
    

    This script runs well for storing the data to the database, but can not for upload an image file. Can anybody help me modify scripts above in order to upload an image file?

    Thanks before.

    解决方案

    No code in this answer, just a work flow example that will bypass curl:

    1. User posts a form with the uploaded file to "site 1", as per normal.
    2. "site 1" processes the form and the uploaded file. The file is placed in a temp directory which is web accessible.
    3. On "site 1", once the uploaded file has been checked, make a file_get_contents('http://site2.loc/pullfile.php?f=filename&sec=checkcode') call. The contents of pullfile.php will do just that, pull the file from "site 1" to "site 2".
    4. The return from file_get_contents() can be checked for an error return from the "site 2" pullfile.php and on error, deal with it. No error, remove the temp file.
    5. The &sec=checkcode could be used to confirm the file has been uploaded successfully to "site 2". It could be an MD5 of the file or something else you come up with.

    Just an idea.

    Edit: Some sample code to help make things clearer, maybe :]

    // ---- Site 1, formprocess.php ----
    
    // Your form processing goes here, including
    // saving the uploaded file to a temp dir.
    
    // Once the uploaded file is checked for errors, 
    // you need move it to a known temp folder called 
    // 'tmp'.
    
    // this is the uploaded file name (which you would
    // have got from the processed form data in $_FILES
    // For this sample code, it is simple hard-coded.
    $site1File = 'test.jpg';
    
    $site1FileMd5 = md5_file('./tmp/'.$site1File);
    
    // now make a remote request to "site 2"
    $site2Result = file_get_contents('http://'.SITE_2_URL.'/pullfile.php?f='.$site1File.'&md5='.$site1FileMd5);
    
    if ($site2Result == 'done') {
        unlink('./tmp/'.$site1File);
    } else {
        echo '<p>
             Uploaded file failed to transfer to '.SITE_2_URL.'
              - but will be dealt with later.
             </p>';
    }
    

    And this will be the 'pullfile.php' on site 2

    // ----- Site 2, pullfile.php -----
    
    // This script will pull a file from site 1 and
    // place it in '/uploaded'
    
    // used to cross-check the uploaded file
    $fileMd5 = $_GET['md5'];
    $fileName = basename($_GET['f']);
    
    // we need to pull the file from the './tmp/' dir on site 1
    $pulledFile = file_get_contents('http://'.SITE_1_URL.'/tmp/'.$fileName);
    
    // save that file to disk
    $result = file_put_contents('./uploaded/'.$fileName,$pulledFile);
    if (! $result) {
        echo 'Error: problem writing file to disk';
        exit;
    }
    
    $pulledMd5 = md5_file('./uploaded/'.$fileName);
    if ($pulledMd5 != $fileMd5) {
        echo 'Error: md5 mis-match';
        exit;
    }
    
    // At this point, everything should be right.
    // We pass back 'done' to site 1, so we know 
    // everything went smooth. This way, a 'blank'
    // return can be treated as an error too.
    echo 'done';
    exit;
    

    这篇关于PHP - 使用CURL将图像文件上传到其他域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆