0

I've written a simple bit of code to test two parameters and forward the user to a link.

error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$secure_box=$_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$data=fgetcsv($fh);
$first_name=$data[0];
$date=$data[1];
$url=$data[2];
{
if($secure_box == $first_name AND $date>=$now)
{
   header("Location: $url");
   exit();
}
else
  {
   header("Location: http://localhost/x/delivery_method.html");
  }
    exit;
?>

My problem here is that the entire CSV file is not being read. What can I do ?

Vinoth
  • 1,339
  • 6
  • 23
  • 42
  • 2
    Well... you're... only reading one line... Or am I misunderstanding something? – deceze Jun 16 '11 at 06:56
  • 1
    What is db.csv? Is it a single line, delimited by commas, and with each field optionally enclosed with double quotes? – Matthew Jun 16 '11 at 06:58
  • 2
    The answer given on http://stackoverflow.com/questions/6332686/load-from-csv-and-forward-to-different-url shows you how to loop. – Matthew Jun 16 '11 at 07:00
  • 1
    possible duplicate of [how to extract data from csv file in php](http://stackoverflow.com/questions/2805427/how-to-extract-data-from-csv-file-in-php) – Gordon Jun 16 '11 at 07:04
  • @gordon we're both classmates working on the same project – Vinoth Jun 16 '11 at 07:06

3 Answers3

8

The entire file isn't being read because you only called fgetcsv once. fgetcsv only reads one line at a time, you need to put the that code in a loop.

Here is an example of how to use fgetcsv in a loop, from the php docs at http://www.php.net/fgetcsv:

<?php
// Example #1 Read and print the entire contents of a CSV file
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
2

This is what I've been able to come up with..Hope it's right

<?php
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");
$name_value = $_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date("d.m.Y");
$line = 1;
if (($handle = fopen("db.csv", "r")) !== FALSE)
{
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
        $num = count($data);
        $line++;
        for ($c = 0; $c < $num; $c++)
        {
            if ($name_value == $data[0] AND $data[1] >= $now)
            {
               header("Location: $data[2]");
               exit();
            }
            else
            {
                header("Location: http://localhost/x/client_unauthorized.html");
            }
        }
    }
    fclose($handle);
}   
?>
1

You can loop to read the whole file line by line until EOF, and check each row in turn.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358