Home  >  Article  >  Backend Development  >  Example of using curl to make post request in PHP

Example of using curl to make post request in PHP

WBOY
WBOYOriginal
2016-08-08 09:28:441163browse

You need to use curl's POST request to obtain data from a third-party server at work. The following is the PHP version of the implementation code for reference.

<?php
    $url = "http://hao.qq.com/lunbo/switch.php";
    $data = array("code"=>"find_wonder");

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
    curl_setopt($ch, CURLOPT_ENCODING, ""); //必须解压缩防止乱码
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12");
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);

    $output = curl_exec($ch);
    curl_close($ch);

    print_r($output);
?>

What needs to be noted here is that the data returned by hao.qq.com is When sent by gzip and chunk, the automatic decompression function of curl must be enabled to obtain the decompressed data, otherwise it will cause garbled data.

Record the above source code file as curl_post.php and execute it on the command line

php curl_post.php

The following is an example of the obtained results


The above example is to send a POST request to hao.qq.com to obtain the specified code fragment. It is a mixture of div and script code fragments, and will generate something similar to the following Page effect


The above introduces the example of using curl to make a post request in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PSR-4 ExampleNext article:PSR-4 Example