【问题标题】:Just want to search for "string".html files with the specified "string" from search bar - PHP只想从搜索栏中搜索具有指定“字符串”的“字符串”.html 文件 - PHP
【发布时间】:2019-01-22 16:17:33
【问题描述】:

我对 PHP 很陌生。请帮忙:)

我只是希望从搜索栏中输入的字符串拉出一个带有文件名中的字符串的 .html 文件。

基本上,我拥有的每个 .html 页面都显示了一个书籍列表,其中每个 .html 页面都由作者(即 freud.html)编写。所以,当我通过搜索栏搜索“弗洛伊德”书籍时,我希望 freud.html 出现。

我不确定如何将搜索栏字符串指向 php 文件。另外,我不确定我的搜索字符串如何提取我想要的 .html 文件或只是一个错误页面。

这是我的搜索栏:

<div class="search-container">
 <form action="searching.php">
   <input type="text" placeholder="Search Author..." name="search">
     <button type="submit"><i class="fa fa-search"></i></button>
 </form>
</div>

这是我在网上找到的 PHP 页面:

<?php
// string to search in a filename.
$searchString = 'myFile';

// all files in my/dir with the extension 
// .html 
$files = glob('/*.html');

// array populated with files found 
// containing the search string.
$filesFound = array();

// iterate through the files and determine 
// if the filename contains the search string.
foreach($files as $file) {
$name = pathinfo($file, PATHINFO_FILENAME);

// determines if the search string is in the filename.
if(strpos(strtolower($name), strtolower($searchString))) {
$filesFound[] = $file;
} 
}

// output the results.
print_r($filesFound);
?>

【问题讨论】:

  • glob('/*.html'); 指的是网络服务器文件系统根目录,而不是文档根目录的子目录。
  • 所有的网络服务器文件系统根都相似吗?我正在使用 cpanel
  • 我的观点是每个主题都有单独的 .html 页面最终会导致维护噩梦。例如,如果您想重新设计网站的外观,现在您有数千个页面要更改,该怎么办?这不好,它从根本上是有缺陷的。
  • 你会如何从不同的页面搜索书籍?
  • 如果我在做这样的项目,我会编写一个网络抓取工具来浏览网站,收集所有内容,将其放入数据库,然后创建一个带有查询参数的页面like somesite.com/books/?author=freud 然后你只需用 GET 的动作制作一个表格,就可以了。没有大惊小怪,没有混乱。另一个注意事项是,这让您在搜索中的灵活性为 0。

标签: php html string file search


【解决方案1】:

当形式:

 <form action="searching.php">
   <input type="text" placeholder="Search Author..." name="search">
     <button type="submit"><i class="fa fa-search"></i></button>
 </form>

是提交,GET 请求被发送到您的网络服务器,路径为/searching.php,GET 参数search=您的搜索输入。然后,您的网络服务器会加载您的 PHP 文件 searching.php 并执行它。

在 PHP 中,您可以使用 $_GET 全局数组访问 GET 参数。

因此,在您的 PHP 中,您可以使用 $_GET["search"] 访问搜索字符串。

对于第二个问题,找到 HTML 文件后,可以使用readfile 显示它。如果找不到文件,您可以加载其他文件,例如 error.html

【讨论】:

  • 表单的method 未设置,因此默认为get,而不是post
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多