Search code examples
csvphp-5.3

Use of csv with php


I have a requirement where I need to work my login form logic using a csv file. 'A' column in csv file has all Usernames and 'T' column has website names. Now the user logs in by typing in their usernames, and depending on that I have to redirect them to the website entered in column T. How will I use php to accompalish this?

A           T
ABC        www.test.com
DEF        www.test1.com

Solution

  • You need to use fgetcsv() in order to read a line from a csv file. Have a look at the code below, it should cover your case:

    $user = "test";
    $file = fopen('file.csv', 'r');
    $lines = explode("\n", $file);
    while(($csv = fgetcsv($line, "\t")) !== FALSE) {
        // Assuming that string are separated by TAB instead comma
        if($csv[0] == $user) {
            header('Location: '.$csv[1]);
            exit();
        }
    }
    

    Edit: Code fixed. Wasn't working as fgetcsv requires a file handle to read from.