ПРОГРАММ: 654 | СТАТЕЙ: 125 | КОДОВ: 3434   

    главная        новости        программы        библиотека        коды        рейтинг       форум   

Афоризм
Жизнь должна быть легкой, не жать, подходить по длине
 
Поиск


 
Рассылка
| Soft-Ежедневник - обзор программ прямо к Вам на e-mail
 
 
Полезное!
 
7 лучших
  Алмазный инструмент
  Зоомагазин в г. Можайск
  Студия дизайна интерьера АПЕЛЬСИН. Дизайн-проект дома, квартиры, коттеджа, офиса, ресторана. Киев.
  Films&Games
  Amarish - питомник британских кошек
  
  
 
  Библиотека > web - разработка > PHPдобавить статью
Безопасный и удобный поиск

Главное, с чем сталкиваешься при написании скрипта для поиска - то, что все кажется простым, но объем кода быстро нарастает...
 

infocity.kiev.ua
10-05-2004
Версия для печати
печать

Главное, с чем сталкиваешься при написании скрипта для поиска - то, что все кажется простым, но объем кода быстро нарастает.

Обработка строки


Первым делом надо порезать ручками строку.

$search = substr($search, 0, 64);

64 символов пользователю будет достаточно для поиска. Теперь каленым железом выжжем все "ненормальные" символы.

$search = preg_replace("/[^(w)|(x7F-xFF)|(s)]/", " ", $search);

По идее, нельзя давать пользователю возможности искать по слишком коротким словам - кроме всего прочего, это сильно загружает сервер. Итак, разрешим искать только по словам, которые длиннее двух букв (если ограничение больше, надо заменить "{1,2}" на "{1, кол-во символов}").

$good = trim(preg_replace("/s([^s]{1,2})s/", " ", ereg_replace("[ ]%2B", "  "," $search ")));

А после замены плохих слов - надо сжать двойные пробелы (они были сделаны специально для корректного поиска коротких слов).

$good = ereg_eplace("[ ]%2B", " ", $good);

Логика


Допустим, мы хотим предоставить пользователю возможность выбирать логику поиска - искать все слова или только одно из нескольких. Если вы хотите сделать как в Яндексе [2] [1] - два амперсанта означают "И" (слово1&&слово2&&слово3) или как-то еще, то я не советчик. Шаманство со строками на небольшом сайте imho не оправдывает затраченного времени. Поэтому форму для поиска рисуем так:


А в поисковом скрипте лишний раз проверяем, что пользователь ввел:

if ($logic!="AND" && $logic!="OR")
  $logic = "OR";

Как будет использоваться логика — ниже.

Релевантность


Наверное, в том же Яндексе [2] [1] все видели ссылочку "сортировать по релевантности". Это оно и есть. Сортировка результатов по количеству совпадений слов.

Отчасти, кстати, такая сортировка снимает проблему обработки логики поиска. Но с БД MySQL делать такую сортировку очень сложно. Надо сперва выбрать, где есть все слова, потом записи, где разные слова (исключив предыдущие). Если у вас постраничный вывод - то вообще дело труба!

Статистика поиска


Неплохо будет сразу информировать пользователя, сколько он нашел строк таблицы. Для этого делается дополнительный запрос в базу:

$query = "SELECT id FROM table WHERE field LIKE "%". str_replace(" ", "%" OR field LIKE "%", $good). "%"";

Для статистики по отдельным словам можно сделать следующее:

$word = explode(" ", $search);
while (list($k, $v) = each($word)) {
  if (strlen($v)>2)
    $stat[]="$v:". mysql_num_rows(mysql_query("SELECT id FROM table WHERE field LIKE "%$v%""));
  else
    $stat[]="$v: <font color=#cc0000>короткое</font>";
  };
$word_stats = "Статистика слов: ". implode("", $stat). "<br>";
unset($stat);

Постраничный вывод результатов


Ну, когда у нас есть макет для поиска и количество строк результата поиска, сделать постраничный поиск - пара пустяков. Проверяем переменную $page (не меньше 0, не больше $results_amount/$rows_in_page).

В запрос, который подсчитывает количество строк (смотри выше), пишем нужные нам поля и поля для сортировки. А потом дописываем

if ($page==0)
  $request .= "LIMIT $rows_in_page";
else
  $request .= "LIMIT ". $page*$rows_in_page. ",". $rows_in_page;

(синтаксис: LIMIT <кол-во строк> либо LIMIT <кол-во строк отступа>, <кол-во строк>)

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

Для навигации можно либо рисовать ссылки на следующую и предыдущую страницы, либо, что сложнее, делать панель навигации на несколько страниц.

if ($page>0)
  print ("<a href=search.php?search=". rawurlencode($good). "&page=". ($page-1). ">предыдущая страница</a>");

if ($page<$results_amount/$rows_in_page)
  print ("<a href=search.php?search=". rawurlencode($good). "&page=". ($page%2B1). ">следующая страница</a>");

Подсветка


Чтобы подсвечивать светом или жирным шрифтом искомые слова в тексте, надо сделать всего лишь следующее:


$highlight = "(". str_replace(" ", "|", $good). ")";

Пробелы (а они у нас между словами стоят поодиночке, и нигде двойной пробел не встречается, к тому же с концов строки мы их тоже вырезали) достаточно заменить на вертикальную черту - разделитель вариантов в регулярных выражениях. "Плохие" слова мы не подсвечиваем, потому что в базе их не ищем :).

В коде, который выводит текст пишем:


$row["text"] = ereg_replace($highlight, "<font color=#cc0000>1</font>", $row["text"]);

После написания выпуска я кинулся, было, писать и себе "подсветку". Не тут-то было! У меня в тексте встречаются теги HTML, поэтому пришлось много подумать... Получилась вот такая вещь (строка со словами для подсветки есть):

$text = eregi_replace(">([^<]*)$words", ">1<font color=#cc0000>2</font>3<", $text);

Приходится смотреть, нет в теге ли это слово. Однако тут встает проблема ресурсоемкости такой замены (мой K6-266 над текстом в 5 килобайт думал целых семь секунд). Печально.

Итог


Применяя такие приемы, можно, во-первых, ограничить свободу действий пользователя и не дать ему а) узнать программную структуру сайта б) вызвать перегрузку сервера (например, отправив мегабайт текста, состоящего из слов длиной в три буквы (фраза получилась двусмысленная, но переписывать не буду :), чтобы скрипт 250 тысяч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадания в строку спецсимволов языка запросов. Во-вторых, некоторое удобство для пользователя - постраничный вывод и подсветка.



Комментарии
Оставить комментарий
страница < | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | >

Mariustaisy | 20-05-22 09:46
This topic deals with the problem of the way to allocate scarce resources in such a method that the advantages – measured in one way or one other - from using these sources are maximised. This additionally results in the general use of antibiotics in the neighborhood and will result in pointless imaging. Inflammation, coagulopathy, and the pathogenesis of a number of organ dysfunction syndrome antibiotics for acne brand names <a href=http://dtekerala.gov.in/medcontent/buy-ultrabac-online-in-usa/>buy ultrabac with a visa</a>.
You have extreme restrictions on value, well being & security or environmental impact so finding a good solvent mix may be very exhausting. A easy fracture happens when the suture material that takes the longest to soak up bone breaks cleanly into two separate pieces. Renal pyramid Inferior vena cava Adrenal (suprarenal) glands Inferior vena cava Abdominal aorta Prostate gland (in males) hilum renal medulla proper kidney ureteral orifice left kidney renal pelvis ureter urinary bladder renal artery renal vein urethra urinary meatus renal cortex Check your solutions by referring to Figure eleven1 on page 310 top antibiotics for acne <a href=http://dtekerala.gov.in/medcontent/buy-cheap-aziphar-online-no-rx/>order genuine aziphar online</a>. National Academy of Clinical Biochemistry Laboratory Medicine Practice tips: Recommendations for the usage of laboratory tests to assist poisoned patients who present to the emergency division. Enzymes stored in these


LucaSmumthact | 19-05-22 21:57
Intratumor heterogeneity in human medication Sackler colloquium: evolutionary on Hereditary Breast and Ovarian Cancer glioblastoma refects cancer evolution- views on well being and medication. But if insomnia is the rule, not the exception, you have to go after it as a particular problem. Dysphagia, shoulder weak point, and cardiovascular instability are also indications that mechanical ventilation could also be needed symptoms vitamin b12 deficiency <a href=http://dtekerala.gov.in/medcontent/purchase-cheap-quetiapine/>discount quetiapine express</a>.
It is known by these expert understand that the particular type will depend on the pH. Foreign bodies can mimic croup, it is important to ask about a possible choking occasion three. Carcinoma of the urethra is Adult kind occurring in adults over 40 years of age and uncommon acne quiz <a href=http://dtekerala.gov.in/medcontent/order-online-isotane-cheap-no-rx/>buy isotane us</a>. Add one hundred fifty 300ml recent frozen plasma at the end of every pheresis session if sufferers have pulmonary the double-antibody positive patients do not appear to have hemorrhage, or have had recent surgical procedure, together with kidney biopsy. While this is able to require an extra effort from the Licensing Authority, it may present a continuing and critical evaluation of the present medical necessities and could present whether or not they achieve their function. Other causes of a illness, Behcet's disease) nodular panniculitis, which may s


YokianFlubsFlut | 16-05-22 18:37
However, suppression of a nursing infant’s immune function is a potential complication. Soft tissue sarcomas and navy service in Vietnam: A case comparison group evaluation of hospital sufferers. This supplies a measure of the pressure that the ventricle should overcome to eject blood erectile dysfunction treatment washington dc <a href=http://www.sttheresechesva.org/session/buy-cheap-vimax-online-no-rx/>buy vimax 30caps low cost</a>.
Gastric emptying of lactose and glucose- galactose in patients with low intestinal lactase activity. This might be accomplished by treating few ml of urine with few ml of hydrochloric acid giving a white ring on the junction of the 2 fluids. Shock and disseminated intravascular coagulation are common in bacteremia as a result of B virus for mac <a href=http://www.sttheresechesva.org/session/purchase-online-colcout-cheap-no-rx/>cheap 0.5 mg colcout with visa</a>. Active-obligation girls and wives of active-responsibility males had lower rates of bodily violence by an intimate companion, in accordance with the study (28. In adults, this tumor tends to occur within the body of the cerebellum, particularly towards the edges. The physical examination may also provide useful With massive bleeding, the necessity to management the air clues to the analysis womens health letter <a href=http://www.sttheresechesva.org/session/buy-female-viagra-online-in-usa/>buy female viagra visa</a>.
Subject to Notice of rights 256 Pancreatitis Management of small-


Joeydrainny | 13-05-22 17:25
With stable tumours there's also a (relative) scarcity of erythropoietin (Miller 1990). Hemoglobin H and Hemoglobin Barts are both ineffective, with no efficient oxygen carrying capability. Effects of morcellation on longthe Society of Laparoendoscopic Surgeons / term outcomes in patients with uterine Society of Laparoendoscopic Surgeons treatment xanthelasma eyelid <a href=http://www.skinbio.com/medlib/order-amoxicillin-online-no-rx/>cheap 500mg amoxicillin otc</a>.
Interviews have been accomplished with eleven,161 respondents of whom 4762 had been males and 6399 were women. The preliminary ibuprofen serum plasma degree Jersey - United States, 2 Division of Nephrology, The ChildrenпїЅs was 330 ?g/mL (therapeutic vary is 10-50 ?g/mL). Every Household detergent is adequate for many rou working surface together with your sofa, foor and tine environmental cleaning virus jc <a href=http://www.skinbio.com/medlib/purchase-cheap-misultina-no-rx/>order misultina 250mg on-line</a>. Journal of the American Academy of Child and Adolescent Psychiatry, 39(eleven), 1396пїЅ 1405. The alternative of aspirin, clopidogrel, or dipyridamole plus aspirin should balance the fact that the latter are simpler than aspirin however the fee is higher. Precursor to product ratios are particularly useful in distinguishing the totally different enzymatic defects symptoms you have diabetes <a href=http://www.skinbio.com/medlib/buy-liv-52-online-in-usa/>order liv 52 mastercard</a>. Due to the severely decr


Basirvak | 03-05-22 23:26
Stay on the scene with the person until he or she is fully conscious and aware the individual has multiple seizures with no signs of of the surroundings. Cachectic sufferers show increased expenditure of resting energy; in distinction, in chronic starvation, the basal metabolic price is decreased. Medical practitioners stress the significance of listing behaviours that may be noticed and measured antibiotic hand soap <a href=https://hmpi.org/material/order-keftab-online/>375 mg keftab</a>.
Resource use in mixed treatment was the sum of resource use of treatment and behavioural remedy, given that the two interventions are led by various kinds of healthcare professionals and no overlap in services provided occurs. Knowing the subtype of the patient’s illness may help the doctor to evaluate how rapidly the disease might progress. In sufferers with schizophrenia, there was no indication of any completely different tolerability of olanzapine within the aged compared to younger sufferers medicine pouch <a href=https://hmpi.org/material/order-cheap-kytril-no-rx/>buy kytril paypal</a>. A mother ought to drink water, buttermilk, house-made soups, soya milk sattu and different unsweetened healthy beverages as an alternative of soda or fruit juices. This consists of the usage of interpreter services the place essential • Ensuring knowledgeable consent is obtained prior to delivering care • Meeting all legislative necessities and professional standards • Applying commonplace pr


Yokianalteway | 29-04-22 04:05
So in style was milk thistle that a tincture of the entire plant was listed in the first United States Homeopathic 1,2 Pharmacopoeia. Criteria Since the choice that a medical emergency existed could be a matter of subjective medical judgment involving the whole gamut of illness and accident situations, it's inconceivable to provide arbitrary guidelines. The threshold for tactile, vibration, and kinesthetic sensibility could also be increased or regular bacteria 4 result in fecalysis <a href=https://ibusausa.com/collection/purchase-cheap-tridosil-no-rx/>buy tridosil line</a>.
The пїЅ Headache is a common opposed impact of this drug, significantly really helpful dose is one to two tablets thrice per day, although when first starting remedy. The entire coronary heart could be imaged with three mm non-overlapping slices, inside one breath hold (30 sec). These toxicities are may be just as variable in Safety examine with surprising ocular results gastritis celiac <a href=https://ibusausa.com/collection/order-ditropan/>discount ditropan amex</a>. Safety administration methods became obligatory in January 2009 for plane operators (1). Though the prevalence of sort 1 diabetes is in- mediated (generally) or it might be idiopathic destruc- creasing all around the world, yet it accounts for a minority. This can be carried out from 15 weeks to During labour, your cervix will dilate (open up) to test for sure chromosomal and genetic 10cm to let your child transfer from your uterus issue


Trompokhit | 25-04-22 00:00
Vaginal Insufflations with Ozone/Oxygen Mixtures Vaginal insufflations are accomplished with ozone focus 0f 2-2,5mg/l in ozone/oxygen mixtures with the gasoline rate 0, 5-1l/min for 5-10 minutes. The perinatal dioxin publicity of infants was estimated by the measurement of dioxin ranges in breast milk of the nursing mothers. Patients with feeding setting, nevertheless, there is concern for use of blended-fiber formulation intolerance had been proven to have the next fee of bacteremia in patients at high threat for bowel ischemia or extreme dysmotility (86% vs 18%; P < infection hemorrhoids <a href=https://franjipaniresort.com/training/order-cheap-cipro/>order discount cipro on-line</a>.
Oral thrush is a white coating on onerous or taste bud and tongue; causes dysphagia if oesophagus concerned; happens in late disease. Recommend injectable B12 for patients with more extreme deficiency or those that might not take in it as a result of diarrhea, vomiting, or bowel resection. Dexamethasone is often given in divided doses, though some authorities favor a single day by day dose birth control low estrogen <a href=https://franjipaniresort.com/training/purchase-cheap-yasmin-online-no-rx/>buy generic yasmin online</a>. Prospective analysis of two medical scores for acute bronchial asthma in kids 18 months to 7 years of age. Contact Dermatitis 41:one hundred ninety–192 methodology to evaluate prevention of irritant combination 250. Venn diagrams comparing the proteins present in eve


AnktosFauck | 21-04-22 03:28
The evidence also means that there are techniques and processes in place inside healthcare provision that may additionally negatively have an effect on entry to healthcare, for example rigid referral proce-dures and care pathways that don't account for individual variation in tradition, poor communication between services and an absence of quality mental healthcare companies. Trial of and insufficient response or intolerance to hydroxyurea, unless contraindicated or clinically significant antagonistic results are experienced Reauthorization 1. With any median nerve harm, there may be potential for loss of sensation in the median nerve distribution, which includes the palmar floor of the thumb, the index fin- ger, the lengthy finger, and the radial facet of the ring finger medicine to treat uti <a href=https://esehospitalalcidesjimenez.gov.co/wpdocs/purchase-divalproex/>discount divalproex 250mg mastercard</a>.
Pancreatic divisum A congenital anomaly in the anatomy of the ducts of the pancreas in which a single pancreatic duct isn't formed, but rather stays as two distinct dorsal and ventral ducts. Transmission Mode Comment: Pneumonic plague more than likely to occur if used as a organic weapon, but some cases of bubonic and first septicemia may also occur. However, when symptoms rise to a peak , they break throughthe it appears that in lots of of these instances, prolonged remedy antidepressant barrierto the purpose where they cause diswith excessive-dosage monotherapy may


SvenDioms | 06-04-22 19:34
Postures seen when the patient is mendacity down: which can erode on the vertebra within the supine a. Less than 1% of complete physique calcium is found in soft tissues (~7 g) and physique fluids (~1 g). Identify the ilio-inguinal nerve and defend it throughout surgery by holding it away from the operating field symptoms after flu shot <a href=http://www.merced-river.org/special-course/buy-online-norpace-no-rx/>cheap norpace online</a>.
Applications of skeletal anchorage in remedy of adults have been mentioned in detail in Chapter 18. By doing so, each contraction is triggered and due to this fact managed by a guide action. J Acquir Immune Defic Syndr Human Retrovirol 2001 27 fifty six sixty two Test mentioned subsequent to group is the preliminary take a look at the ones mentioned beneath an anion are confirmatory tests for it clinical depression symptoms quiz <a href=http://www.merced-river.org/special-course/order-escitalopram-online/>purchase escitalopram with american express</a>. The willpower of dif- neutropenia is the patient’s preliminary episode of fever and neutro- ferences in affected person threat of an infection and infectious issues penia, or persistent unexplained fever of their preliminary episode ranges (excessive danger and low risk) during the period of neutropenia (after 4–7 days) or a subsequent episode of fever and neutrope- has been recognized and additional validated since this clinical nia (recurrent) (robust, low). Doppler examination reveals


EsielFesLayexy | 06-04-22 19:09
These pores and skin lesions ing papules with a central eschar (ecthyma gangrenosum like may be discrete or multiple, are found preferentially between lesion). In principle, stem cells An inevitable and essential a part of this derived from a person could present an individ- research involves the use of animals. Hepatology 2010 ; fifty one : ingestion of Herbalife contaminated with Bacillus subtilis muscle relaxant apo 10 <a href=http://www.merced-river.org/special-course/buy-azathioprine/>discount azathioprine amex</a>.
Note: We cowl outpatient mental health and substance use dysfunction companies or supplies provided and billed by residential therapy centers at the levels proven right here. Chem icals Analyte/InternalStandard Purchasedfrom 2 a H -6 25-hydroxyvitaminD3(95%) Synthetica b 25-hydroxyvitaminD3(ninety eight%) Sigma-Aldrich 2 c H -6 all-transretinol(ninety nine. It is the Pregnancy carries an overall maternal mortality contraceptive of selection acne 17 year old male <a href=http://www.merced-river.org/special-course/order-benzac-online-in-usa/>discount benzac 20gr with visa</a>. Study reports use of morcellation or en bloc elimination of the uterus or uterine fibroid. Fullness of optic nerve with nerve fiber layer opacity may be replaced by coalescing refractile excrescences 6. Cytokines During acute pancreatitis, some inflammatory cells and pancreatic tissues launch inflammatory mediators and cytokines, which influence the whole means of inflammation gastritis

Имя:
E-mail:
Сообщение:


Число=
укажите сумму чисел на картинке

   очистить

популярные статьи по теменовые статьи
Создание видео из фотографий в программе "ФотоШОУ"
Разное / Обработка фото и видео
Больница для компьютера
железо / Система
Чем так популярны социальные сети?
Разное / разное
Синхронизация данных с сотового телефона на ПК
железо / Мобильные устройства
Куплю хостинг
web - разработка / Хостинг

Опрос
На что Вы обращаете внимание в первую очередь при покупке товара в интернет-магазине?  
 
Комментарии и оценку пользователей
Наличие нескольких фотографий
Подробное и качественное описание
Условия доставки
Возможность покупки в кредит
 
Самое свежее  
 ПРОГРАММЫ

ICQ 8.0.5990
ICQ 8.0.5990

Mozilla Firefox 18.0.2
Mozilla Firefox 18.0.2

ArtMoney 7.40.4
ArtMoney 7.40.4

 НОВОСТИ

Хакерская атака на Google из Китая
Хакерская атака на Google из Китая

Мы победили! Олимпиада 2014 пройдет в Сочи
Мы победили! Олимпиада 2014 пройдет в Сочи

 БИБЛИОТЕКА

Создание видео из фотографий в программе "ФотоШОУ"
Создание видео из фотографий в программе "ФотоШОУ"

Больница для компьютера

 
Рекомендую!



Copyright © 2004-2024 MostInfo.net  | связь с админом
При использовании материалов сайта ссылка на MostInfo обязательна.