descargando archivos con php curl
Una forma sencilla y eficiente para descargar archivos con curl, es crear un nuevo recurso de archivo y asociarlo a curl a través de la opción CURLOPT_FILE con curl_setopt. El siguiente ejemplo primero se autentifica contra un supuesto sitio (capturando las cookies) y luego procede a descargar el archivo (que requiere autentificación).
<?php // Data for the login $raw_post = "&". http_build_query(array("user" => "deerme")); $raw_post .= "&". http_build_query(array("passwd" => "xdxdxd")); // Login $ch = curl_init('http://www.example.com/login.aspx'); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS , $raw_post ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookie.txt'); $buffer = curl_exec($ch); // Download the file $fp = fopen("/tmp/report.xls", 'w+'); $ch = curl_init("http://www.example.com/report/get-auth-report.aspx"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookie.txt'); curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookie.txt'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_exec($ch); // Example by deerme.org
Hi, I am new to PHP… and I need to download an image from a IP camera (http://127.0.0.1/jpg/image.jpg ) and I need to authenticate for download it.
I want to use your example but I don´t understad why to use a XLS file???
I need to download the image and save it do an image folder… Would you help me please? Thanks!
Hi Sergio, Generally The IP cameras require some type of authentication, normally the WWW-Authenticate: Basic.
The next code, it tries to download a picture from a site that requests basic authentication.
PD: Remeber remove the spaces in url (code).
You can find a backup of this code in https://github.com/deerme/deerme.org/blob/master/php/harvest/curl-example-download-image-from-ip-camera.php
Thanks! I’ll try!