Skip to content

Instantly share code, notes, and snippets.

@amdrade
Last active April 4, 2020 06:05
Show Gist options
  • Save amdrade/7248abf2a5006f01fbcbea6a6606511d to your computer and use it in GitHub Desktop.
Save amdrade/7248abf2a5006f01fbcbea6a6606511d to your computer and use it in GitHub Desktop.
PHP: Exemplo cURL com autenticação HTTP básica
<?php
// index.php
<?php
$aDados = ['item1' => 'value1', 'item2' => 'value2', 'dados' => ['a','b','c']];
$username = 'user';
$password = 'pass';
$sUrl = 'http://localhost/projetos/estudos/php/curl/response.php/?item3=value3&item4=value4';
$sHttpBuildQuery = http_build_query($aDados);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $sUrl );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_FAILONERROR, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $sHttpBuildQuery );
curl_setopt( $ch, CURLOPT_USERPWD, "$username:$password" );
curl_setopt( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
if (!$retorno = curl_exec( $ch )) {
echo '</pre>'; echo 'Error: "' . curl_error( $ch ) . '" - Code: ' . curl_errno( $ch ); echo '</pre>';
}
curl_close($ch);
echo '<pre>'; print_r($retorno); echo '</pre>';
//auth.php
echo '<pre>'; print_r('REQUEST'); echo '</pre>';
echo '<pre>'; print_r($_REQUEST); echo '</pre>';
echo '<pre>'; print_r('GET'); echo '</pre>';
echo '<pre>'; print_r($_GET); echo '</pre>';
echo '<pre>'; print_r('POST'); echo '</pre>';
echo '<pre>'; print_r($_POST); echo '</pre>';
echo '<pre>'; print_r('PHP_AUTH_USER'); echo '</pre>';
echo '<pre>'; print_r($_SERVER['PHP_AUTH_USER']); echo '</pre>';
echo '<pre>'; print_r('PHP_AUTH_PW'); echo '</pre>';
echo '<pre>'; print_r($_SERVER['PHP_AUTH_PW']); echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment