https://openclassrooms.com/forum/sujet/curl-php-obtention-dune-page-blanche
-
-
Save julp/7331ebe6e5c7e138feaeee73b806be4c to your computer and use it in GitHub Desktop.
[OC] Passer un formulaire protégé par token CSRF avec cURL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
const CSRF_FIELD_NAME = '_csrf_token'; | |
const COOKIE_FILE = __DIR__ . '/cookie.txt'; | |
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'; | |
libxml_use_internal_errors(true); | |
# c'est laid mais le but est de préalablement s'assurer que le fichier existe et que l'on peut y écrire | |
if (false === ($fp = fopen(COOKIE_FILE, 'w'))) { | |
echo "Impossible de créer/tronquer ", __FILE__; | |
exit; | |
} | |
fclose($fp); | |
$curl = curl_init(); | |
curl_setopt_array( | |
$curl, | |
[ | |
CURLOPT_URL => 'http://localhost:4004/bidule/new', | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_USERAGENT => USER_AGENT, | |
CURLOPT_COOKIEJAR => COOKIE_FILE, | |
] | |
); | |
if (false === ($response = curl_exec($curl))) { | |
echo "Requête #1 a échoué : ", curl_error($curl); | |
exit; | |
} | |
curl_close($curl); | |
$doc = new DomDocument; | |
$doc->loadHTML($response); | |
$xpath = new DomXPath($doc); | |
$csrf = $xpath->query('//form//input[@name = "' . CSRF_FIELD_NAME . '"][last()]'); | |
if (1 != $csrf->count()) { | |
die("Impossible de trouver le token CSRF"); | |
} | |
$token = $csrf->item(0)->getAttribute('value'); | |
$curl = curl_init(); | |
curl_setopt_array( | |
$curl, | |
[ | |
CURLOPT_URL => 'http://localhost:4004/bidule', | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_USERAGENT => USER_AGENT, | |
CURLOPT_COOKIEFILE => COOKIE_FILE, | |
CURLOPT_POST => true, | |
CURLOPT_POSTFIELDS => http_build_query( | |
[ | |
CSRF_FIELD_NAME => $token, | |
'bidule' => [ | |
# <input name="bidule[name]" ...> | |
'name' => 'som nom', | |
# <textarea name="bidule[description]"> | |
'description' => 'sa description', | |
], | |
], | |
'', | |
'&' | |
), | |
] | |
); | |
if (false === ($response = curl_exec($curl))) { | |
echo "Requête #2 a échoué : ", curl_error($curl); | |
exit; | |
} | |
curl_close($curl); | |
// var_dump($response); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment