【问题标题】:PHP Adding objects to array from a txt filePHP将对象从txt文件添加到数组
【发布时间】:2015-03-16 16:48:47
【问题描述】:

我正在尝试将 IP 地址添加到数组中,但无法使其正常工作
有人可以看到我犯了什么错误或推荐其他解决方案吗?

$ipAddress = $_SERVER['REMOTE_ADDR'];
$include = include "ip.txt";

$array = array($include);

if (in_array($ipaddress, $array)){
    echo "in array";
}
else {echo "error";}

这就是 ip.txt 文件的样子(文件是否“公开”并不重要):

'IP1', 'IP2', 'IP3', 'IP4'

【问题讨论】:

    标签: php arrays file include load


    【解决方案1】:

    你做错了一些事情,但这应该对你有用:

    <?php
    
        $ipAddress = $_SERVER['REMOTE_ADDR'];
        $include = file_get_contents("ip.txt");
    
    
        $array = explode(",", str_replace("'", "", $include));
    
        if (in_array($ipAddress, $array)) {
            echo "in array";
        } else {
            echo "error";
        }
    
    ?>
    

    1。你必须使用file_get_contents(),因为include首先只包含文件,所以这个纯文本在php代码中,其次它只返回truefalse!更多信息参见手册:http://php.net/manual/en/function.include.php

    还有一段话:

    处理返回:包括在失败时返回 FALSE 并引发警告。成功包含,除非被包含文件覆盖,否则返回 1。

    2。您必须从文件中分解字符串并删除单引号以获取数组中的 IP

    3。 PHP 变量区分大小写,所以$ipAddress$ipaddress 是两个不同的变量!更多信息参见手册:http://php.net/manual/en/language.variables.basics.php

    还有一个引用:

    变量名区分大小写。

    【讨论】:

      【解决方案2】:

      include 将尝试将文件作为 PHP 程序运行。

      改为使用file_get_contents():

      $include = file_get_contents('ip.txt');
      $array = explode(', ', $include);
      
      if (in_array("'$ipaddress'", $array)){
          echo "in array";
      }
      

      由于IP地址是用'包围的,所以也将它添加到in_array()的针部分。

      更简单的方法是将 IP 地址分别放在一行上。然后你可以使用file(),它返回一个包含文件行的数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 2023-03-22
        • 1970-01-01
        • 2012-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多