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

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

Обработка имен файлов

Joomla может содержать большое кол-во файлов. Взаимодействие с ними: автоматическое создание имен, чтение, запись - обычное дело для некоторых компонентов Joomla. Хорошим примером в этом случае можно назвать «Медиа менеджер». При неправильном именовании файлов и обращении к ним существует опасность непредвиденных ошибок на сервере и даже дыр в безопасности. Особо нужно быть осторожным, если пользователю самому дано право менять имена файлов на сервере, либо загружить свои. Подробную информацию о уязвимости можно прочитать на сайте cwe.mitre.org.

Статический класс JFile, который предоставляет нам встроенная библиотека из набора Joomla. Подключить библиотеку можно с помощью следующей строки.

jimport('joomla.filesystem.file');

Обезопасить имя файла очень просто - для этого есть универсальный метод

// делаем имя файла безопасным
$safeFilename = JFile::makeSafe($unsafeFilename);

Как работает makeSafe() ? Очень просто! Он проверяет наличие в строке спецсимволов и последовательностей, Если находит что-либо подозрительное, то просто удаляет их из исходного файла.

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

  • Имя не должно начинаться с точки
  • Удаляются точки стоящие рядом
  • Все символы кроме латиницы, точки, цифр, подчеркивания, пробела минуса будут удалены
Оригинальное
Безопасное
Комментарий
.htaccess htaccess Убирает точку в начале имени
some%20file.html some20file.html Символ (%) процент
../../traversed.file traversed.file Удаление разделителя (/) и двойных точек
spaced out.file spaced out.file Все нормально, изменений не произходило
dotty...to..the.dot dottytothe.dot Повторение символа точки (.)

 

Часто бывает необходимо проверить расширение файла, чтобы отказаться в загрузке подозрительных (например ".php"). В этом нам поможет метод getExt():


switch (JFile::getExt($filename)) {
    case 'jpeg':
    case 'jpg':
        echo 'File is a JPEG';
        break;
    case 'gif':
        echo 'File is a GIF';
        break;
    default:
        echo 'File is not a JPEG or a GIF';
}

При необходимости можно очень просто удалить расширения в имени файла

$filenameWithoutExtension = JFile::stripExt($filename);

Таким образом можно для картинок в формате JPEG, у которых расширение может встретиться как ".jpeg", так и ".jpg", сделать небольшой сценарий, чтобы все картинки подобного формата всегда хранились с одним и тем же расширением.

$filename = JFile::stripExt($filename) . '.jpeg';

Так же полезным может оказаться метод для проверки существования файла. Например так

if (JFile::exists($filename)) {
    echo "<img src=\"$filename\" alt=\"image\">";
} else {
    echo JText::_("No Image File");
}

Смотрите также:
Комментарии (9) Добавить комментарий
  • goo.gl
    goo.gl
    13 Июля 2018, 19:31
     ↑  0  ↓     ответ

    ? am in fact delighted to read this webb site posts which c?ntains lots oof usefu? information, t?anks for providing these data.

  • pocket knives high quality
    pocket knives high quality
    15 Июля 2018, 19:02
     ↑  0  ↓     ответ

    Hі, its fastidious piece of writing on the topіc of media pгint, we all be aware of media is a impressi?e source of data.

  • energy and health
    energy and health
    07 Мая 2020, 01:43
     ↑  0  ↓     ответ

    It's awesome designed for me to have a website, which is beneficial in support of my knowledge.

    thanks admin

  • g
    g
    15 Июня 2020, 17:36
     ↑  0  ↓     ответ

    I am sure this article has touched all the internet users, its really really pleasant piece

    of writing on building up new webpage.

  • g
    g
    16 Июня 2020, 13:17
     ↑  0  ↓     ответ

    Hey there, You have done an incredible job. I

    will definitely digg it and personally suggest to my friends.

    I am sure they will be benefited from this website.

  • g
    g
    17 Июня 2020, 06:51
     ↑  0  ↓     ответ

    Asking questions are in fact good thing if you are not understanding something completely, but this paragraph offers fastidious understanding yet.

  • g
    g
    17 Июня 2020, 21:15
     ↑  0  ↓     ответ

    Hi there, just became aware of your blog through Google,

    and found that it's truly informative. I am gonna watch out for brussels.

    I'll be grateful if you continue this in future. Lots

    of people will be benefited from your writing.

    Cheers!

  • Lou
    Lou
    28 Января 2023, 10:50
     ↑  0  ↓     ответ

    Dear joomla-book.ru owner, Thanks for the well-structured and well-presented post!

  • casino en ligne
    casino en ligne
    24 Мая 2025, 14:40
     ↑  0  ↓     ответ

    I all the time used to read paragraph in news papers but now

    as I am a user of internet thus from now I am using

    net for content, thanks to web.

    casino en ligne

    Very descriptive article, I loved that a lot. Will there be

    a part 2?

    casino en ligne

    Its not my first time to pay a quick visit this site, i am visiting this site dailly and

    obtain nice information from here every day.

    casino en ligne

    With havin so much content and articles do you ever run into any issues

    of plagorism or copyright violation? My blog has a lot of unique content I've either created myself or outsourced but it seems a lot of it is popping it up all

    over the web without my agreement. Do you know any solutions to

    help stop content from being stolen? I'd really appreciate it.

    casino en ligne

    Greetings! I know this is somewhat off topic but I was wondering which blog platform are you using for

    this website? I'm getting tired of Wordpress because I've had

    problems with hackers and I'm looking at alternatives for another platform.

    I would be fantastic if you could point me in the direction of a good platform.

    casino en ligne francais

    It's amazing to visit this web page and reading the views of all colleagues regarding this post,

    while I am also eager of getting familiarity.

    casino en ligne

    Nice answer back in return of this issue with solid arguments and telling the whole thing about that.

    casino en ligne

    What's up, I read your blogs daily. Your humoristic style is witty,

    keep it up!

    meilleur casino en ligne

    What's up to every body, it's my first go to see of this website; this weblog carries remarkable and genuinely fine data in favor of visitors.

    casino en ligne francais

    I don't know whether it's just me or if perhaps everybody else encountering problems with your blog.

    It appears as though 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 as well? This may be a issue with my browser because I've

    had this happen previously. Many thanks

    casino en ligne

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




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

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