Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active December 16, 2015 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrobinsonc/5452853 to your computer and use it in GitHub Desktop.
Save jrobinsonc/5452853 to your computer and use it in GitHub Desktop.
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment