How to Set PHP_AUTH_USER and PHP_AUTH_PW in PHP

Kevin Amayi Feb 02, 2024
  1. Use the curl Post Request to Set PHP_AUTH_USER and PHP_AUTH_PW in PHP
  2. Use the curl Request in Command Line to Set PHP_AUTH_USER and PHP_AUTH_PW in PHP
  3. How to Confirm if the Values PHP_AUTH_USER and PHP_AUTH_PW Have Been Set Successfully in PHP
How to Set PHP_AUTH_USER and PHP_AUTH_PW in PHP

This article will look at how to set PHP_AUTH_USER and PHP_AUTH_PW using the curl request in PHP and use curl request through the command line. It will also show how to confirm if the values, PHP_AUTH_USER and PHP_AUTH_PW, have been set successfully.

Use the curl Post Request to Set PHP_AUTH_USER and PHP_AUTH_PW in PHP

We will set the username and password by sending PHP code a curl request.

<?php
    $username = 'Kevin';
    $password = 'Musungu455';
    $url = 'http://localhost:2145/test2';
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($c, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    $output = curl_exec($c);
    $info = curl_getinfo($c);
    print_r($info);
    curl_close($c);
?>

Output:

Array
	(
		[url] => http://localhost:2145/test2
		[content_type] => text/html; charset=iso-8859-1
		[http_code] => 301
		[header_size] => 262
		[request_size] => 105
		[filetime] => -1
		[ssl_verify_result] => 0
		[redirect_count] => 0
		[total_time] => 0.000658
		[namelookup_time] => 0.000132
		[connect_time] => 0.000209
		[pretransfer_time] => 0.000246
		[size_upload] => 0
		[size_download] => 236
		[speed_download] => 358662
		[speed_upload] => 0
		[download_content_length] => 236
		[upload_content_length] => -1
		[starttransfer_time] => 0.000604
		[redirect_time] => 0
		[redirect_url] => http://localhost:2145/test2/
		[primary_ip] => 127.0.0.1
		[certinfo] => Array()
		[primary_port] => 2145
		[local_ip] => 127.0.0.1
		[local_port] => 58738
		[http_version] => 2
		[protocol] => 1
		[ssl_verifyresult] => 0
		[scheme] => HTTP
	)

Use the curl Request in Command Line to Set PHP_AUTH_USER and PHP_AUTH_PW in PHP

We will set the username and password by sending a curl request through the command line.

curl --user Kevin:Musungu455 http://localhost:2145

How to Confirm if the Values PHP_AUTH_USER and PHP_AUTH_PW Have Been Set Successfully in PHP

We will check if the username and password have been set, and if so, display a success message with the username and password.

<?php

    if(!isset($PHP_AUTH_USER)) {
        Header("WWW-Authenticate: Basic realm=\"My Realm\"");
        Header("HTTP/1.0 401 Unauthorized");
        echo "Sign in cancelled\n";
        exit;
    } else {
        echo "Hello $PHP_AUTH_USER.<P>";
        echo "You entered $PHP_AUTH_PW as your password.<P>";
    }
?>

Output:

Hello Kevin.
You entered Musungu455 as your password.