jrobinsonc
4/24/2013 - 3:07 PM

post_request.php

<?php
 
 /**
 * Pasar variables por post.
 *
 * @author JoseRobinson.com
 * @version 201304241106
 * @link GitHup: https://gist.github.com/5452853
 * @param string $url La URL a la cual se le hará la petición.
 * @param array $data La data que se quiere enviar.
 * @param array $headers Para enviar headers adicionales.
 * @return string
 */
function post_request($url, $data, $headers = array())
{
    // Se verifican los datos.
	if (!is_array($data)) throw new Exception('Los datos deben pasarse como un array.');

	// Se verifican las cabeceras.
	if (!is_array($headers)) throw new Exception('Las cabeceras deben pasarse como un array.');

	// Se convierte la data en string (a=1&b=2).
	$data_query = http_build_query($data);
	
	// Se extrae la info de la url.
	$url_parsed = parse_url($url);
	
	// Se verifica que la petición hecha sea del tipo HTTP.
	if (@$url_parsed['scheme'] != 'http') throw new Exception('Solo se soportan peticiones HTTP.');
	
	// Se abre una conexión vía socket.
	$fp = @fsockopen(@$url_parsed['host'], 80);

	// Se verifica si se pudo abrir la conexión.
	if ($fp === FALSE) throw new Exception("No se pudo abrir la conexión con {$url_parsed['host']}.");
	
	// Se hace la petición.
	fputs($fp, "POST {$url_parsed['path']} HTTP/1.1\r\n");
	fputs($fp, "Host: {$url_parsed['host']}\r\n");
	
	if (count($headers) > 0)
	{
		foreach($headers as $headerName => $headerValue)
		{
			fputs($fp, "$headerName: $headerValue\r\n");
		}
	}
	
	fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
	fputs($fp, "Content-length: ". strlen($data_query) ."\r\n");
	fputs($fp, "Connection: close\r\n\r\n");
	fputs($fp, $data_query);

	// Se almacena el resultado en una variable.
	$result = ''; 
	while(!feof($fp)) $result.= fgets($fp, 128);
	
	// Se cierra la conexión.
	fclose($fp);

	// Se retorna el resultado.
	return $result;
}