Posting data to a URL with PHP

Primary tabs

If you want to send data to a web site, you can either POST or GET.

GET is easy - you just read the web page contents and pass the data as a variable in the URL.

$data = array();
$data["key"] = $value;
...
$url = "http://domain.com?data=" . json_encode($data);
file_get_contents($url)

However, URLs over 2,000 characters may cause errors in some browsers. Thus limiting the amount of data you can send.

POST does not have this limit. This function allows you to POST data to a URL.

    function file_post_contents($url, $data_as_array = array(), $optional_headers = null) {
        if (is_null($data_as_array)) {
            $data_as_array = array();
        }
        $data = http_build_query($data_as_array);
        $params = array('http' => array(
                    'method' => 'POST',
                    'content' => $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;
    }

Each key in the $data array will be available in the $_POST variable.

Tags:

Your IP Info

IP Address Locator

Speed Test

Test how fast your Internet connection really is.

DropBox

Use this link to get DropBox http://db.tt/iQHWaaF