A cfhttp “POST” in php

后端 未结 2 2052
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 14:37

I have a ColdFusion page that appends the a URL with form variables. I\'m trying replicate this code in php:

 

        
相关标签:
2条回答
  • 2021-01-22 14:51

    In PHP HTTP is intergrated as a so called stream wrapper­Docs. That means you can use it with standard file- and stream-related functions:

    $url = 'http://api.test.com/import-lead-data.php';
    $result = file_get_contents($url);
    

    This would create a standard GET request. But you want to have a POST request, therefore you need to add some context options­Docs:

    $url = 'http://api.test.com/import-lead-data.php';
    $options['http'] = array(
        'method' => "POST", 
    );    
    $context = stream_context_create($options);    
    $result = file_get_contents($url, NULL, $context);
    

    This would make the POST request instead of GET. What's still missing are the form fields. Let's say you have all fields in an array of key => value pairs:

    $url = 'http://api.test.com/import-lead-data.php';
    $content = http_build_query($form_fields);    
    $options['http'] = array(
        'method' => "POST", 
        'content' => $content,
    );    
    $context = stream_context_create($options);    
    $result = file_get_contents($url, NULL, $context);
    

    Hope that's helpful. Naturally you can use as well the http_post_data or http_post_fields function as well if you have it available.

    See as well: HEAD first with PHP Streams.

    0 讨论(0)
  • 2021-01-22 15:03

    The HTTP PECL extension (which contains the HTTPRequest class) isn't part of a default PHP installation.

    I would take a look at CURL: http://php.net/manual/en/book.curl.php. You can set the HTTP method and parameters.

    Or, if you don't mind using a framework, checkout the Zend FW HTTP Client module: http://framework.zend.com/manual/en/zend.http.html

    Here's an example of using CURL to do a post request: http://davidwalsh.name/execute-http-post-php-curl

    0 讨论(0)
提交回复
热议问题