Querying a multi-column CSV file using PHP

I have a PHP-based application that I've been managing that I'm currently in the process if re-factoring.  One part of the application contains a very lengthy if/else routine that's similar to the following:

$office_username = $_SERVER['REMOTE_USER'];
if($username == 'john') {
	$email = "john4556567@domain.com";	
} else if($username == 'mary') {
	$email = "mary3533367@emaidomainladdress.com";	
	....	
	....
} else {
	$email = "test@domain.com";
}

Open in new window


The application is currently using .htdigest based authentication, and we've decided that we'd prefer to keep it this way and to NOT store the user info in the database (to avoid having to build any kind of administrative console for managing users).

Although this approach is functional, it's resulting in problems when one of the other site administrators has to update the if/else routine with another username and email address.  In other words, he sometimes fails to download the single-page application from the server prior to applying his updates, which results in my recent updates being completely "blown out", so to speak.

What I'd like to do is replace the entire if/else statement with a routine that queries a separate CSV file (that lives outside of the site root) to see if it contains the username, and that then returns the email address that corresponds to it and that's on the matching row.  For example, the format of the CSV file would be as follows:

john,john4556567@domain.com
mary,mary3533367@emaidomainladdress.com

This way, the other site administrator would haver have to touch the application's source code.  He would only need to update the CSV file.  

How might I accomplish something like this? (I'm not opposed to using an external PHP library or to using a different file format)

Thanks in advance,
- Yvan
egoselfaxisAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
One approach would be to open the CSV, loop through line by line and check the username. Something like this (untested) code should get you going in the right direction:

// Get your Username
$username = $_SERVER['REMOTE_USER'];

// Set a default email address:
$email = "test@domain.com";

// Open the file for reading
$file = fopen("users.csv","r");

// Loop through each line of the file
while(!feof($file)):
	// Read a line
	$line = fgetcsv($file);
	
	// Split the line on the comma
	$userDetails = explode(',', $line, 2);

	// Check the username
	if ($userDetails[0] == $username) {
		$email = $userDetails[1];
		break;
	}
endwhile;

// Close the file
fclose($file);

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
Couple of thoughts... You might want to treat this as an "ini" file.  PHP has a built-in parser.
http://php.net/manual/en/function.parse-ini-file.php

Email addresses are not case-sensitive.  Your business rules would establish whether the username should be case-sensitive.

If the file gets damaged, you would want to throw and exception, and probably notify an administrator immediately.  Keeping a copy trail in GIT or similar version control might be a good idea.
gr8gonzoConsultantCommented:
If your primary concern is "to avoid having to build any kind of administrative console for managing users" - is there a reason you don't just use an existing tool like HeidiSQL? It's an easy-to-use, free, Windows-based GUI for MySQL (and some other DBs, too).

Just saying - if the reason you're not moving to a database is because you think you'll have to build an admin console for it, there's a pretty easy solution to that. And HeidiSQL has a fairly intuitive console (lots of screenshots on their website), so the admin doesn't need to be a tech guru to use it, although there ARE a lot of powerful tools contained inside it (e.g. download tables as CSV for backup purposes, etc...).

I have no personal affiliation with the tool other than I've been using it for years now and I've gotten a couple of other people hooked on it, too, some of them not so tech-savvy.

A very simple database table will all but eliminate the problems you've described, and a GUI will make his job even simpler than before. Editing a CSV file always has the potential for problems if you're manually maintaining it. Trust me - lots of people have been there and everyone always gets into a situation where a quote isn't commented properly or they miss a comma or add one too many, and your authentication (and possibly application, too) is down for a chunk of time until you can find the problem in the CSV file.
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Eddie ShipmanAll-around developerCommented:
I actually do something similar with our Holiday schedule. However, I use an XML file to store my data and use SimpleXML to parse it.
Much easier to query, too!
egoselfaxisAuthor Commented:
Hi guys.  I'm so sorry for the delay in my replying to everyone's thoughtful responses here.  I've been in a holding pattern for the past week or so due to the client having gone MIA on me, and was hoping to get some feedback from him before replying.  Regardless, I guess I should just close this out for now.

Chris .. I haven't tested your PHP example yet, but it looks like it might very well fit the bill.  Thank you.

Ray  .. the approach you're suggesting sounds interesting, but knowing my client the way that I do, I'm fairly certain that he would find some way to screw things up if I gave him anything more complicated than a CSV file to work with.  Still, I learned something new .. so kudos to you.

Gr8gonzo .. your suggestion is excellent.  However, my client is often times administering his website from different locations and PCs, which means that configuring and using client software to manage the users database unnecessarily complex.  Still, .. thank you for making me aware of an excellent open source database administration tool.  I've just downloaded and installed a copy of it for myself.

Again, -- thanks all!

Regards,
- Yvan
Eddie ShipmanAll-around developerCommented:
Would have been much easier on you and the client to use XML for the configuration file and create your own management console but good luck.
gr8gonzoConsultantCommented:
A side note on the HeidiSQL - it is available as a portable app, which means you can simply save it onto a USB stick and run it straight from there, no matter what PC you're on.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.