A cfhttp “POST” in php

后端 未结 2 2051
佛祖请我去吃肉
佛祖请我去吃肉 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.

提交回复
热议问题