How To Use cURL (in PHP) For Authentication And SSL Communication Cómo usar el enrollamiento (en PHP) para autenticación y SSL Comunicación
Using cURL (in PHP) to access http s url is often not as simple as using the proper url. El uso de enrollamiento (en PHP) para acceder url http s a menudo no es tan sencillo como utilizar la URL adecuada. Using it for authentication is also not very clearly documented. Su utilización para la autentificación tampoco está muy claramente documentada. This is a mini tutorial for both accessing https url’s as well as for http authentication. Este es un mini tutorial para acceder a ambos url https, así como para la autentificación http.
The following is a simple example which show the most common options you will ever need to use to access https url’s as well as for http authentication. El siguiente es un ejemplo sencillo que muestran la opciones más comunes que usted necesitará siempre a utilizar para acceder a la url https, así como para la autentificación http.
// The usual - init a curl session and set the url / / La habitual - init curl un período de sesiones y fijar la url
$ch = curl_init(); $ ch = curl_init ();
curl_setopt($ch, CURLOPT_URL, $base_url); curl_setopt ($ ch, CURLOPT_URL, $ base_url);
// Set your login and password for authentication / / Establezca su nombre de usuario y contraseña para la autentificación
curl_setopt($ch, CURLOPT_USERPWD, ‘login:pasword’); curl_setopt ($ ch, CURLOPT_USERPWD, 'login: pasword');
// You can use CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, / / Puede utilizar CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE,
// CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE / / CURLAUTH_NTLM, CURLAUTH_ANY y CURLAUTH_ANYSAFE
// / /
// You can use the bitwise | (or) operator to combine more than one method. / / Puede utilizar el bitwise | (o) operador para combinar más de un método.
// If you do this, CURL will poll the server to see what methods it supports and pick the best one. / / Si usted hace esto, se Curl servidor de la encuesta para ver qué métodos soporta y elige la mejor.
// / /
// CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | / / CURLAUTH_ANY es un alias de CURLAUTH_BASIC | CURLAUTH_DIGEST |
// CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM / / CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM
// / /
// CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | / / CURLAUTH_ANYSAFE es un alias de CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE |
// CURLAUTH_NTLM / / CURLAUTH_NTLM
// / /
// Personally I prefer CURLAUTH_ANY as it covers all bases / / Personalmente prefiero CURLAUTH_ANY ya que abarca todas las bases
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt ($ ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// This is occassionally required to stop CURL from verifying the peer’s certificate. / / Esto es a veces obligados a dejar de curl de verificar el certificado de pares.
// CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if / / CURLOPT_SSL_VERIFYHOST posible que también tenga que ser TRUE o FALSE si
// CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2 - check the existence of a / / CURLOPT_SSL_VERIFYPEER está deshabilitada (su valor por defecto es 2 - comprobar la existencia de un
// common name and also verify that it matches the hostname provided) / / Nombre común y también verificar que coincida con el nombre de host proporcionado)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, false);
// Optional: Return the result instead of printing it / / Opcional: Regresa el resultado en lugar de imprimirla
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1);
// The usual - get the data and close the session / / La habitual - obtener los datos y cerrar la sesión
$data = curl_exec($ch); $ data = curl_exec ($ ch);
curl_close($ch); curl_close ($ ch);
Use the above as a template for your code to simplify your data access using cURL. Use lo anterior como una plantilla para el código para simplificar el acceso a los datos utilizando el enrollamiento.
PS. The challenge with cURL documentation in PHP is that it is hard to find what you need from hundreds of available options and without enough examples of common use cases. El reto con cURL documentación en PHP es que es difícil encontrar lo que necesita de cientos de opciones disponibles y sin suficientes ejemplos de casos de uso común. What is needed is a series of How-To’s like the mini-tutorial above. Lo que se necesita es una serie de How-To's como el mini-tutorial.
Filed under Filed under Computer Security Seguridad informática , Headline News Headline News , How To Cómo , PHP , Tech Note Nota técnica , Web , Web Services Web Services | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | este artículo |
Email this Article Enviar artículo
You may also like to read También puede leer |





October 31st, 2006 at 10:06 pm 31 de octubre de 2006, a las 10:06 pm
[...] Let’s take a PHP script that does a number of CURL calls as an example. [...] Tomemos un script PHP que hace una serie de curl pide a modo de ejemplo. PHP gives you access to libcurl a really powerful tool for calling up other web pages, web services, RSS feeds, and whatever else you can dream up, right in your PHP code. PHP le da acceso a libcurl realmente un instrumento poderoso para llamar a otras páginas web, servicios web, los canales RSS, y todo lo que usted puede soñar, justo en su código PHP. This article is not a general introduction to CURL, so I won’t go into detail, but basically the CURL functions allow your code to make requests and get responses from web sites just like a browser. Este artículo no es una introducción general a curl, por lo que no voy a entrar en detalles, pero básicamente las funciones Curl permitir que su código para hacer peticiones y recibir respuestas de los sitios web al igual que un navegador. You can then parse the results use the data on your site. A continuación, puede analizar los resultados de utilizar los datos en su sitio. [...]
November 2nd, 2006 at 4:48 am 2 de noviembre de 2006, a las 4:48 am
[...] [...] [...] [...]
November 28th, 2007 at 12:02 pm 28 de noviembre de 2007, a las 12:02 pm
Thank you for this article and all of the information you’ve provided. Gracias por este artículo y toda la información que ha proporcionado.
After I had my prototype remote log-in system working, I moved it to a secure server, and nothing worked anymore. Después tuve mi prototipo de mando a distancia para acceder al sistema sistema de trabajo, me mudé a un servidor seguro, trabajado y nada más.
Then I Googled for a couple of hours, until I found this page. Entonces me Googled durante un par de horas, hasta que encontré esta página. Awesome! Imponente! Everything is working again. Todo está funcionando de nuevo.
Yes, you are absolutely right: It’sa jungle out there when you’re trying to find which CURL options are applicable and will actually work with any given situation. Sí, tiene usted toda la razón: Es una jungla allá afuera cuando usted está tratando de encontrar opciones que Curl son aplicables y en realidad funcionan con cualquier situación dada.
Hats off to you! Hats Off to you! You made my day! Usted ha hecho mi día!
January 15th, 2008 at 2:46 pm 15 de enero de 2008 a 2:46 pm
Thanks for the info. Gracias por la info.
One small thing: curl_exec() should have $ch as the parameter: Una pequeña cosa: curl_exec () debería tener $ ch como el parámetro:
$data = curl_exec($ch);$ data = curl_exec ($ ch);January 15th, 2008 at 10:50 pm 15 de enero de 2008 a 10:50 pm
Thanks. Gracias. Corrected. Corregido.
March 29th, 2008 at 6:22 am 29 de marzo de 2008 a 6:22 am
// CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | / / CURLAUTH_ANYSAFE es un alias de CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE |
// CURLAUTH_NTLM / / CURLAUTH_NTLM
// / /
problem pls check it… PLS problema comprobarlo…
May 7th, 2008 at 9:00 am 7 de mayo de 2008 a las 9:00 am
hello, Hola,
I tried ur code for a different website but it says there is syntax error(unexpected ‘:’ in that specific line in the line which we are supposed to edit our username and password to that site.. as i looking fro such similar login codes i would be thankful if u could help, He intentado ur código de un sitio web diferente, pero dice que hay error de sintaxis (inesperada »:« en esa línea específica en la línea que se supone que tenemos que editar nuestro nombre de usuario y contraseña para ese sitio .. i como buscando vaivén tales códigos de acceso similares i sería agradecido si u podría ayudar,
Thanks and regards, Gracias y saludos,
Rahul.. Rahul ..