zoukankan      html  css  js  c++  java
  • php中curl、fsockopen的应用

    最近要用到通过post上传文件,网上盛传的有curl的post提交和fsockopen,其中curl最简单,于是从最简单的说起。
    
    这是简单的将一个变量post到另外一个页面
    
    $url = '';
    $data = array('a'=> 'b');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $ret = curl_exec($ch);
    curl_close($ch);
    主要说下这个选项CURLOPT_RETURNTRANSFER:如果设置为true/1,则curl_exec的时候不会自动将请求网页的内容输出到屏幕,$ret为请求网页的内容,如果设置为false/0,则curl_exec的时候会自动将请求网页的内容输出到屏幕,此时如果请求成功的话$ret的内容是1或者true。
    
    下面是上传本地文件的代码,如果需要上传远程文件,则先down到本地,然后删掉即可(如有同学有别的办法还请告知):
    
    $url = '';
    $file = '1.jpg';
    $field['uploadFile'] = '@'.$file;(uploadFile为接收端的name名)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $field);
    $ret = curl_exec($ch);
    curl_close($ch);
    
    -------------------------------------------------------------------------------------
    
    这是fsockopen的办法:
            $uploadInfo = array(
                    'host'=>'',
                    'port'=>'80',
                    'url'=>'/upload.php'
            );
            $fp = fsockopen($uploadInfo['host'],$uploadInfo['port'],$errno,$errstr);
    
        $file = '1.jpg';
    
                    $content = file_get_contents($file);
                    $boundary = md5(time());
                    $out.="--".$boundary."
    ";
                    $out.="Content-Disposition: form-data; name="uploadFile"; filename="".$file.""
    ";
                    $out.="Content-Type: image/jpg
    
    ";
                    $out.=$content."
    ";
                    $out.="--".$boundary."
    ";
    
     
    
                    fwrite($fp,"POST ".$uploadInfo['url']." HTTP/1.1
    ");
                    fwrite($fp,"Host:".$uploadInfo['host']."
    ");
                    fwrite($fp,"Content-Type: multipart/form-data; boundary=".$boundary."
    ");
                    fwrite($fp,"Content-length:".strlen($out)."
    
    ");
                    fwrite($fp,$out);
                    while (!feof($fp)){
                            $ret .= fgets($fp, 1024);
                    }
                    fclose($fp);
                    $ret = trim(strstr($ret, "
    
    "));
                    preg_match('/http:.*/', $ret, $match);
                    return $match[0];
    
  • 相关阅读:
    Install and Configure OSSEC on Debian 7&8
    手动替换WORDPRESS的GOOGLE字体等加速【非插件】
    LDAP常用命令解析
    Install guide for OpenLDAP and GOsa 2 on Ubuntu & Debian
    Linux 转发 email Redirect local emails to a remote email account
    Ubuntu,忘记了root密码,怎么重置?
    LDAP 原理图解
    CAS实现SSO单点登录原理
    cacti 安装与 与不能显示图像故障解决方案
    LDAP概念和原理
  • 原文地址:https://www.cnblogs.com/caster/p/4140474.html
Copyright © 2011-2022 走看看