【问题标题】:PHP find files on server which contain certain stringsPHP在服务器上查找包含某些字符串的文件
【发布时间】:2014-04-21 16:34:39
【问题描述】:

例如,我的图片文件夹中有几张图片:

User12345_gallery0.png
User12345_profilePic.jpg
User12345_gallery1.png
User12345_gallery2.jpg
User54321_gallery0.png

我想要做的是将用户传递给我的 getimages.php 并获取该用户的图像。我以前从未这样做过,所以我在语法上苦苦挣扎。这是我目前所拥有的:

if($_REQUEST['user']){
$ext = array('jpeg', 'png', 'jpg');
$dir = 'images/';
$user = $_REQUEST['user'];
$images = array();
foreach ($ext as $ex){
    if (file_exists(strpos($dir.$user."_gallery", "gallery"))) {
        //add file to $images???
    }
}
}

我想检查文件是否包含用户名和“画廊”的实例。我怎样才能做到这一点?我在正确的轨道上吗?

【问题讨论】:

  • 首先,file_exists() 需要一个文件名,strpos() 返回一个字符串偏移量。
  • 您的用户 ID 是否始终具有相同数量的字符?
  • 您可以使用glob 进行模式搜索。但是,由于它需要在每次调用时扫描整个目录中的所有文件名,因此如果您的网站变得流行,它将执行得非常糟糕。
  • 是的,我理解这是错误的。我不知道确切的文件名...我只是注意到我没有遍历整个图像文件夹...

标签: php arrays function output


【解决方案1】:

为此使用glob()stripos()..

<?php

if($_REQUEST['user']){

    $user = $_REQUEST['user'];
    $images = array();
     foreach (glob("images/*.{jpg,png,gif}", GLOB_BRACE) as $filename) {
         if(stripos($filename,$user)!==false && stripos($filename,'gallery')!==false)
            $images[]=$filename;
    }
}

【讨论】:

  • OP 不应该使用glob(array('jpeg', 'png', 'jpg'))...吗?
  • 为什么不直接使用带有 glob 的模式呢? glob($user."_gallery*")
  • @JonathanKuhn 看起来“_gallery”并不总是模式的一部分,例如“profilePic”......
  • 您不能将数组附加到这样的字符串。你可以使用glob($user."_gallery*.{jpg,png,gif}", GLOB_BRACE);
  • 很抱歉把你的 cmets 变成了对话:)。如果搜索您知道在$user 中识别的特定用户,我建议您使用$user."_gallery*.{jpg, png, gif}" 模式,如果搜索所有用户的图库,则使用"*_gallery*.{jpg, png, gif}"
【解决方案2】:

为什么不直接查看目录中的图片名称并为您的用户返回图片名称?

$ext = array('jpeg', 'png', 'jpg');
$dir = 'images/';
$user = $_REQUEST['user'];

// the length of your username (for the expression bellow)
$usernamelength  = strlen($user); 

// read a list of all files into an array
$filesindirarray = scandir($dir);

// loop through the list
foreach($filesindirarray as $filename)
{
   // does the filename start with
   if(substr($filename,0,($usernamelength+8)) ==  $user .'_gallery')
   {

      // fish out the files extension
      $fileext = pathinfo($filename, PATHINFO_EXTENSION);

      // if the extension of the files is in your list
      if(in_array($fileext,$ext))
         // add to images
    }
} 

【讨论】:

  • 感谢您的帮助,但在我的问题中,我展示了图像的命名方式,其中一些具有“user_gallery...”,而另一些具有“user_profilePic...”。所以我认为你的方式不会只取回画廊图片
  • 我更改了代码,只返回名称中带有_aggery的图片。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2015-01-31
  • 2021-08-29
  • 2014-05-07
  • 1970-01-01
相关资源
最近更新 更多