Password protecting a file using PHP functions
How to password protecting a file using FTP functions
There is an alternative to using .htaccess and .htpassword to password protect files.
PHP can mimic the HTTP authentication process by setting the appropriate headers for the username/password dialog box to pop up. The values entered in the box are stored in the $PHP_AUTH_USER, $PHP_AUTH_PW and $PHP_AUTH_TYPE variables.
In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP 4, and --with-ftp when using PHP 3.
To see if your PHP installation supports FTP Functions you can run the phpinfo() function and look for "FTP Functions" :
PHP Code:
<?php
phpinfo()
?>You will be using the following two functions:
Function ftp_connect (string host, int [port]) opens up a FTP connection to the specified host.
The port parameter specifies an alternate port to connect to. If it is omitted or zero, then the default FTP port, 21, will be used. Returns a FTP stream on success, FALSE on error.
Function ftp_login (int ftp_stream, string username, string password)
Logs in the given FTP stream returned from ftp_connect().
Returns TRUE on success, FALSE on error.
Create a file called pftplogin.php.
Note: You must have an FTP account for the server that you are going to run this script on.
PHP Code:
<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Secure FTP Login"');
header('HTTP:/1.0 401 Unauthorized');
echo "Authentication Failed!";
exit();
}
// check for the existence of a value for $PHP_AUTH_USER and display the username/password box if it does
// not exist then exit the script.
if(!isset($PHP_AUTH_USER)) {
authenticate();
exit;
echo "Authorization Failed\n";
}
else {
$ftp_server="localhost"; // replace localhost with your ftp server
// set up basic connection
$conn_id = ftp_connect("$ftp_server");
// login with username and password
// use @ to suppress error messages returned by ftp_login() function because you will be printing
// your own error messages
$login_result = @ftp_login($conn_id, "$PHP_AUTH_USER", "$PHP_AUTH_PW");
// check connection
if ((!$conn_id) ¡¡ (!$login_result)) {
authenticate();
echo "Ftp connection has failed!";
echo "Attempted to connect to $ftp_server for user $PHP_AUTH_USER";
die;
}
// close the FTP stream
ftp_quit($conn_id);
?>To password protect a file, include pftplogin.php at the top of the file:
PHP Code:
<?include "pftplogin.php";?>
If you included pftplogin.php in secretfile.php and viewed it in your browser, the authenticate dialog box
will pop up. If your attempt to login is successful the browser will display secretfile.php.
See it in action. ¦ Get complete code.