RSS   Twitter   Copiny   Copiny
Нашел ошибку? 

Выдели фрагмент текста с ошибкой или неточностью и нажми Ctrl+Enter!

Безопасный полнотекстовый поиск в базе данных Joomla

Часто приходится писать расширения, которые используют полнотекстовый поиск по базе данных. Один из таких компонентов — это поиск по сайту. Тут нельзя обойтись простым экранированием, а строка может содержать специфические символы. Для этих целей обычно пользуются LIKE — что очень не безопасно. Попробуем разобраться, как уменьшить риск полнотекстового поиска по базе данных Joomla.

Но как не крути конструкцию LIKE %…% приходится использовать для поиска по базе данных Joomla. Некоторая сложность возникает если мы попытаемся искать специальные символы, который по идее нужно экранировать перед использованием в MySQL-запросах. Существует два основных метода класса JDatabase, которые призваны помочь нам: getEscaped() — для экранирования спец символов и Quote() для обрамления кавычками. Например

// получаем объект базы данных

$db =& JFactory::getDBO();

// подготовка строки для поиска

$escaped = $db->getEscaped($searchFor, true);

$quoted  = $db->Quote('%' . $escaped . '%', false);



// собираем запрос

$like = $db->nameQuote('columnName') . ' LIKE ' . $quoted;


Обычно, когда мы используем JDatabase:Quote(), в нашей строке автоматически экранируются специальные символы. Такие символы как «%" (процент) и «_» (подчеркивание) тоже будут верно экранированы при использовании второго параметра (в примере выше он установлен на «false»). Если это не сделать, то запрос будет выполнен с ошибкой. Для того чтобы верно использовать эту строку воспользуемся методом JDatabase:getEscaped(), в качестве второго параметра которого принимается необязательный параметр, который указывает были ли экранированы спец символы «%" и «_». После этого собираем запрос полностью, обрамляя обработанные строки знаком «%», кавычками и формируем весь запрос.

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

Имя переменойЗначение переменной
$searchFor We are 25% through the_chapter
$escaped We are 25\% through the\_chapter
$quoted '%We are 25\% through the\_chapter%'
$like 'columnName' LIKE '%We are 25\% through the\_chapter%'

 

Пример можно сделать более гибким, если заменить все пробелы символом «%» (напомним, что в контексте MySQL он обозначает любое кол-во символов). В итоге получаем код следующего вида:

// разделяем исходную строку по пробельным символам
$words = preg_split('~[\s,\.]+~', $searchFor);
// перебираем слова, и экранируем в каждом из них символы
for ($i = 0; $i < count($words); $i ++) {
    $words[$i] = $db->getEscaped($words[$i], true);
}

// собираем массив в строку и обрамляем полученную строку кавычками
$quotedSearch = implode('%', $words);
$quotedSearch = $db->Quote('%' . $quotedSearch . '%', false);

// собираем готовый sql
$like = $db->nameQuote('columnName') . ' LIKE ' . $quoted;

Посмотрим значения переменных из этого листинга во время выполнения кода.

Имя переменойЗначение переменной
$searchFor We are 25% through the_chapter
$words array('We', 'are', '25%', 'through', 'the_chapter')
$words array('We', 'are', '25\%', 'through', 'the\_chapter')
$quotedSearch We%are%25\%%through%the\_chapter
$quotedSearch '%We%are%25\%%through%the\_chapter%'
$like 'columnName' LIKE '%We%are%25\%%through%the\_chapter%'

Смотрите также:
Комментарии (45) Добавить комментарий
  • v
    v
    02 Августа 2012, 00:58
     ↑  -1  ↓     ответ

    vgngn

  • tinyurl.com
    tinyurl.com
    23 Ноября 2019, 22:35
     ↑  0  ↓     ответ

    Hello to all, how is all, I think every one is getting more from this

    website, and your views are pleasant in favor of new viewers.

  • http://tinyurl.com/
    http://tinyurl.com/
    24 Ноября 2019, 07:35
     ↑  0  ↓     ответ

    Hello to every one, since I am truly keen of reading this web site's post to be updated regularly.

    It contains good stuff.

  • http://tinyurl.com/w9zzymz
    http://tinyurl.com/w9zzymz
    25 Ноября 2019, 00:16
     ↑  0  ↓     ответ

    Hello there I am so happy I found your website, I really

    found you by error, while I was looking on Google

    for something else, Regardless I am here now and would just like to say thank you

    for a tremendous post and a all round thrilling blog (I also love the theme/design), I

    don’t have time to look over it all at the minute but I have

    bookmarked it and also added in your RSS feeds, so when I have

    time I will be back to read much more, Please do keep up the superb jo.

  • http://tinyurl.com/ufhvv4m
    http://tinyurl.com/ufhvv4m
    25 Ноября 2019, 00:43
     ↑  0  ↓     ответ

    Hello, Neat post. There is an issue together with your web site in web explorer, might check this?

    IE still is the marketplace leader and a huge component

    of other folks will miss your magnificent writing due to this problem.

  • this coconut oil
    this coconut oil
    25 Ноября 2019, 20:17
     ↑  0  ↓     ответ

    Great delivery. Great arguments. Keep up the

    great spirit.

  • plenty of fish dating site
    plenty of fish dating site
    26 Ноября 2019, 20:08
     ↑  0  ↓     ответ

    Great goods from you, man. I have take note your stuff prior to and you're simply extremely fantastic.

    I actually like what you've received right here, really like what you

    are saying and the best way through which you are saying it.

    You're making it entertaining and you still take care of to stay it

    smart. I cant wait to read far more from you. That is really a tremendous website.

  • plenty of fish dating site
    plenty of fish dating site
    27 Ноября 2019, 03:23
     ↑  0  ↓     ответ

    I'm curious to find out what blog system you're working with?

    I'm experiencing some small security issues with my latest blog

    and I would like to find something more safe.

    Do you have any recommendations?

  • ps4 games
    ps4 games
    28 Ноября 2019, 15:07
     ↑  0  ↓     ответ

    Great goods from you, man. I have have in mind your stuff prior to and you are just too wonderful.

    I actually like what you have bought here, certainly like what you are

    stating and the best way in which you are saying it.

    You are making it enjoyable and you still take care of to stay it sensible.

    I can not wait to read much more from you. That is really a wonderful site.

  • ps4 games
    ps4 games
    30 Ноября 2019, 16:08
     ↑  0  ↓     ответ

    Appreciation to my father who shared with me concerning this web site, this blog is

    actually remarkable.

  • quest bars cheap
    quest bars cheap
    02 Декабря 2019, 09:57
     ↑  0  ↓     ответ

    Hello, I enjoy reading all of your article post. I like to write a little comment to

    support you.

  • quest bars cheap coupon twitter
    quest bars cheap coupon twitter
    03 Декабря 2019, 03:50
     ↑  0  ↓     ответ

    always i used to read smaller posts which also clear their motive, and

    that is also happening with this post which I am

    reading now.

  • quest bars cheap
    quest bars cheap
    05 Декабря 2019, 00:35
     ↑  0  ↓     ответ

    Hello there! This blog post could not be written any better!

    Going through this post reminds me of my previous

    roommate! He always kept preaching about this. I'll forward this post to him.

    Pretty sure he will have a great read. I appreciate you for sharing!

  • ps4 games
    ps4 games
    06 Декабря 2019, 04:25
     ↑  0  ↓     ответ

    Hi, always i used to check webpage posts here early in the dawn, since i enjoy to gain knowledge

    of more and more.

  • ps4 games
    ps4 games
    06 Декабря 2019, 04:51
     ↑  0  ↓     ответ

    I'm truly enjoying the design and layout of your blog.

    It's a very easy on the eyes which makes it much more enjoyable

    for me to come here and visit more often. Did you hire out a developer to create your theme?

    Exceptional work!

  • ps4 games
    ps4 games
    06 Декабря 2019, 08:09
     ↑  0  ↓     ответ

    Ahaa, its good conversation on the topic of this piece of writing at this place at this weblog, I have read all

    that, so at this time me also commenting here.

  • ps4 games
    ps4 games
    06 Декабря 2019, 19:18
     ↑  0  ↓     ответ

    Unquestionably believe that which you stated. Your favorite

    justification seemed to be on the internet the easiest thing to be aware of.

    I say to you, I certainly get annoyed while people think about worries that they just do not know about.

    You managed to hit the nail upon the top and defined out

    the whole thing without having side effect , people could take a signal.

    Will probably be back to get more. Thanks

  • ps4 games
    ps4 games
    06 Декабря 2019, 22:06
     ↑  0  ↓     ответ

    I'm curious to find out what blog platform you have been working with?

    I'm having some minor security problems with my

    latest site and I would like to find something more risk-free.

    Do you have any recommendations?

  • ps4 games
    ps4 games
    07 Декабря 2019, 09:13
     ↑  0  ↓     ответ

    I am no longer positive the place you are

    getting your information, but great topic. I must spend some time studying more or understanding more.

    Thanks for wonderful information I was searching for this

    information for my mission.

  • ps4 games
    ps4 games
    07 Декабря 2019, 13:47
     ↑  0  ↓     ответ

    Hi! Someone in my Myspace group shared this site with

    us so I came to check it out. I'm definitely enjoying the information. I'm bookmarking

    and will be tweeting this to my followers! Outstanding blog and amazing design.

  • quest bars cheap
    quest bars cheap
    07 Декабря 2019, 16:13
     ↑  0  ↓     ответ

    Excellent post but I was wondering if you could write a

    litte more on this subject? I'd be very thankful if you could elaborate a little

    bit further. Cheers!

  • quest bars cheap
    quest bars cheap
    09 Декабря 2019, 19:31
     ↑  0  ↓     ответ

    Hi there, I enjoy reading through your article. I wanted to write a

    little comment to support you.

  • quest bars cheap
    quest bars cheap
    10 Декабря 2019, 07:13
     ↑  0  ↓     ответ

    I read this article completely concerning the resemblance of hottest and

    earlier technologies, it's amazing article.

  • ps4 games
    ps4 games
    11 Декабря 2019, 11:04
     ↑  0  ↓     ответ

    I visited many sites but the audio quality for audio songs existing at this web

    page is truly wonderful.

  • ps4 games
    ps4 games
    13 Декабря 2019, 16:25
     ↑  0  ↓     ответ

    Excellent site you have here but I was curious if you knew of any user

    discussion forums that cover the same topics

    talked about in this article? I'd really love to be a part of online community where I can get advice from other experienced individuals that share the same interest.

    If you have any recommendations, please let me know.

    Kudos!

  • ps4 games
    ps4 games
    14 Декабря 2019, 06:33
     ↑  0  ↓     ответ

    At this moment I am going away to do my breakfast, when having my breakfast coming again to read more news.

  • coconut oil
    coconut oil
    16 Декабря 2019, 10:46
     ↑  0  ↓     ответ

    whoah this weblog is great i like reading your articles.

    Keep up the great work! You understand, lots of people are searching around

    for this information, you could aid them greatly.

  • coconut oil
    coconut oil
    18 Декабря 2019, 03:58
     ↑  0  ↓     ответ

    Hi! This post couldn't be written any better! Reading this post reminds me of my

    good old room mate! He always kept chatting about this.

    I will forward this article to him. Pretty sure he will have a good read.

    Thank you for sharing!

  • coconut oil
    coconut oil
    19 Декабря 2019, 16:12
     ↑  0  ↓     ответ

    My spouse and I stumbled over here coming from a different website and

    thought I might check things out. I like what I see so i am just following you.

    Look forward to looking into your web page repeatedly.

  • match.com free trial
    match.com free trial
    29 Декабря 2019, 09:44
     ↑  0  ↓     ответ

    magnificent issues altogether, you simply received a emblem new reader.

    What may you recommend in regards to your post that you simply made some days in the past?

    Any certain?

  • plenty of fish vs match.com free trial
    plenty of fish vs match.com free trial
    30 Декабря 2019, 17:07
     ↑  0  ↓     ответ

    Good post. I learn something new and challenging on sites I stumbleupon everyday.

    It's always useful to read through content from other writers and use a little

    something from their sites.

  • match.com free trial
    match.com free trial
    31 Декабря 2019, 02:23
     ↑  0  ↓     ответ

    I was suggested this blog by my cousin. I am not sure

    whether this post is written by him as no one else know such detailed about

    my trouble. You are wonderful! Thanks!

  • http://asksylphoflight.tumblr.com
    http://asksylphoflight.tumblr.com
    31 Декабря 2019, 21:24
     ↑  0  ↓     ответ

    Great post. I used to be checking continuously this blog and I'm inspired!

    Extremely useful info particularly the ultimate phase :) I handle such information much.

    I used to be seeking this particular info for a very long time.

    Thank you and good luck.

  • https://russellwebster.tumblr.com/
    https://russellwebster.tumblr.com/
    01 Января 2020, 15:11
     ↑  0  ↓     ответ

    Hello, yup this article is really fastidious and I have learned lot of things from

    it about blogging. thanks.

  • sling tv
    sling tv
    01 Января 2020, 19:02
     ↑  0  ↓     ответ

    It's awesome to visit this web page and reading the views of all friends on the topic of this piece of writing,

    while I am also keen of getting experience.

  • http://tinyurl.com
    http://tinyurl.com
    02 Января 2020, 23:34
     ↑  0  ↓     ответ

    This information is priceless. How can I find out more?

  • sling tv asksylphoflight
    sling tv asksylphoflight
    05 Января 2020, 13:41
     ↑  0  ↓     ответ

    Great beat ! I wish to apprentice even as you amend your website, how could i subscribe

    for a blog web site? The account helped me a appropriate deal.

    I had been a little bit acquainted of this your broadcast provided

    bright clear concept

  • sling tv
    sling tv
    07 Января 2020, 08:00
     ↑  0  ↓     ответ

    Wonderful goods from you, man. I have understand your

    stuff previous to and you're just too wonderful.

    I really like what you have acquired here, really like what you're saying

    and the way in which you say it. You make it entertaining and you

    still care for to keep it wise. I can't wait to read far more from you.

    This is really a wonderful site.

  • sling tv asksylphoflight
    sling tv asksylphoflight
    07 Января 2020, 15:43
     ↑  0  ↓     ответ

    It's a pity you don't have a donate button! I'd without

    a doubt donate to this fantastic blog! I suppose for now i'll settle for bookmarking and

    adding your RSS feed to my Google account. I look forward to brand new updates and

    will talk about this site with my Facebook group. Chat soon!

  • http://tinyurl.com
    http://tinyurl.com
    07 Января 2020, 18:21
     ↑  0  ↓     ответ

    Hey! I just wanted to ask if you ever have any problems with hackers?

    My last blog (wordpress) was hacked and I ended up losing

    months of hard work due to no backup. Do you have any

    methods to protect against hackers?

  • sling tv
    sling tv
    14 Января 2020, 07:13
     ↑  0  ↓     ответ

    I was pretty pleased to discover this page.

    I need to to thank you for your time due to this fantastic read!!

    I definitely really liked every part of it and I have you book marked to check out new things in your blog.

  • sling tv
    sling tv
    14 Января 2020, 19:34
     ↑  0  ↓     ответ

    Tremendous issues here. I am very satisfied to see

    your article. Thanks a lot and I am looking forward to touch you.

    Will you please drop me a mail?

  • sling tv
    sling tv
    15 Января 2020, 21:10
     ↑  0  ↓     ответ

    I do not know if it's just me or if everyone else experiencing problems with your site.

    It appears as if some of the text within your posts are running off

    the screen. Can somebody else please provide feedback and let me

    know if this is happening to them too? This might

    be a issue with my browser because I've had this happen previously.

    Many thanks

  • sling tv
    sling tv
    17 Января 2020, 05:22
     ↑  0  ↓     ответ

    If some one needs expert view about running a blog

    then i propose him/her to pay a quick visit this web

    site, Keep up the nice job.

  • sling tv
    sling tv
    19 Января 2020, 09:34
     ↑  0  ↓     ответ

    Fantastic web site. Plenty of helpful information here. I am sending it

    to several buddies ans also sharing in delicious.

    And obviously, thank you on your effort!

Оставить комментарий




* обязательно для заполнения

1 введенный почтовый адрес используется только для обратной связи при ответах в комментариях и сервиса gravatar.com
.