Matthew J. Kellett

Website Architect and Developer

Pass $_post Variables Without Forms

Intro

Ever wanted to send variables to another script without clogging up the URI? Well the following is a function which allows you to do just that :D

This is just one method that can be used to pass variables between pages. A more advanced version would be to use cURL

Usage

Using the function is easy and can be carried out with just two parameters:

  1. The URL of the page to pass the parameters through too
  2. An array of variable => value pairs to pass as $_POST parameters

As an example see the code snippets below:

$context = array(
	'post_variable1' => 'post_value1',
	'post_variable2' => 'post_value2',
	'post_variable3' => 'post_value3'
);
$something = sendPost("some-url.php", $context);

The Function

The function is as follows:

function sendPost($url, $context) {
	$context = array_change_key_case($context, CASE_LOWER);
	$contextSize = sizeof($context);
	$contextKeys = array_keys($context);
	$data = "";
	foreach ($contextKeys as $key) {
		$amp = $contextKeys === FALSE ? "" : "&";
		$data .= urlencode($key)."=".urlencode($context[$key]).$amp;
	}

	list($host,$url) = explode('/',$url,2);
	$sock = fsockopen($host, 80, $errno, $errstr, 1);
	if (!$sock) { die("$errstr ($errno) in ".__FILE__." (".__LINE__.")\n"); }
	$http_request = "POST /".$url." HTTP/1.1\r\n";
	$http_request .= "Host: ".$host."\r\n";
	$http_request .= "Content-type: application/x-www-form-urlencoded\r\n";
	$http_request .= "Content-length: " . strlen($data) . "\r\n";
	$http_request .= "Accept: */*\r\n";
	$http_request .= "\r\n";
	$http_request .= "$data\r\n";
	$http_request .= "\r\n";
	fwrite($sock,$http_request);
	$response_headers = array();
	while ($str = trim(fgets($sock))) {
		array_push($response_headers,$str);
	}
	fclose($sock);
	$errors = true;
	foreach($response_headers as $response_header) {
		if($response_header == 'HTTP/1.1 200 OK') {
			$errors = false;
		}
	}
	if (!$errors)
		return true;
	else
		return false;
}

Enjoy and please feel free to leave a comment if you use this code

Comments

There are no comments for this article

Write a comment

Write a comment

Like, follow, share us

Code Categories

Use the links below to view each of the different code snippet categories

Latest Code Snippets

Below are the latest code snippets that I have written

Donations

If you like this code snippet or use it then please donate something to me so I can continue updating this as well as creating new ones