user707165
user707165

Reputation:

Read data from CSV in PHP and then forward to a webpage

I've to redirect my user to a webpage based on his name and date. If his name does not match or his ID has expired I need to send him to a different page. If he passes these two conditions I need to redirect him to a webpage eg. www.google.com

$name_value=$_GET['query'];
$fh = fopen('db.csv', 'r');
$now = date(); 
$data=fgetcsv($fh); 
$name=$data[0];
$date=$data[1];
$url=$data[2];
if($name_value == $name)
{
  if($date==$now)
  {
   header("Location:".$data[2]);
  }
}
else
  {
   echo("not successful");
  }
exit;

This is the CSV file contents

 merch,26.06.2011,http://www.google.com

My problem is that the Header is not redirecting to the webpage. Any help would be greatly appreciated.

Upvotes: 1

Views: 246

Answers (6)

Marc B
Marc B

Reputation: 360762

Do you have multiple users listed in this csv file? fgetcsv() only reads a single line at a time, so for multiple users you'd have to use a loop to first find the line that the user is on, THEN check the expiry date.


for multiple users, you'd need to do this:

$fh = fopen('db.csv', 'rb');
while(list($name, $date, $url) = fgetcsv($fh)) {
   if (($name === $name_value) && ($date === $now)) 
       header("Location: $url");
       exit();
   }
}
echo "not successful";

Upvotes: 1

HertzaHaeon
HertzaHaeon

Reputation: 601

date(), without any arguments, produces this on my server:

Warning: date() expects at least 1 parameter, 0 given in test.php on line 1

I suggest you turn your error reporting on for testing purposes:

error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", "On");

To match the format in your CSV file, you need:

$now = date("d.m.Y");

Upvotes: 2

Paul DelRe
Paul DelRe

Reputation: 4039

You call date() without any parameters, which means $date is set to false and will only match $now values that can also be considered false.

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

Source

Upvotes: 1

Paul Sonier
Paul Sonier

Reputation: 39490

You must specify the Header location before you send any other content to the user; otherwise, the header doesn't redirect.

Upvotes: 1

cwallenpoole
cwallenpoole

Reputation: 82048

First, are your warnings turned on? This should not be failing silently.

Second, you probably mean date("m.d.Y"); and not date();.

Upvotes: 4

Lukas Knuth
Lukas Knuth

Reputation: 25755

A dirty way of doing this would be using a Meta refresh to redirect to the desired site (but don't beat me :D ).

Also:

if($name_value == $name && $date==$now)

You don't need to use two if-statements. Bind the two conditions with a logical AND.

Upvotes: 1

Related Questions