Tag Archives: htaccess

How to wrap basic HTTP authentication with PHP

Suppose you have a file hosted on an Apache server that is protected by Basic HTTP Authentication, often via an old-school ‘.htaccess’ file, to prevent anonymous users from downloading it without a valid username/password. Then someone asks you to wrap that protected file download with some kind of GUI, maybe a simple HTML form to gather some standard user data (e.g. name and email address). The trouble is once the user has submitted the form they then get prompted separately by the browser to enter a username/password for the HTTP authentication, and this two step process is a bad user experience and looks unprofessional. What you really want to do is ask the user for the username and password as part of the first form, and then just supply those credentials behind the scenes so the download just starts once the form has been submitted. I was recently asked to solve this exact problem, and there simply wasn’t time to address this properly with a nicer solution.

So here is a simple way to pass in credentials for Basic HTTP Authentication from a PHP download script. You must have the PHP “Client URL Library” (“cURL”) extension installed on the web server hosting the PHP script.

If you just want to download the complete working script, you can get it from my GitHub Gist. If you’d like to read about some of the details, please continue…

Continue reading How to wrap basic HTTP authentication with PHP