doulubashang6936 2011-11-09 20:13
浏览 65
已采纳

PHP - 使用strpos比较字符串

I have set up a polling system on my website. However to ensure that people cannot vote again, I have a IP finding mechanism to gather their IP and to make sure that they do not vote again.

The way in which i do this, is I gather their IP then compare it to a text file which has the IP in it. It has a comma to separate each IP.

function getUserIP()
{
//check ip from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
//to check ip is pass from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}

$visitorIp = getUserIP();
$myFile = "ip_polllist.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 200);
fclose($fh);
$findme = $visitorIp.",";
$mystring = $theData;
echo $mystring;
echo $findme;
$pos = strpos($mystring, $findme);
if($pos === true)
{
    die();
}
if($pos == true)
{
die();
}

What is wrong with the code and why does $pos = false?

  • 写回答

3条回答 默认 最新

  • douqiang6036 2011-11-09 21:17
    关注

    I don't think your approach is really good:

    1) It is not really good to write to a single file from multiple requests, because the looking of the file might decrease the performance of your script. Don't you have access to any database system?

    2) Do you have any account system on your page? If yes, I would prefer to restrict a second vote based on the account rather than on the IP address.

    3) What do you do when you start a second poll? Create a second file?

    4) fread($fh, 200): What happens if you have 100 locked users (IPs)? Your script only reads the first 200 bytes.

    5) if($pos == true): I really don't like relying on the autocasting "feature" of PHP. You are expecting FALSE or a number so check for FALSE and >= 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法