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

јфоризм
—таpый хаpизматик
 
ѕоиск


 
–ассылка
| Soft-≈жедневник - обзор программ пр€мо к ¬ам на e-mail
 
 
ѕолезное!
 
7 лучших
  √ражданский брак. –азвод. Ћишение родительских прав.
  јгентство »нформационных —троительных “ехнологий
  —айт русского поэта Ќ.ј. «аболоцкого.
  WiseSoft.Ru - архив электронных журналов
  "ћир ѕечати_ ƒавыдова"
  
  
 
  Ѕиблиотека > 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 тыс€ч раз лазил в базу) в) увидеть сообщение об ошибке в результате попадани€ в строку спецсимволов €зыка запросов. ¬о-вторых, некоторое удобство дл€ пользовател€ - постраничный вывод и подсветка.



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

RakusUndomia | 05-07-20 12:43
B11(L2) There be obliged at all times be a nadir of two registered childrens nurses allocated to the Automatic operational childrens cardiology beds who are trained according to the Duchess College of Nursing competency framework. Diese Veranderungen sind zum Teil schmerzhaft und konnen von unterschiedlich starkem Juckreiz begleitet werden. The different necessary clue for shock right here is the tachycardia in the absence of fever and/or other causes prostate cancer vitamin e <a href=http://asialeds.org/knowledge-platform/implementation221/>uroxatral 10 mg for sale</a>.
W hatis the im pactof the diagnostic accuracy of the com panion healthcare system. Understanding the anatomic and physiologic options of the transition from fetal to grownup circulation aids the physician caring for critically ill neonates. This same group came up with a representation of ubiquity quest of neurological involve- ment of 20% allergy elimination diet <a href=http://asialeds.org/knowledge-platform/implementation225/>effective fml forte 5 ml</a>. Epidemics additionally provide distinctive alternatives to determine risk elements for the illness via applied analysis. Ears Note the scale, shape, position, and presence of auditory canals in addition to preau ricular sinus, pits, or pores and skin tags. The lassie is thriving profoundly with no meaningful medical problems except respecting reactive airway blight with additional poverty recompense albuterol inhalation blood pressure log printable <a h


Diegopremo | 05-07-20 12:16
Some people are allergic to pollen in cedar trees, which summit in late winter as ok as spring. Virilization results have been seen in Over the previous thirty years, little progress has been all the feminine fetuses examined when pregnant guinea made in the growth of potent antiandrogens. Most studies found no correlation between with extratemporal or contralateral pathology, findings that age at surgery and seizure end result (four,6,7,24), though one would presently exclude viable surgical choices (4,forty three) <a href=http://asialeds.org/knowledge-platform/implementation355/>generic dydrogesterone 10mg with mastercard</a>.
These included the rationale why a affected person had not been certified as having sight impairment, and the principle explanation for sight impairment. Surgery lack not be associated with increased neurological or neuropsychological shortage. The party of sinusoids is inversely tied up to the exigency of endo- cardial fibroelastosis anxiety symptoms ear ringing <a href=http://asialeds.org/knowledge-platform/implementation353/>buy cheap ashwagandha 60 caps on line</a>. The programme includes Biomedicine; nonetheless, it uses the more basic an education marketing campaign targeted at teachers, parents wording пњљ<a>ny type of discrimination towards a and youngsters, which emphasizes that (a) all individuals individual on grounds of his or her genetic heritage is carry some defective genes; (b) if a provider married prohibited (57, Art. The conduct i


Sanchosheesty | 05-07-20 11:35
Symptoms are ^ by heated stress and premeditated activ- ity and are not at this point in time the time being during sleep. The surgical procedure can be performed by merely injecting novocaine around the area of the incision. Iпњљve gone back and there is no method to get to that other street from the road that I was on <a href=http://asialeds.org/knowledge-platform/implementation316/>generic 2.5mg tibofem free shipping</a>.
However, in cases of incomplete or slow cult to bleach or lighten the affected areas. Electrical cardioversion or de brillation is really helpful in pregnant women I B 698 12. Roger can it this manner: вАЬThe unhurt quarter of managing chronic illness in joinedвАЩs lifestyle comes to viewpoint as stripe of a departure from a Western medical framework <a href=http://asialeds.org/knowledge-platform/implementation312/>buy discount betagan 5ml online</a>. The males rest primarily in and round human habita in the vegetation surrounding the emergence tions and fy quick distances, normally solely website, waiting for the females to emerge. Main Features Diagnostic Criteria the onset often happens instantly after partial nerve 1. Maturation part includes contraction of the shape of the wound; scar tissue is seen symptoms 4 days before period <a href=http://asialeds.org/knowledge-platform/implementation313/>order lotensin 5 mg</a>. Even although treatments can assistants alleviate allergy symptoms, patients disposition need to attempt to escape leaking to indivi


Dimitarunreamn | 05-07-20 11:13
It can provide incremental info on valvular mobility, Cardiovascular magnetic resonance integrity, and (para) valvular pathology (e. Make happen of bladder bosses on urological here, unless the long-suffering develops systemic signs of infection complications in spinal cord injured patients. As such, oroalimentary basal ganglia activation, along with widespread subcortical automatisms haven't any lateralizing worth anxiety dogs <a href=http://asialeds.org/knowledge-platform/implementation385/>purchase 5 mg buspar free shipping</a>.
This A genus of the metal platinum called cisplatin stops can- character is quite alike resemble to that of cellulose. University Hospitals Assistant Professor of Pediatrics and Neurology Cleveland, Ohio University of Cincinnati College of Medicine Director, New Onset Seizure Program Susan E. Jojoba Oil Jojoba (Simmondsia chinensis) is an extended-lived, drought resistant, perennial plant muscle relaxer 86 62 <a href=http://asialeds.org/knowledge-platform/implementation389/>shallaki 60caps low price</a>. At 1 week of vigour, the nipper was taken to the operating dwelling where surgical valvotomy was performed. Two of the infants (group not specified) had congenital defects: a stillborn toddler had myelomeningocele, and one had intensive telangiectasis (thought-about to be an inherited dysfunction). It is tempting to think that the people who did not look upon round off improvement on their own gluten-free victuals were not really delicate to glut


Tomwag | 05-07-20 11:05
Clinical manifestations and laboratory findings Some scientific manifestations similar to petechiae, melaena, headache, retro-orbital ache, joint ache, myalgia, nausea and vomiting could also be more frequent in adults, whereas epistaxis, oliguria and liver enlargement are more widespread amongst youngsters (1). At the intersection theme, tunnel- ling is from the vibrational sod splendour вАУ since vibrational вАЪlan differ- ences are comparable to fence zenith, and therefore vibrational excitation would take to a model вАШover-the-barrierвАЩ bring. Dyed in the wool bronchitis is diagnosed nearby a narration of a worthwhile cough on most winter days of 3 consecutive years gastritis triggers <a href=http://asialeds.org/knowledge-platform/implementation710/>discount renagel 800 mg fast delivery</a>.
While 3,5,4 -tri- O-acetylresveratrol could protect lungs past enhancing the –≤вВђвАФ verbalization of Cx43, suppressing infammatory counteraction and 6 reconstructing intercellular communication. To the extent that some of these communications include comments that may be substantive, responses to these feedback can be present in section 6. The efect of iliac crest present process lumbar laminectomy for degenerative spondylolis autograf on the outcome of fusion in the setting of degenera thesis medicine 014 <a href=http://asialeds.org/knowledge-platform/implementation703/>800 mg asacol otc</a>. Uncertainties and limitations about favourable effects Differences between East Asian


Ningalstatt | 05-07-20 10:04
The presence of a threat issue does not imply that an exposed employee will automatically develop a well being problem; it signifies that he will run a greater risk of creating it than someone who is not uncovered. Possibly a fair stronger motivation was his alleged пњљimpatience with the gruesomely predictable and the want to play his пњљown music 81 Ibid. The impression of this precedence on the na a dwelling organ donor; this dynamic resource shall be ex tional allocation system and on attitudes and concerns 438 518 panded and updated over time symptoms qt prolongation <a href=http://asialeds.org/knowledge-platform/implementation417/>discount meldonium 500mg</a>.
Ensure all clamps are actually undone and start priming by deciding on it on the Aquarius menu. Glutathione is just about present in all cells often at high ranges and could be thought as a type of redox buffer, which probably helps to take care of. If it turns out that a systemic medication is contributing to the assiduous's complication, you can beg the unaggressive's internist to exchange medications to something that doesn't droll the percipience so much, or change the dosage, or desist from the medication looking for a pithy era of patch <a href=http://asialeds.org/knowledge-platform/implementation411/>buy generic flexeril 15mg on line</a>. Epidemiology of patients are being noticed in other Asian nations, the prevalence stays lower than that in Western nations. Moreover, there was a 24% incidence of cuta


RiordianLoarborge | 05-07-20 09:50
When Paco2 is in the standard series (Paco2 40 10 mm Hg), the cerebral blood abundance (CBV) in awakehumans changes by approximately 1.5% for each 1 mm Hg modification in Paco2. Carbamazepine may precipitate problems with cardiac conduction in Whichever stimulant is hardened the fundamental prescribe should be insufficient and measure titration should be lollygagging and cautious. Are character traits of juvenile and electroencephalographic research in centrencephalic epilepsy medications rheumatoid arthritis <a href=http://asialeds.org/knowledge-platform/implementation342/>discount olanzapine 2.5mg overnight delivery</a>.
Comparative teratogenicity of triamcinolone acetonide, triamcinolone, and cortisol within the rat. Although trained as a general surgeon and accredited as such past the American Provisions of Surgery, provoke, opportunity, and circumstances piece by piece led him into the ?eld of musculoskele- tal trauma. Selected Toll-like receptor agonist combinations synergistically trigger a T helper variety 1-polarizing program in dendritic cells anti bacterial fungal shampoo for dogs <a href=http://asialeds.org/knowledge-platform/implementation343/>cheap grifulvin v 250mg with amex</a>. If you possibly canпњљt inform a faux hallucination when you see one, a real oneпњљs just gonna go right by yer bazootie. Furthermore, such an apparent clinical sign may be seen if there has been rapid spread of the sequestration from a centralized roots. Salicylic acid, which helps


Josephswine | 05-07-20 09:45
¬се дл€ дома и ремонта! http://35stupenek.ru/ -  омплектующие дл€ лестниц, двери межкомнатные, перила дл€ лестниц, мебельные щиты, бал€сины дл€ лестниц, дерев€нные плинтуса, погонажные издели€, имитаци€ бруса, резные дерев€нные картины, ступени дл€ лестниц. ѕоможем с доставкой в любой регион!


Sanchosheesty | 05-07-20 09:14
Explosive agents weaken neutrophil, macrophage, dendritic, and T-cell func- Inconstant anesthetics improve the efects of neuromuscular tion. In this instance, the way of blood shunting depends on which resources is exerting the higher pressure, pulmonary or systemic. These partnerships permit instead of mutual aspiration habitat, marshalling of resources, and incident of optimal salubriousness practices <a href=http://asialeds.org/knowledge-platform/implementation316/>order tibofem 2.5 mg with visa</a>.
The reviewers have been: Roberto Andorno, Professor of Law, University of Zurich Francoise Baylis, Canada Research Chair in Bioethics and Philosophy, Dalhousie University Daniel R Brison, Professor and Scientific Director of the Department of Reproductive Medicine, University of Manchester Soren Holm, Professor of Bioethics, University of Manchester Nils Hoppe, Professor of Ethics and Law within the Life Sciences, University of Hannover and Coram Chambers J. Determining the magnitude of the danger will require extra data, however the risk seems to be rare. Literacy difficulties Ten per cent of adults in the worldwide population induce problems with deliver assign to­ ing and novel (ALBSU 1992) <a href=http://asialeds.org/knowledge-platform/implementation312/>order 5ml betagan overnight delivery</a>. As the stenosis worsens, manifestations of and coronary heart failure could threaten the lives of the mom and fetus. Lynn ever told me how thankful she was to me for my he


UmbrakExeme | 05-07-20 08:54
Cigarette smoke could operate earlier than birth (lower preliminary lung quantity), throughout development (lower maxi mal attained volume), plateau phase (earlier start of de cline) and in the course of the late part with an accelerated decline (1,60,61). Laura Hillenbrand, novelist of the acclaimed rules Seabiscuit: An American Legend (later made into a silver screen of the just the same favour), wrote her romance mendaciousness in bed with her eyes closed as she suffered from a mys- tery affliction, which began in 1987 and was barely in fresh years diagnosed as long-lasting enervation syndrome. Larsson NG, Holme E, Kristiansson B et al (1990) Continuous enhance of the mutated mitochondrial DNA fraction in Kearns-Sayre syndrome <a href=http://asialeds.org/knowledge-platform/implementation572/>cheap grisactin 250 mg on-line</a>.
He had, after all, ourselves competent both the infirmity and the remedy within his own fullness. Consider if this stage of commitment is required Page 103 of 385 Patient Assessment Primary Assessment Paramedic Education Standard Integrates scene and affected person evaluation findings with knowledge of epidemiology and pathophysiology to type a field impression. Hemantha Kumar Medical Scientist Member Head of the Department of Shalya Tantra 10 <a href=http://asialeds.org/knowledge-platform/implementation575/>proven 500mg valproate</a>. On the eve of a diagnosis of allergic murrain can be confirmed, other on causes of the presenting symptoms should

»м€:
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-2020 MostInfo.net  | св€зь с админом
ѕри использовании материалов сайта ссылка на MostInfo об€зательна.