Php source code for search

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A PHP script that searches your entire (PHP) website based on keywords and outputs relative URLs of appropriate pages along with their search score.

License

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Kotlin передача данных между activity

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A PHP script that searches your entire (PHP) website based on keywords and outputs relative URLs of appropriate pages along with their search score in a JSON array.

It builds a list of all the files (yes, ALL THE FILES!) available in your website directory — even the ones inside sub-folders, sub-sub-folders and even .hidden folders and .hidden files themselves — excluding the ones you choose to exclude from the search — and then reads the meta keywords from the files and matches them with the queried keywords.

Input/arguments to the script

Individual keywords. Comma separated, trimmed. For example:

https://www.example.com/search.php?q=keyword1,keyword2,apple,banana 

The following JSON array is returned:

where search-score is an integer. The array is sorted in decreasing order of search scores. That means, the first result is the most relevant and the relevance decreases as the array index increases. It does not contain any element with score less than 1.

In case of 0 (zero) search results, it will return an empty JSON array like so:

This script matches the supplied arguments with the meta keywords of the pages of your website, i.e., the keywords you specify in the HTML meta tags of the files like so:

It doesn’t matter how many spaces there are between individual keywords; they should just be comma-separated.

Exclude resources from search

Just put the relative URLs of the files that you do not want to appear in the search results (one per line) in the file ignore . You can also omit an entire folder by putting its relative URL.

Code quality & intended usage

The code is not at all optimized for large number of files. It’s a simple script that you can implement on your personal blog. I wrote this code as a past time activity. It works for sure but is definitely not the best (Complexity: O(n 3 )).

Use it as you want. Modifications are welcome. See license details in LICENSE.

About

A PHP script that searches your entire (PHP) website based on keywords and outputs relative URLs of appropriate pages along with their search score.

Источник

Пишем поиск по сайту на PHP и MySQL

Сегодня мы напишем собственный поиск по сайту с использованием PHP и MySQL. Первым делом рассмотрим краткий алгоритм.

Пользователь выполняет POST запрос из формы поиска, этот запрос передается специальному скрипту-обработчику, который должен обработать поисковый запрос пользователя и возвратить результат.

Сначала скрипт должен обработать должным образом запрос пользователя для обеспечения безопасности, затем выполняется запрос к базе данных, который возвращает в ассоциативном массиве результаты, которые должны будут выводиться на экран. Итак, приступим.

Для начала создадим форму поиска на нужной нам странице:

Эта форма и будет отправлять сам поисковый запрос скрипту search.php. Теперь создадим сам скрипт-обработчик.

 if (!mysql_select_db(DB_NAME)) < exit('Cannot select database'); >mysql_query('SET NAMES utf8'); function search ($query) < $query = trim($query); $query = mysql_real_escape_string($query); $query = htmlspecialchars($query); if (!empty($query)) < if (strlen($query) < 3) < $text = '

Слишком короткий поисковый запрос.

'; > else if (strlen($query) > 128) < $text = '

Слишком длинный поисковый запрос.

'; > else < $q = "SELECT `page_id`, `title`, `desc`, `title_link`, `category`, `uniq_id` FROM `table_name` WHERE `text` LIKE '%$query%' OR `title` LIKE '%$query%' OR `meta_k` LIKE '%$query%' OR `meta_d` LIKE '%$query%'"; $result = mysql_query($q); if (mysql_affected_rows() >0) < $row = mysql_fetch_assoc($result); $num = mysql_num_rows($result); $text = '

По запросу '.$query.' найдено совпадений: '.$num.'

'; do < // Делаем запрос, получающий ссылки на статьи $q1 = "SELECT `link` FROM `table_name` WHERE `uniq_id` = '$row[page_id]'"; $result1 = mysql_query($q1); if (mysql_affected_rows() >0) < $row1 = mysql_fetch_assoc($result1); >$text .= '

href="'.$row1['link'].'/'.$row['category'].'/'.$row['uniq_id'].'" title="'.$row['title_link'].'">'.$row['title'].'

'.$row['desc'].'

'; > while ($row = mysql_fetch_assoc($result)); > else < $text = '

По вашему запросу ничего не найдено.

'; > > > else < $text = '

Задан пустой поисковый запрос.

'; > return $text; > ?>

Естественно, данные таблиц БД нужно задать собственные. Рассмотрим, что делает эта функция. Первые 4 строчки обрабатывают запрос, чтобы он стал безопасным для базы. Такую обработку нужно делать обязательно, т. к. любая форма на Вашем сайте — это потенциальная уязвимость для злоумышленников.

Затем идет проверка, не пустой ли запрос. Если запрос пустой, то возвращаем соответствующее сообщение пользователю. Если запрос не пустой, проверяем его на размер.

Если поисковый запрос имеет длину менее 3 или более 128 символов, также выводим соответствующие сообщения пользователю. Иначе, выполняем запрос к базе данных, который делает выборку идентификатора страницы, ее заголовка, описания, описания ссылки, категорию, если она есть и идентификатор самой статьи, в которой найдены совпадения нужных нам полей с поисковым запросом.

В данном случае мы делаем сравнение с текстом статьи, ее заголовком, ключевыми словами и описанием. Если ничего не найдено, выводим пользователю сообщение об этом. Если запрос возвратил хотя бы одну запись, выполняем в цикле еще один запрос, который делает выборку из таблицы со страницами ссылку на страницу, на которой находится статья.

Если у Вас все статьи на одной странице, вы можете опустить этот шаг. После выполнения запроса при каждой итерации цикла в переменную $text Дозаписываем одну найденную статью.

После завершения цикла, возвращаем переменную $text , Которая и будет выводиться на нашей странице пользователю.

Теперь осталось на этой же странице search.php сделать вызов этой функции и вывести ее результат пользователю.

Также вы можете упростить скрипт поиска по Вашему усмотрению. Желательно создать стиль в таблице css для выводимой информации, чтобы выводимая информация смотрелась более красиво и читабельно. Все замечания вопросы по скрипту можете задавать в комментариях.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Simple PHP-based MySQL search library with 0 dependencies. @dbsearch

phpsearch/library

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Keyword search, translation to another programming language (Python?), & prepared statement support coming soon! Vote on features

PHPSearch is a PHP search engine library with no dependencies. It’s super simple and easy to use, with minimal programming knowledge required.

With PHPSearch, you don’t have to worry about SQL Injection, advanced search algorithms, or even removing unimportant words in your search query. All of that boring stuff is covered by PHPSearch so you can focus on your project.

You can install PHPSearch using Composer. This is the easiest way.

composer config minimum-stability dev composer require mrfakename/phpsearch 

In the past, there were many packages that I wanted to use, but they were only available through Composer. This was extremely frustrating for me because I didn’t want to use Composer (mainly because of the sheer numbers of files it created!)

  1. Download the source code from GitHub
  2. Copy src/PHPSearch/PHPSearch.php to your server
  3. Include PHPSearch.php in your code.
include_once 'PHPSearch.php';
include_once 'PHPSearch.php'; use mrfakename\PHPSearch; # Create the connection! $conn = mysqli_connect('localhost', 'root', '', 'links'); # Create the object! $search = new PHPSearch(); $search->setQuery('PHPSearch'); // Not case-sensitive! $search->setConn($conn); // or $search = new PHPSearch('PHPSearch', $conn); $res = $search->search('title', 'author', 'publisher', 'keywords'); // Returns mysqli_result # Show the results mysqli_fetch_assoc($res)) < echo " 

$row[title] by $row[author], published by $row[publisher].

"; >
new PHPSearch(string? query, mysqli? connection): PHPSearch 
$search = new PHPSearch('test', $conn);

If you already created a search object and passed the query and connection, you can skip this part.

PHPSearch->setQuery(string query): bool 

If you already created a search object and passed the query and connection, you can skip this part.

PHPSearch->setConn(mysqli connection): bool 
$conn = mysqli_connect('localhost', 'root', '', 'books'); $search->setQuery($conn);

This is the most important function.

PHPSearch->search(string tablename, . string tablecolumns): mysqli_result 
$res = $search->search('books', 'title', 'author', 'publisher');

You could parse the mysqli_result this way but it’s really up to you:

while ($row = mysqli_fetch_assoc($res)) < echo $row['title'] . '
'
; >

Copyright © 2023 DBSearch. All rights reserved.

PHPSearch is an affiliate of DBSearch. DBSearch is creating open-sourced tools for searching databases. Learn more

About

Simple PHP-based MySQL search library with 0 dependencies. @dbsearch

Источник

Оцените статью