matt
matt

Reputation: 44293

htaccess password protection and mod-rewrite?

i wonder how i can solve the following problem. on the root directory of my server lies a file calles upload.php

i want to be able to add a "/upload" (without .php) to my URL and the browser should ask for a password (and maybe username if possible). I i enter the password (and username) correctly upload.php should be opened.

Is this possible with htaccess?

Upvotes: 1

Views: 1215

Answers (1)

Artefacto
Artefacto

Reputation: 97815

Yes, both those are two distinct questions.

First: remove the .php extension

There are mainly two ways of doing this.

  • Enable content negotiation throws MultiViews. This will allow you to refer to other resources without extension and even have several files with similar names but different extensions and let Apache pick the best according to what the browser prefers. See the link. You can enable it with Options +MultiViews in a <Directory> block in http.conf or .htaccess if you allows override for this option.
  • Use mod_rewrite. A rule specifically for your case could be RewriteRule ^upload$ upload.php. This can also be put in a <Directory> block in http.conf or .htaccess (if activated). You will need to have enabled mod_rewrite and the rewrite engine with RewriteEngine on.

Seconds: require authentication

You can do this both with PHP and Apache.

  • For Apache, see the docs here.
  • For PHP, using basic authentication (be warned the password will be sent to the server in plain text and unless you are using https it may be snooped by someone watching your traffic), you can do something like this:

 

function send401() {
    $realm = "Credentials for upload";
    header('WWW-Authenticate: Basic realm="'.$realm.'"');
    header('HTTP/1.1 401 Unauthorized');
    die();
}

function verify_credentials($user, $password) {
    //check user and password here. Return true or false
    return true;
}

if (!array_key_exists('PHP_AUTH_USER',$_SERVER) ||
        !array_key_exists('PHP_AUTH_PW',$_SERVER)) {
    send401();
}
elseif (!verify_credentials($_SERVER['PHP_AUTH_USER'],
        $_SERVER['PHP_AUTH_PW']))
    send401();

//if it gets here, the user was successfully authenticated

Upvotes: 2

Related Questions