Jump to content

opening, reading and storing contents of a CSV file


cookie_crumble

Recommended Posts

Hi

 

I am very new at this PHP business so pls be patient.

 

what i an trying to do:

 

  • Open a CSV file using PHP
  • store each element of the file in an array
  • Use the array to validate user input against what is stored in the CSV file for example Username and password validation

 

I know this seems simple to someone who knows but it is not to me  :-[

 

My goal is

 

If(username and password exists in CSV file and they match those entered by the user on the webpage)

{

welcome back user X

}

 

else

{

invalid username or password

}

 

What i have so far (but does not work correctly) is:

 

<CODE>

$user_name = (trim($_POST['user_name']));

$password = (trim($_POST['password']));

$sCSVFile = 'users.txt';

$fp = fopen($sCSVFile,'rt');

 

  while(!feof($fp))

  {

$users = fgetcsv($fp);

$number_users = count($users);

 

  for ($i=0; $i<$number_users; $i++)

    {

$line = explode(",", $users[$i]);

 

foreach($line as $value)

echo "$value<br>";

    }

 

<END>

 

this code seems to print what is in the file using $value but i am not able to use $value as a comparison for the $user_name entered by the user.

 

There is currently only 2 columns in the csv file "username,password"

Any hints would be appreciated

 

Regards

 

 

 

what i would recommend doing is to phrase the file into an array like

array(

0 => array(

0=> "username from file"

1=> "password from file"

)

)

here is some untested sample code

$user_name = (trim($_POST['user_name']));
$password = (trim($_POST['password']));
$search_array = array($user_name,$password);
$sCSVFile = 'users.txt';
$fp = fopen($sCSVFile, 'rt');
$array = array();
while (!feof($fp)) {
 $array[] = fgetcsv($fp);
}
if(in_array($search_array,$array)){
echo "Login success";
}else{
echo "login failed";
}

it puts all the lines into a array then searches the array for a line that matches the user input

Please report back i am interested to see if my code works

 

Scott.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.