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 p开发者_高级运维age. 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.
First, are your warnings turned on? This should not be failing silently.
Second, you probably mean date("m.d.Y");
and not date();
.
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");
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
.
You must specify the Header location before you send any other content to the user; otherwise, the header doesn't redirect.
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
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";
精彩评论