Skip to content

Instantly share code, notes, and snippets.

@jonhattan
Created June 4, 2013 08:28
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jonhattan/5704465 to your computer and use it in GitHub Desktop.
Save jonhattan/5704465 to your computer and use it in GitHub Desktop.
PHP script using curl to login to a website using POST, store the cookie and request pages subsequently. The script also provides placeholders to parse data from a page and create a node in Drupal. It is intended to be used as a drush script (drush php-script --script-path=/path/to/script/folder thingie2drupal)
<?php
$URL = 'http://example.com/login.php';
$user = 'USER';
$pass = 'PASS';
$cookie_path = dirname(__FILE__).'/cookie.txt';
/**
* Hace login en la web enviando un POST con el usuario y contraseña.
*/
function login($user, $pass) {
global $cookie_path;
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'Usuario='.$user.'&Password='.$pass);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_path);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
/**
* Recupera una página html.
*/
function get($url) {
global $cookie_path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_path);
$html = curl_exec($ch);
curl_close($ch);
return $html;
}
/**
* Parsea el html y retorna un array con todos los datos relevantes.
*/
function parse($html) {
// Se deja esta implementación como ejercicio para el lector.
}
/**
* Crea un nodo a partir del contenido de $data
*/
function create_node($data) {
// guarda un nodo
$node = (object)array(
'title' => 'Loren ipsum',
'body' => 'dolor sit amet'
);
$node = node_save($node);
if (!$node->nid) {
print "ERROR: error al crear un nodo para $data"; // TODO: $data se imprimirá como 'Array'
}
// lo asocia a una tax
taxonomy_node_save($node, array($tax1, $tax2, $tax3));
}
/**
*
*/
function main() {
if (!login($user, $pass)) {
print "ERROR: no pude hacer login.\n";
exit;
}
$html = get($url);
$data = parse($html);
create_node($data);
}
main();
@pabloguillermoalarcon
Copy link

Lo use y no me funciono, podrias explicar como usarlo.
Saludos

@parsidea
Copy link

parsidea commented Apr 6, 2019

Hi My friend
i want use your cod in a login to blog site and send post to site
how are you
site is blogfa.com
thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment