douhuan1380 2015-01-14 15:06
浏览 107
已采纳

使用cUrl请求svg.sencha.io时出现错误请求

I'm trying to use Extjs's feature to convert graphics into images. I'm not requesting svg.sencha.io directly from the javascript, instead, I'm trying to call using cUrl in my php code. For some reasons, calling it from the php is my only option and with the cUrl code that I'm using right now, I always get "Bad request". So, my question is: Have anyone around here dealt with this situation before? Here is the code I'm trying to work with:

    $url = 'http://svg.sencha.io';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $file = curl_exec($ch);

    curl_close($ch);

    var_dump($file);

The $_POST contains the parameters type, width, height and svg. They seem to be fine, because I runned cUrl directly from my machine and it worked. So the problem really is with cUrl and php. The var_dump($file);prints string(12) "Bad request."

I would really appreciate some help, I've been stuck in this for awhile now.

  • 写回答

1条回答 默认 最新

  • douwen5741 2015-01-14 16:20
    关注

    I found the solution (at least for now it seems to be working).

    The solution was not use cUrl and instead use an alternative. So, I searched for some of that and I came into this post: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/. The function on the post didn't work for me at first, but after reading almost all of the comments, I made a little change and this is the function that make a POST request to svg.sencha.io and returns the image correctly:

    function _postRequest($url, $data, $optional_headers = null) {
        $params = array('http' => array(
                        'method' => 'POST',
                        'content' => http_build_query($data)
                   ));
        if ($optional_headers !== null) {
            $params['http']['header'] = $optional_headers;
        }
        $ctx = stream_context_create($params);
        $fp = @fopen($url, 'rb', false, $ctx);
        if (!$fp) {
            throw new Exception("Problem with $url, $php_errormsg");
        }
        $response = @stream_get_contents($fp);
        if ($response === false) {
            throw new Exception("Problem reading data from $url, $php_errormsg");
        }
        return $response;
    }
    

    According to someone on the comment section of that post, this method is slower than cUrl (and the process is slow indeed), but apparently there isn't other options.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料