jueves, octubre 13, 2016

Invocar un script php via POST desde PHP y no morir en el intento

Hacer algo tan sencillo como invocar un script PHP vía POST, algo que desde HTML es tan fácil cómo :


Se vuelve sorprendentemente complicado cuando en vez de invocar el ws.php usamos otro script para invocar, por ejemplo porqué estamos haciendo un plugin para wordpress.

Después de pasar unas cuantas horas debugando y paseando por los foros de stackoverflow he encontrado la solución, que consiste en ajustar bien las cabeceras http, y aquí la dejo para quien pueda ser útil en forma de función.

function ws_envia($data, $url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER,
        array("X-HTTP-Method-Override:'POST'",
            'Content-Type:application/x-www-form-urlencoded',
            'Content-Length: ' . strlen(http_build_query($data))));
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    $response = curl_exec($ch);
}

No hay comentarios:

Publicar un comentario