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

јфоризм
ќн умчалс€ в ночь на газонокосилке
 
ѕоиск


 
–ассылка
| Soft-≈жедневник - обзор программ пр€мо к ¬ам на e-mail
 
 
ѕолезное!
 
7 лучших
  ¬се о заработке и раскрутке
  "ћир ѕечати_ ƒавыдова"
  јнекдоты,частушки,афоризмы,юмор
  ѕеревозка мебели ’арьков
  DOKUCHAEV.INFO - ћои контакты
  
  
 
  Ѕиблиотека > 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 | >

GeorgBarbots | 18-06-21 08:53
Refer to Chapter physicians changing their follow, such that they three, Section 10 for an outline of potential not prescribe the beforehand accepted sources of bias. The number of glutamate residues current is involved in the regulation of folate-dependent metabolism. It is a strong hyperlink amongst micromaximum level of all samples of tea over monitored vitamins of crops, animals and humans and the absorption period <a href=http://currentsky.com/learning/course32/> erectile dysfunction vacuum pump price buy genuine vpxl online</a>.
Risk evaluation for and techniques to scale back perioperative pulmonary problems for patients undergoing noncardiac-thoracic surgery: A guideline from the American College of Physicians. B 6 An endometrial biopsy obtained with the resectoscope utilizing a cutting loop (Gynecare Versapoint , Ethicon Endo-Surgery Inc. Brown has type O blood according to the model what surface antigens does she have on her red blood cells four <a href=http://currentsky.com/learning/course40/> blood pressure medication during pregnancy purchase generic midamor from india</a>. Moreover, he looked very tall and strong and, due to this particular phenotype, his classmates incessantly mocked him, so he usually reacted aggressively. Answer is 4 Apley,s orthopedics 8th ed/ 230 Maheshwari essential orthopedics 2nd ed/51 (table 10. Inhalation publicity of male Fischer 344 rats for 4 hr to 3 aluminium flakes, at aluminium concentrations of 10, 50, 100, 200 or one thousand


Redgescant | 13-06-21 23:33
Lowest revenue group having low protective foods suffer type rickets and nutritional anemia. Bacteria and mycoplasmas are commonly concerned together in the pathogenesis of pneumonia in goats and sheep. Ocular Alignment in Infancy Ocular deviations through the first month of life do not essentially indicate an abnormality <a href=https://www.piramalcriticalcare.com/wp-content/medical-research/report702/> prostate yeast infection purchase penegra</a>.
Austria made no reservations to the Convention and the implementing legislation offers effective and beneficiant mechanisms for processing Hague Convention requests. In general, retinoic acid seems to in?u man melanocytes, it could possibly alter cell shape, suggesting that ence, in a focus-dependent manner, cell lineage retinoic acid could act on cytoskeleton proteins (397, 543). Some of the common ailments of titis can be caused by staphylococcal, otolaryngologist interest are described here <a href=https://www.piramalcriticalcare.com/wp-content/medical-research/report705/> pain treatment mayo clinic cheap 600mg motrin with mastercard</a>. In addition, long-time period studies have shown that the benefts of calcipotriene remedy had been maintained for up to one yr <eleven>15]. There ought to be education on the nature of melancholy and its therapy choices and will embrace the next: a. The third issue concerns the differentiation from a dysfunction secondary to extreme deafness or to some specific neurological or different str


Leifsum | 11-06-21 11:59
In this procedure, a nonabsorbable suture is positioned within the sclera 16 mm posterior to the limbus and adjoining to the lateral rectus muscle, incorporating one fourth of the transposed vertical rectus muscle. Cryoneurolysis for zygapophyseal joint ache: a multicenter, randomized, double-blind, sham-managed retrospective evaluation of 117 interventions. We use females from this colony as foster moms and as recipients of ovarian and embryo transplants <a href=https://davisislandspharmacy.com/wp-content/medical-professionals/purchase-phenazopyridine/> gastritis gi bleed order phenazopyridine without prescription</a>.
Presyncope is a sense of lightheadedness that is skilled in the setting of worldwide cerebral hypoperfusion. At current, appropriate timing of sperm collection remains unknown and can be variable among sufferers in accordance with their environmental background. Criteria have been established to set off required counseling and a system is in place to alert the 21% 31% 47% pharmacist of this need <a href=https://davisislandspharmacy.com/wp-content/medical-professionals/buy-olmesartan/> arteria zygomatico orbital buy olmesartan 40mg</a>. Ranjkesh F, Barekatain M, Akuchakian S: Bifrontal Houck P: Tranylcypromine versus imipramine in versus right unilateral and bitemporal electrocon anergic bipolar depression. This includes a subjective as well as goal take a look at of excellent reason, counting on the equal and certainly superior capability of women to make a


KliffHek | 10-06-21 21:58
Evaluation, Risk Stratification, and Management of Arrhythmogenic Cardiomyopathy channels,(280) which have several uncommon traits, such as activation on hyperpolarization, permeability to sodium and potassium ions, modulation by intracellular cyclic adenosine monophosphate, and a small single-channel conductance. Rhab considerable size and produce signs by merely domyomas may be surgically cured if the tumor is accessi obstructing mitral infow. Hemodialysis Isoniazid No change 300 mg once day by day, or 900 mg 3 occasions weekly Rifampin No change 600 mg as soon as every day, or 600 mg 3 instances weekly Pyrazinamide Yes 25 35 mg/kg per dose three times weekly (not every day) Ethambutol Yes 15 25 mg/kg per dose three instances weekly (not daily) Levofloxacin Yes 750 a thousand mg per dose 3 occasions weekly (not day by day) Cycloserine Yes 250 mg once every day, or 500 mg/dose three occasions weeklya Ethionamide No change 250 500 mg per dose every day p-Aminosalicylic acid No change 4 g per dose twice daily Streptomycin Yes 12 15 mg/kg per dose 2 or 3 instances weekly (not day by day) Capreomycin Yes 12 15 mg/kg per dose 2 or three times weekly (not daily) Kanamycin Yes 12 15 mg/kg per dose 2 or three occasions weekly (not day by day) Amikacin Yes 12 15 mg/kg per dose 2 or three occasions weekly (not every day) Note: Standard doses are given except there's intolerance <a href=https://davisislandspharmacy.com/wp-content/medical-professionals/buy-casodex-online-in-usa/> prosta


GamalBuifs | 06-06-21 09:10
On the opposite hand, it has been recognized that Similarly, higher calcium ranges in dialysates cardiac arrhythmia is more frequent in sufferers may be useful to sustain calcium balance when it being handled with lower-calcium dialysates. Of the books on adoption, seven were someone s own tales advised in first individual narrative. The case refects the choice-making pro- cess used in the diagnosis and therapy of a red, itchy eye <a href=http://musicfirstcoalition.org/wp-content/records/order-cheap-serpina-no-rx/> anxiety emoji buy serpina 60 caps otc</a>.
The head of each department stories directly to our Collection/Production Director. A 35year-old woman with anemia secondary to myelodysplastic syndrome developed a deep vein thrombosis (location and extent not specified) within the 18th week of being pregnant and was handled with unfractionated heparin. Challenge experiments carried out with human chorionic gonadotropin, gonadotropin-releasing hormone, or naloxone suggested that the decrease in serum testosterone was due to a lesion at the level of the testes <a href=http://musicfirstcoalition.org/wp-content/records/buy-cheap-ritonavir-online-no-rx/> medications you can take while pregnant generic 250mg ritonavir with mastercard</a>. The diagnostic work-up consists of medical and specic prosthesis must be made after in depth patient infor echocardiographic evaluation. Diferential Diagnosis The frst step in developing a diferential prognosis for a white patch (leukoplaki


HjalteHeilmrern | 05-06-21 10:58
Karvonen M, Viik-Kajander M, Moltchanova E, Libman I, LaPorte R, Maternal age at start and childhood sort 1 diabetes: a pooled evaluation of Tuomilehto J. The decision to give a blood transfusion to a patient with persistent anaemia is predicated on the patient's symptoms that indicate an absence of oxygen-transport capacity and a number of medical 108 Blood Transfusion Guideline, 2011 parameters such as affected person age, the pace at which the anaemia occurred, the cause of the anaemia, cardiac and/or pulmonary illness leading to decreased oxygen reserves and/or the flexibility to compensate for the shortage of oxygen transport capacity. Prophylactic therapy during immunosuppressive therapyProphylactic remedy throughout immunosuppressive remedy 1 depression vegetative symptoms <a href=https://www.fastmap.com/wp-content/laboratory-practice/order-bupron-sr/>buy bupron sr 150mg online</a>. Powered instrumentation utilizing a septoplasty bur may be helpful for the discount of bony spurs. There are still main hurdles to cross, nonetheless, like patents and proprietary rights of genes used, in addition to criticism by public interest groups just like the Rural Advancement Foundation International of Canada and others.
The most likely reason for this patientвАЩs respiration difficulties is insufficient production of which of the next substances. Cause and danger elements There is not any easy causal relationship and genetic predisposition in not notably strong. Ammonia intoxica


ZubenBexpede | 05-06-21 10:07
Complete cochlear implant analysis should be performed by a professional audiologist. For households that report each hire and utilities, the three primary wants expenditure sample-weighted averages for meals, utilities and rent are added to calculate complete primary needs expenditure per (equivalent) person. Peripheral the Management of Patients With Lower Extremity Peripheral arterial disease: analysis and management medications zocor <a href=https://www.fastmap.com/wp-content/laboratory-practice/order-coversyl-online/>purchase coversyl uk</a>. However, before this take a look at may have added worth, there may be need for higher treatment options. A variant of this foraminal compression take a look at includes rotation, facet bend, and slight extension of the neck with the appliance of axial stress to the head.
Mode of Transmission Generally, West Nile encephalitis is unfold by the bite of an infected mosquito. These proportions steadily change as the arteries department many occasions and turn into smaller till within the arterioles (the smallest arteries) the tunica media consists almost completely of smooth muscle. Medical Policy In Pharmaceuticals (Therapeutic Medications) part, change title of Antihistaminic and 487 Guide for Aviation Medical Examiners Desensitization Injections to incorporate the word Allergy medications 122 <a href=https://www.fastmap.com/wp-content/laboratory-practice/buy-topamax-online/>buy topamax 100 mg with visa</a>. Cerebral damage (irradia


Ur-Goshembesteda | 22-05-21 17:26
In the past, in several parts of the world, the pterygium was eliminated They do that by using a marking and cutting devise referred to as a Corneal through radiation plaques, which worked by inserting a small steel Punch. Serine and glycine are more abundant than the two others and therefore are the principle sources. The rate of malignant tumours ranges from 10-22%, and < 50 circumstances have been reported (21-23) <a href=https://pd-trak.com/wp-content/conference/buy-online-betapace/> blood pressure gauge cheap betapace 40mg with amex</a>.
About 11-13 days after ovulation, if there isn't any implantation, ovarian production of progesterone and estradiol starts to fall of. It is definitely an organising scheme which allows the evaluation of various skills but technique of standardised and objective testing. If so, then other (unde ter, <10 ?m) is more efficient than that by bigger ?ned) components in addition to the level of preexisting immunity droplets <a href=https://pd-trak.com/wp-content/conference/buy-online-npxl-cheap/> himalaya herbals review purchase genuine npxl on line</a>. The again ought to be rigorously examined in patients with hip complaints, including analyzing for. Choanal atresia, choanal stenosis: Congenital absence (or narrowing) of the passageway between the nose and pharynx because of a thick bone or thin membranous bone. Multifunctional antimicrobial peptides: therapeutic targets in a number of human diseases <a href=https://pd-trak.com/wp-content/


Muntasirpaf | 13-05-21 21:50
The appearance of colonies, or the power or incapability to kind colonies on explicit media can, in some circumstances, be used to identify the genotypes of bacterial cells. Forty freshly extracted intact cal specimens are shown at both concerned in group service vs. Each sarcomere is around 2 –Ю—Шm in length with a three-dimensional cylinder-like organization and is bordered by structures called Z-discs (also called Z-lines, because pictures are two-dimensional), to which the actin myoflaments are anchored (Figure 3) cholesterol quail egg <a href=http://alleneng.net/medical-solutions/account476/>20mg atorlip-20 amex</a>.
In complement to Regulations 883/2004 and 987/2009, which regulate the coordination of social security techniques, the Directive improves affected person selection as sufferers can go to different Member States for therapy, and obtain reimbursement for this treatment if they're entitled to it of their residence nation. Creatine, too, performs a key position in cellular vitality formation and is decreased within the brain cells of hyper Diagnostically, the presence of acidosis, ketosis, hypoglyce ammonemic animals as a result of altered creatine transport and mia, and low bicarbonate ranges indicate that the root explanation for synthesis. Despite this, their staff ship a and even transfer training programs will extremely advanced stage of invasive trauma train that you that you can not obtain a care and carry out airway skills, chest de nice deal in terms


GamalTow | 12-05-21 09:33
The threat reduc tion was estimated to be 88% for coronary coronary heart illness and eighty% for stroke. IвАЩm nonetheless capable of assist with cooking and operating the women to high school in the intervening time. In the occasion that a patient does not respond nicely to the preliminary agent, a unique agent within the similar class is Page 247 appropriate quadriceps fungus <a href=http://alleneng.net/medical-solutions/account78/>purchase lotrisone 10 mg on line</a>.
Cholesteatoma needs radical mastoidec Inward spread towards inside capsule: Paralysis tomy, which removes the irreversible disease and exterior of leg is followed by the paralysis of arm and face. Prescribers must take full accountability for prescribing unlicensed medicinal merchandise and unlicensed uses or administration of licensed products, when such use falls outside the suggestions. Outbreaks as a result of subspecies E meningo cillin/clavulanic acid 875 mg/a hundred twenty five mg orally twice daily, or septica and E anopheles have been related to contami clindamycin can be used (600 mg intravenously every 8 nated water sources and have typically occurred in well being-care hours or 300 mg orally every 6 hours) arterial thrombosis <a href=http://alleneng.net/medical-solutions/account79/>generic aceon 2 mg overnight delivery</a>. Malignancy, infection, drug induced Stop any medicine that may cause hyponatraemia. This section ciation of the significance of involving it in study improvement will chron

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