Php подгрузить файл html

DOMDocument::loadHTML

The function parses the HTML contained in the string source . Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Parameters

Since Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Return Values

Returns true on success or false on failure. If called statically, returns a DOMDocument or false on failure.

Errors/Exceptions

If an empty string is passed as the source , a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml’s error handling functions.

Prior to PHP 8.0.0 this method could be called statically, but would issue an E_DEPRECATED error. As of PHP 8.0.0 calling this method statically throws an Error exception

While malformed HTML should load successfully, this function may generate E_WARNING errors when it encounters bad markup. libxml’s error handling functions may be used to handle these errors.

Examples

Example #1 Creating a Document

See Also

  • DOMDocument::loadHTMLFile() — Load HTML from a file
  • DOMDocument::saveHTML() — Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() — Dumps the internal document into a file using HTML formatting
Читайте также:  Python поиск замена подстроки

User Contributed Notes 19 notes

You can also load HTML as UTF-8 using this simple hack:

$doc = new DOMDocument ();
$doc -> loadHTML ( » . $html );

// dirty fix
foreach ( $doc -> childNodes as $item )
if ( $item -> nodeType == XML_PI_NODE )
$doc -> removeChild ( $item ); // remove hack
$doc -> encoding = ‘UTF-8’ ; // insert proper

DOMDocument is very good at dealing with imperfect markup, but it throws warnings all over the place when it does.

This isn’t well documented here. The solution to this is to implement a separate aparatus for dealing with just these errors.

Set libxml_use_internal_errors(true) before calling loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions.

When using loadHTML() to process UTF-8 pages, you may meet the problem that the output of dom functions are not like the input. For example, if you want to get «Cạnh tranh», you will receive «Cạnh tranh». I suggest we use mb_convert_encoding before load UTF-8 page :
$pageDom = new DomDocument ();
$searchPage = mb_convert_encoding ( $htmlUTF8Page , ‘HTML-ENTITIES’ , «UTF-8» );
@ $pageDom -> loadHTML ( $searchPage );

Pay attention when loading html that has a different charset than iso-8859-1. Since this method does not actively try to figure out what the html you are trying to load is encoded in (like most browsers do), you have to specify it in the html head. If, for instance, your html is in utf-8, make sure you have a meta tag in the html’s head section:

If you do not specify the charset like this, all high-ascii bytes will be html-encoded. It is not enough to set the dom document you are loading the html in to UTF-8.

Warning: This does not function well with HTML5 elements such as SVG. Most of the advice on the Web is to turn off errors in order to have it work with HTML5.

If we are loading html5 tags such as

, there is following error:

DOMDocument::loadHTML(): Tag section invalid in Entity

We can disable standard libxml errors (and enable user error handling) using libxml_use_internal_errors(true); before loadHTML();

This is quite useful in phpunit custom assertions as given in following example (if using phpunit test cases):

// Create a DOMDocument
$dom = new DOMDocument();

// fix html5/svg errors
libxml_use_internal_errors(true);

// Load html
$dom->loadHTML(» «);
$htmlNodes = $dom->getElementsByTagName(‘section’);

if ($htmlNodes->length == 0) $this->assertFalse(TRUE);
> else $this->assertTrue(TRUE);
>

Remember: If you use an HTML5 doctype and a meta element like so

your HTML code will get interpreted as ISO-8859-something and non-ASCII chars will get converted into HTML entities. However the HTML4-like version will work (as has been pointed out 10 years ago by «bigtree at 29a»):

It should be noted that when any text is provided within the body tag
outside of a containing element, the DOMDocument will encapsulate that
text into a paragraph tag (

).

For those of you who want to get an external URL’s class element, I have 2 usefull functions. In this example we get the ‘


elements back (search result headers) from google search:

1. Check the URL (if it is reachable, existing)
# URL Check
function url_check ( $url ) <
$headers = @ get_headers ( $url );
return is_array ( $headers ) ? preg_match ( ‘/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/’ , $headers [ 0 ]) : false ;
>;
?>

2. Clean the element you want to get (remove all tags, tabs, new-lines etc.)
# Function to clean a string
function clean ( $text ) $clean = html_entity_decode ( trim ( str_replace ( ‘;’ , ‘-‘ , preg_replace ( ‘/\s+/S’ , » » , strip_tags ( $text ))))); // remove everything
return $clean ;
echo ‘\n’ ; // throw a new line
>
?>

After doing that, we can output the search result headers with following method:
$searchstring = ‘djceejay’ ;
$url = ‘http://www.google.de/webhp#q=’ . $searchstring ;
if( url_check ( $url )) $doc = new DomDocument ;
$doc -> validateOnParse = true ;
$doc -> loadHtml ( file_get_contents ( $url ));
$output = clean ( $doc -> getElementByClass ( ‘r’ )-> textContent );
echo $output . ‘
‘ ;
>else echo ‘URL not reachable!’ ; // Throw message when URL not be called
>
?>

Be aware that this function doesn’t actually understand HTML — it fixes tag-soup input using the general rules of SGML, so it creates well-formed markup, but has no idea which element contexts are allowed.

For example, with input like this where the first element isn’t closed:

loadHTML will change it to this, which is well-formed but invalid:

Источник

Загрузка файлов на сайт: PHP, AJAX, HTML5 и Drag’n’Drop

Скучные формы загрузки — прошлый век. HTML5 дает возможности, чтобы добавить Drag’n’Drop, а AJAX позволяет загружать файлы без обновления страницы.

Евгений Кучерявый

Пишет о программировании, в свободное время создаёт игры. Мечтает открыть свою студию и выпускать ламповые RPG.

В основном пользователи смотрят или скачивают информацию с сайтов, но иногда им может быть нужно что-нибудь загрузить самим. Это может быть аватарка, архив с документами, песня, видео со свадьбы или статья в формате .docx.

Программисту нужно позаботиться о том, чтобы посетитель смог сделать это максимально удобно. Загрузить файл на сайт можно и с помощью обычной формы и обработчика на PHP, но с выходом HTML5 появились другие интересные возможности — в этой статье мы поговорим и о базовых функциях, и о нововведениях.

Загрузка файлов на PHP

Начать следует с создания формы:

Форма уже функционирует: можно выбирать или перетаскивать файлы, а после нажатия на кнопку «Загрузить» данные отправятся в обработчик. Там они попадают в многомерный супермассив $_FILES. Его структура выглядит так:

  • имя поля, через которое загружен файл;
  • name — имя загружаемого файла;
  • type — тип в формате MIME-type;
  • size — объем в байтах;
  • tmp_name — временный адрес;
  • error — номер ошибки, если она произошла.

Если через одно поле загружается сразу несколько файлов, то получение доступа к какому-то конкретному происходит следующим образом: $_FILES[‘file’][‘name’][0] — индекс файла находится в самом конце.

Сначала нужно провести несколько проверок, и только потом перемещать файлы из временного хранилища непосредственно на сайт. Иначе может получиться так, что взломщики загрузят на сайт PHP-файлы и смогут их запустить, чтобы получить доступ к базе данных или к файловой системе сервера.

Вот как выглядит обработчик:

Заключение

Дальше с файлами можно делать все что угодно:

  • использовать изображения в статьях и в качестве аватарок;
  • добавить плеер, который будет воспроизводить видео и аудио;
  • создать текстовый, графический или аудио/видеоредактор;
  • разрешать скачивать файлы по ссылке и так далее.

Читайте также:

Источник

Загрузка файлов на сервер PHP

Загрузка файлов на сервер PHP

В статье приведен пример формы и php-скрипта для безопасной загрузки файлов на сервер, возможные ошибки и рекомендации при работе с данной темой. HTML-форма отправит файл только методом POST и с атрибутом enctype=»multipart/form-data» .

Форма для загрузки сразу нескольких файлов

Файл upload.php

  • Поддерживает как одиночную загрузку файла так и множественную (multiple) без изменения кода.
  • Проверка на все возможные ошибки которые могут возникнуть при загрузке файлов.
  • Имена файлов переводятся в транслит и удаляются символы которые будут в дальнейшем мешать вывести их на сайте.
  • Есть возможность указать разрешенные и запрещенные для загрузки расширения файлов.
// Название $input_name = 'file'; // Разрешенные расширения файлов. $allow = array(); // Запрещенные расширения файлов. $deny = array( 'phtml', 'php', 'php3', 'php4', 'php5', 'php6', 'php7', 'phps', 'cgi', 'pl', 'asp', 'aspx', 'shtml', 'shtm', 'htaccess', 'htpasswd', 'ini', 'log', 'sh', 'js', 'html', 'htm', 'css', 'sql', 'spl', 'scgi', 'fcgi' ); // Директория куда будут загружаться файлы. $path = __DIR__ . '/uploads/'; if (isset($_FILES[$input_name])) < // Проверим директорию для загрузки. if (!is_dir($path)) < mkdir($path, 0777, true); >// Преобразуем массив $_FILES в удобный вид для перебора в foreach. $files = array(); $diff = count($_FILES[$input_name]) - count($_FILES[$input_name], COUNT_RECURSIVE); if ($diff == 0) < $files = array($_FILES[$input_name]); >else < foreach($_FILES[$input_name] as $k =>$l) < foreach($l as $i =>$v) < $files[$i][$k] = $v; >> > foreach ($files as $file) < $error = $success = ''; // Проверим на ошибки загрузки. if (!empty($file['error']) || empty($file['tmp_name'])) < switch (@$file['error']) < case 1: case 2: $error = 'Превышен размер загружаемого файла.'; break; case 3: $error = 'Файл был получен только частично.'; break; case 4: $error = 'Файл не был загружен.'; break; case 6: $error = 'Файл не загружен - отсутствует временная директория.'; break; case 7: $error = 'Не удалось записать файл на диск.'; break; case 8: $error = 'PHP-расширение остановило загрузку файла.'; break; case 9: $error = 'Файл не был загружен - директория не существует.'; break; case 10: $error = 'Превышен максимально допустимый размер файла.'; break; case 11: $error = 'Данный тип файла запрещен.'; break; case 12: $error = 'Ошибка при копировании файла.'; break; default: $error = 'Файл не был загружен - неизвестная ошибка.'; break; >> elseif ($file['tmp_name'] == 'none' || !is_uploaded_file($file['tmp_name'])) < $error = 'Не удалось загрузить файл.'; >else < // Оставляем в имени файла только буквы, цифры и некоторые символы. $pattern = "[^a-zа-яё0-9,~!@#%^-_\$\?\(\)\\[\]\.]"; $name = mb_eregi_replace($pattern, '-', $file['name']); $name = mb_ereg_replace('[-]+', '-', $name); // Т.к. есть проблема с кириллицей в названиях файлов (файлы становятся недоступны). // Сделаем их транслит: $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', ); $name = strtr($name, $converter); $parts = pathinfo($name); if (empty($name) || empty($parts['extension'])) < $error = 'Недопустимое тип файла'; >elseif (!empty($allow) && !in_array(strtolower($parts['extension']), $allow)) < $error = 'Недопустимый тип файла'; >elseif (!empty($deny) && in_array(strtolower($parts['extension']), $deny)) < $error = 'Недопустимый тип файла'; >else < // Чтобы не затереть файл с таким же названием, добавим префикс. $i = 0; $prefix = ''; while (is_file($path . $parts['filename'] . $prefix . '.' . $parts['extension'])) < $prefix = '(' . ++$i . ')'; >$name = $parts['filename'] . $prefix . '.' . $parts['extension']; // Перемещаем файл в директорию. if (move_uploaded_file($file['tmp_name'], $path . $name)) < // Далее можно сохранить название файла в БД и т.п. $success = 'Файл «' . $name . '» успешно загружен.'; >else < $error = 'Не удалось загрузить файл.'; >> > // Выводим сообщение о результате загрузки. if (!empty($success)) < echo '

' . $success . '

'; > else < echo '

' . $error . '

'; > > >

Возможные проблемы

  • На unix хостингах php функция move_uploaded_file() не будут перемещать файлы в директорию если у нее права меньше 777.
  • Загрузка файлов может быть отключена в настройках PHP директивой file_uploads .
  • Не загружаются файлы большого размера, причина в ограничениях хостинга.
    Посмотрите в phpinfo() значения директив:
    • upload_max_filesize – максимальный размер закачиваемого файла.
    • max_file_uploads – максимальное количество одновременно закачиваемых файлов.
    • post_max_size – максимально допустимый размер данных, отправляемых методом POST, его значение должно быть больше upload_max_filesize .
    • memory_limit – значение должно быть больше чем post_max_size .

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

    Источник

Оцените статью