2013-03-05 111 views
0

如果查询为空或者存在错误的代码名称,我想要做的是将访问者发送到错误页面?我目前的脚本回应了下面的内容:“这个网站上不会有黑客入侵!”,但这一切都发生在发送原始查询的同一页面上。如果MySQL查询为NULL,则动作

我们的目标是将访问者发送到位于第一页所在的同一文件夹内的我的自定义错误页面。

http://www.example.com/download/file.php 

http://www.example.com/download/error.php 

和我现在的剧本是

<?php 
$host = 'localhost'; 
$db_name = 'My_DB_Name'; 
$db_user = 'MY_User_Name'; 
$db_pass = '******'; 
$path_to_file_directory = 'download/files/'; 
mysql_connect($host, $db_user, $db_pass); 
mysql_select_db($db_name) or die(mysql_error()); 

$file_code = filter_input(INPUT_GET, 'urlid'); 

# Query for file info 
$res = mysql_query("SELECT * FROM `Files` WHERE `urlID`='".$file_code."'") or die (mysql_error()); 

# If query is empty, there is a bad code name 
# This catches possible hacking attempt. 
if(mysql_num_rows($res) == 0) 
{ 
echo 'There will be no hacking on this website! '; 
exit(); 
} 

# Save file info into an array called "$info" 
$info = mysql_fetch_assoc($res); 

# File path is below 
$file_path = $path_to_file_directory.$info['file_name']; 

# Now push the download through the browser 
# There is more than 1 way to do this. 
if (file_exists($file_path)) { 
echo '<p>if it does not: <a href="'.$file_path.'">click here to try again</a>.</p>'; 
exit; 
} 

?> 

我明白,我必须改变回声别的东西,但我不知道我有什么,而不是使用,因为只需将链接内部回声一个错误页面将只能随声附和它我file.php页面上

请帮

+1

*强制性的:*'mysql_ *'函数将[在PHP 5.5中弃用](http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated)。不建议编写新代码,因为它将来会被删除。相反,无论是[MySQLi](http://php.net/manual/en/book.mysqli.php)还是[PDO](http://php.net/manual/en/book.pdo.php)和[是一个更好的PHP开发人员](http://jason.pureconcepts.net/2012/08/better-php-developer/)。 – 2013-03-05 17:54:40

+0

发布整个代码 – 2013-03-05 17:58:26

+0

感谢您的回复和建议,我实际上正在尝试学习PHP,并已开始这样做,但正如您可以通过我的问题中的脚本来判断,我只是一个初学者。 – AlexB 2013-03-05 17:59:45

回答

2

我想你需要的是重定向到另一个页面。您可以使用它的header函数。

<?php 
if(mysql_num_rows($res) == 0) 
{ 
    header('Location: /nohacking.php'); 
    exit(); 
} 
?> 

这会将您的浏览器重定向到nohacking.php文件。

1

只要你还没有发送的任何标题,但(即,基本上,这是任何HTML前):

if(mysql_num_rows($res) == 0) 
{ 
die(header("Location: error.php")); 
} 

header()函数将重定向页面,并且die()函数将停止处理其余的PHP。

+0

谢谢你,我仍然必须使用或'死(mysql_error());'如果我要选择你的选择,我在原始脚本中有哪些? – AlexB 2013-03-05 18:13:27

+0

您应该为了调试目的(您可能不想在生产代码中)。如果查询出问题,mysql_error()只会引发错误。这不包括一个空的返回(这是mysql_num_rows($ res)== 0正在测试的内容)。因此,如果您希望代码在查询无效的情况下停止运行(例如,如果您尝试在不存在的列中搜索),请保留它。 – sundance 2013-06-21 12:58:41