Что в html означает function primer
Элемент HTML представляет собой предварительно отформатированный текст, который должен быть представлен точно так, как написано в HTML-файле. Текст обычно отображается с использованием непропорционального («monospace») шрифта. Пробелы внутри этого элемента отображаются как записанные.
Интерактивный пример
| Категории контента | Основной поток, Явный контент |
|---|---|
| Допустимое содержимое | Фразовый контент |
| Пропуск тегов | Нет, открывающий и закрывающий теги обязательны. |
| Допустимые родители | Любой элемент, который принимает содержимое потока |
| Неявные ARIA-роли | Нет соответствующей роли |
| Допустимые ARIA-роли | Любые |
| DOM-интерфейс | HTMLPreElement (en-US) |
Атрибуты
Этот элемент включает в себя только глобальные атрибуты.
Содержит предпочтительное количество символов, которое должна иметь строка. Это был нестандартный синоним width . Чтобы добиться такого эффекта, используйте CSS width .
Содержит предпочтительное количество символов, которое должна иметь строка. Хотя технически он все ещё реализован, этот атрибут не имеет визуального эффекта; чтобы достичь такого эффекта, используйте CSS width .
Подсказка, указывающая, как должен происходить перенос. В современных браузерах этот атрибут игнорируется, и никакого визуального эффекта не приводит; чтобы достичь такого эффекта, используйте CSS white-space .
Пример
HTML
p>Использовать CSS для изменения цвета шрифта легко.p> pre> body < color: red; >pre>
Результат
Проблемы доступности
Важно предоставить альтернативное описание для любых изображений или диаграмм, созданных с использованием предварительно отформатированного текста. Альтернативное описание должно чётко и лаконично описывать содержание изображения или диаграммы.
Люди, испытывающие проблемы с плохим зрением и просматривающие страницы с помощью вспомогательных технологий, таких как программа чтения с экрана, могут не понимать, что представляют собой предварительно отформатированные текстовые символы, когда они читаются последовательно.
Комбинация элементов и , дополненная id и ARIA role и aria-labelledby , позволяет объявить предварительно отформатированный текст как изображение, а figcaption служит альтернативным описанием изображения.
Пример
figure role="img" aria-labelledby="cow-caption"> pre> ____________________________ < Я эксперт в своей области. >---------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || pre> figcaption id="cow-caption"> Корова говорит: «Я эксперт в своей области». Корова проиллюстрирована с использованием предварительно отформатированных текстовых символов. figcaption> figure>
- MDN Understanding WCAG, Guideline 1.1 explanations (en-US)
- H86: Providing text alternatives for ASCII art, emoticons, and leetspeak | W3C Techniques for WCAG 2.0
Характеристики
| Specification |
|---|
| HTML Standard # the-pre-element |
Совместимость браузера
BCD tables only load in the browser
Смотреть также
- CSS: white-space , word-break
- Связанный элемент:
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on 19 нояб. 2023 г. by MDN contributors.
Your blueprint for a better internet.
HTML Tag
The tag defines the relationship between the current document and an external resource.
The tag is most often used to link to external style sheets or to add a favicon to your website.
The element is an empty element, it contains attributes only.
Browser Support
| Element | |||||
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Yes |
Attributes
| Attribute | Value | Description |
|---|---|---|
| crossorigin | anonymous use-credentials |
Specifies how the element handles cross-origin requests |
| href | URL | Specifies the location of the linked document |
| hreflang | language_code | Specifies the language of the text in the linked document |
| media | media_query | Specifies on what device the linked document will be displayed |
| referrerpolicy | no-referrer no-referrer-when-downgrade origin origin-when-cross-origin unsafe-url |
Specifies which referrer to use when fetching the resource |
| rel | alternate author dns-prefetch help icon license next pingback preconnect prefetch preload prerender prev search stylesheet |
Required. Specifies the relationship between the current document and the linked document |
| sizes | HeightxWidth any |
Specifies the size of the linked resource. Only for rel=»icon» |
| title | Defines a preferred or an alternate stylesheet | |
| type | media_type | Specifies the media type of the linked document |
Global Attributes
Event Attributes
Related Pages
HTML DOM reference: Link Object
Default CSS Settings
Most browsers will display the element with the following default values:
link <
display: none;
>
COLOR PICKER


Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
header
header() используется для отправки HTTP -заголовка. В » спецификации HTTP/1.1 есть подробное описание HTTP -заголовков.
Помните, что функцию header() можно вызывать только если клиенту ещё не передавались данные. То есть она должна идти первой в выводе, перед её вызовом не должно быть никаких HTML-тегов, пустых строк и т.п. Довольно часто возникает ошибка, когда при чтении кода файловыми функциями, вроде include или require , в этом коде попадаются пробелы или пустые строки, которые выводятся до вызова header() . Те же проблемы могут возникать и при использовании PHP/HTML в одном файле.
/* Этот пример приведёт к ошибке. Обратите внимание
* на тег вверху, который будет выведен до вызова header() */
header ( ‘Location: http://www.example.com/’ );
exit;
?>
Список параметров
Существует два специальных заголовка. Один из них начинается с » HTTP/ » (регистр не важен) и используется для отправки кода состояния HTTP. Например, если веб-сервер Apache сконфигурирован таким образом, чтобы запросы к несуществующим файлам обрабатывались средствами PHP-скрипта (используя директиву ErrorDocument ), вы наверняка захотите убедиться, что скрипт генерирует правильный код состояния.
// Этот пример иллюстрирует особый случай «HTTP/».
// Лучшие альтернативы в типичных случаях использования включают:
// 1. header($_SERVER[«SERVER_PROTOCOL»] . » 404 Not Found»);
// (чтобы переопределить сообщения о состоянии http для клиентов, которые все еще используют HTTP/1.0)
// 2. http_response_code(404); (для использования сообщения по умолчанию)
header ( «HTTP/1.1 404 Not Found» );
?>?php
Другим специальным видом заголовков является «Location:». В этом случае функция не только отправляет этот заголовок браузеру, но также возвращает ему код состояния REDIRECT (302), если ранее не был установлен код 201 или 3xx .
header ( «Location: http://www.example.com/» ); /* Перенаправление браузера */
?php
/* Убедиться, что код ниже не выполнится после перенаправления .*/
exit;
?>
Необязательный параметр replace определяет, надо ли заменять предыдущий аналогичный заголовок или заголовок того же типа. По умолчанию заголовок будет заменён, но если передать false , можно задать несколько однотипных заголовков. Например:
header ( ‘WWW-Authenticate: Negotiate’ );
header ( ‘WWW-Authenticate: NTLM’ , false );
?>?php
Принудительно задаёт код ответа HTTP. Следует учитывать, что это будет работать, только если строка header не является пустой.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Ошибки
Если не удалось запланировать отправку заголовка, header() выдаёт ошибку уровня E_WARNING .
Примеры
Пример #1 Диалог загрузки
Если нужно предупредить пользователя о необходимости сохранить пересылаемые данные, такие как сгенерированный PDF-файл, можно воспользоваться заголовком » Content-Disposition, который подставляет рекомендуемое имя файла и заставляет браузер показать диалог загрузки.
// Будем передавать PDF
header ( ‘Content-Type: application/pdf’ );
?php
// Он будет называться downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );
// Исходный PDF-файл original.pdf
readfile ( ‘original.pdf’ );
?>
Пример #2 Директивы для работы с кешем
PHP-скрипты часто генерируют динамический контент, который не должен кешироваться клиентским браузером или какими-либо промежуточными обработчиками, вроде прокси-серверов. Можно принудительно отключить кеширование на многих прокси-серверах и браузерах, передав заголовки:
header ( «Cache-Control: no-cache, must-revalidate» ); // HTTP/1.1
header ( «Expires: Sat, 26 Jul 1997 05:00:00 GMT» ); // Дата в прошлом
?>?php
Замечание:
В некоторых случаях ваши страницы не будут кешироваться браузером, даже если вы не передавали этих заголовков. В браузерах есть определённые настройки, с помощью которых пользователь может изменять обычный ход кеширования, отключать его. Вы должны переопределять любые настройки, которые могут повлиять на кеширование скрипта, отправляя приведённые выше заголовки.
Кроме того, для случаев когда используются сессии, можно задать настройки конфигурации session_cache_limiter() и session.cache_limiter . Эти настройки можно использовать для автоматической генерации заголовков управляющих кешированием.
Примечания
Замечание:
Доступ к заголовкам и их вывод будет осуществляться только в случае, если в используемом вами SAPI есть их поддержка.
Замечание:
Чтобы обойти эту проблему, можно буферизовать вывод скрипта. В этом случае все выводимые данные будут буферизоваться на сервере, пока не будет дана явная команда на пересылку данных. Управлять буферизацией можно вручную функциями ob_start() и ob_end_flush() , либо задав директиву output_buffering в конфигурационном файле php.ini , или же настроив соответствующим образом конфигурацию сервера.
Замечание:
Строка заголовка состояния HTTP всегда будет отсылаться клиенту первой, вне зависимости от того был соответствующий вызов функции header() первым или нет. Это состояние можно перезаписать, вызывая header() с новой строкой состояния в любое время, когда можно отправлять HTTP-заголовки.
Замечание:
Спецификация HTTP/1.1 требует указывать абсолютный URI в качестве аргумента » Location:, включающий схему, имя хоста и абсолютный путь, хотя некоторые клиенты способны принимать и относительные URI. Абсолютный URI можно построить самостоятельно с помощью $_SERVER[‘HTTP_HOST’] , $_SERVER[‘PHP_SELF’] и dirname() :
/* Перенаправление браузера на другую страницу в той же директории, что и
изначально запрошенная */
$host = $_SERVER [ ‘HTTP_HOST’ ];
$uri = rtrim ( dirname ( $_SERVER [ ‘PHP_SELF’ ]), ‘/\\’ );
$extra = ‘mypage.php’ ;
header ( «Location: http:// $host$uri / $extra » );
exit;
?>?php
Замечание:
Идентификатор сессии не будет передаваться вместе с заголовком Location, даже если включена настройка session.use_trans_sid. Его нужно передавать вручную, используя константу SID .
Смотрите также
- headers_sent() — Проверяет, были ли отправлены заголовки
- setcookie() — Отправляет cookie
- http_response_code() — Получает или устанавливает код ответа HTTP
- header_remove() — Удаляет ранее установленные заголовки
- headers_list() — Возвращает список переданных заголовков (или готовых к отправке)
- Раздел документации HTTP-аутентификации
User Contributed Notes 33 notes
14 years ago
I strongly recommend, that you use
header($_SERVER[«SERVER_PROTOCOL»].» 404 Not Found»);
header(«HTTP/1.1 404 Not Found»);
I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a «HTTP/1.1 200 Ok» — Header.
Most of the pages were displayed correct, but on some of them apache added weird content to it:
A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)
«0» at the bottom of the page (after the complete output of my php script)
It took me quite a while to find out about the wrong protocol in the HTTP-header.
13 years ago
Several times this one is asked on the net but an answer could not be found in the docs on php.net .
If you want to redirect an user and tell him he will be redirected, e. g. «You will be redirected in about 5 secs. If not, click here.» you cannot use header( ‘Location: . ‘ ) as you can’t sent any output before the headers are sent.
So, either you have to use the HTML meta refresh thingy or you use the following:
16 years ago
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().
// 301 Moved Permanently
header ( «Location: /foo.php» , TRUE , 301 );
// 302 Found
header ( «Location: /foo.php» , TRUE , 302 );
header ( «Location: /foo.php» );
// 303 See Other
header ( «Location: /foo.php» , TRUE , 303 );
// 307 Temporary Redirect
header ( «Location: /foo.php» , TRUE , 307 );
?>
The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it’s a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer «page rank» to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header(‘Location:’) defaults to 302.
4 months ago
If you use header() to allow the user to download a file, it’s very important to check the encoding of the script itself. Your script should be encoded in UTF-8, but definitely not in UTF-8-BOM! The presence of BOM will alter the file received by the user. Let the following script:
$content = file_get_contents ( ‘test_download.png’ ) ;
$name = ‘test.png’ ;
$size = strlen ( $content ) ;
header ( ‘Content-Description: File Transfer’ );
header ( ‘Content-Type: application/octet-stream’ );
header ( ‘Cache-Control: no-cache, must-revalidate’ );
header ( ‘Expires: 0’ );
header ( ‘Content-Disposition: attachment; filename keyword»>. $name . ‘»‘ );
header ( ‘Content-Length: ‘ . $size );
header ( ‘Pragma: public’ );
?>
Irrespectively from the encoding of test_download.png, when this PHP script is encoded in UTF-8-BOM, the content received by the user is different:
— a ZWNBSP byte (U+FEFF) is added to the beginning of the file
— the file content is truncated.
If it’s a binary file (e.g. image, proprietary format), the file will become unreadable.
17 years ago
When using PHP to output an image, it won’t be cached by the client so if you don’t want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.
// Test image.
$fn = ‘/test/foo.png’ ;
// Getting headers sent by the client.
$headers = apache_request_headers ();
// Checking if the client is validating his cache and if it is current.
if (isset( $headers [ ‘If-Modified-Since’ ]) && ( strtotime ( $headers [ ‘If-Modified-Since’ ]) == filemtime ( $fn ))) // Client’s cache IS current, so we just respond ‘304 Not Modified’.
header ( ‘Last-Modified: ‘ . gmdate ( ‘D, d M Y H:i:s’ , filemtime ( $fn )). ‘ GMT’ , true , 304 );
> else // Image not cached or cache outdated, we respond ‘200 OK’ and output the image.
header ( ‘Last-Modified: ‘ . gmdate ( ‘D, d M Y H:i:s’ , filemtime ( $fn )). ‘ GMT’ , true , 200 );
header ( ‘Content-Length: ‘ . filesize ( $fn ));
header ( ‘Content-Type: image/png’ );
print file_get_contents ( $fn );
>
?>
That way foo.png will be properly cached by the client and you’ll save bandwith. 🙂
14 years ago
If using the ‘header’ function for the downloading of files, especially if you’re passing the filename as a variable, remember to surround the filename with double quotes, otherwise you’ll have problems in Firefox as soon as there’s a space in the filename.
So instead of typing:
header ( «Content-Disposition: attachment; filename keyword»>. basename ( $filename ));
?>
you should type:
header ( «Content-Disposition: attachment; filename=\»» . basename ( $filename ) . «\»» );
?>
If you don’t do this then when the user clicks on the link for a file named «Example file with spaces.txt», then Firefox’s Save As dialog box will give it the name «Example», and it will have no extension.
See the page called «Filenames_with_spaces_are_truncated_upon_download» at
http://kb.mozillazine.org/ for more information. (Sorry, the site won’t let me post such a long link. )
3 years ago
Since PHP 5.4, the function `http_response_code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).
15 years ago
You can use HTTP’s etags and last modified dates to ensure that you’re not sending the browser data it already has cached.
$last_modified_time = filemtime ( $file );
$etag = md5_file ( $file );
header ( «Last-Modified: » . gmdate ( «D, d M Y H:i:s» , $last_modified_time ). » GMT» );
header ( «Etag: $etag » );
if (@ strtotime ( $_SERVER [ ‘HTTP_IF_MODIFIED_SINCE’ ]) == $last_modified_time ||
trim ( $_SERVER [ ‘HTTP_IF_NONE_MATCH’ ]) == $etag ) <
header ( «HTTP/1.1 304 Not Modified» );
exit;
>
?>
6 years ago
It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location
«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»
7 years ago
According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:
Content-Disposition: attachment;
filename*= UTF-8»%e2%82%ac%20rates
for backward compatibility, what should be sent is:
Content-Disposition: attachment;
filename=»EURO rates»;
filename*=utf-8»%e2%82%ac%20rates
As a result, we should use
$filename = ‘中文文件名.exe’ ; // a filename in Chinese characters
$contentDispositionField = ‘Content-Disposition: attachment; ‘
. sprintf ( ‘filename=»%s»; ‘ , rawurlencode ( $filename ))
. sprintf ( «filename*=utf-8»%s» , rawurlencode ( $filename ));
header ( ‘Content-Type: application/octet-stream’ );
readfile ( ‘file_to_download.exe’ );
?>
I have tested the code in IE6-10, firefox and Chrome.
5 years ago
The header call can be misleading to novice php users.
when «header call» is stated, it refers the the top leftmost position of the file and not the «header()» function itself.
»
7 years ago
// Response codes behaviors when using
header ( ‘Location: /target.php’ , true , $code ) to forward user to another page :
$code = 301 ;
// Use when the old page has been «permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred.»
$code = 302 ; (default)
// «Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field.»
$code = 303 ;
// «This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached.»
$code = 307 ;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!
// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.
19 years ago
A call to session_write_close() before the statement
header ( «Location: URL» );
exit();
?>
is recommended if you want to be sure the session is updated before proceeding to the redirection.
We encountered a situation where the script accessed by the redirection wasn’t loading the session correctly because the precedent script hadn’t the time to update it (we used a database handler).
15 years ago
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.
This redirects to 2.html since the second header replaces the first.
header ( «location: 1.html» );
header ( «location: 2.html» ); //replaces 1.html
?>
This redirects to 1.html since the header is sent as soon as the echo happens. You also won’t see any «headers already sent» errors because the browser follows the redirect before it can display the error.
header ( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //1.html already sent
?>
Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren’t sent until the output buffer is flushed.
ob_start ();
header ( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //replaces 1.html
ob_end_flush (); //now the headers are sent
?>
11 years ago
Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:
Workaround: do not send those headers.
Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.
Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache’s «BrowserMatch» directive. The following example disables compression in all versions of IE:
BrowserMatch «.*MSIE.*» gzip-only-text/html
6 years ago
Note that ‘session_start’ may overwrite your custom cache headers.
To remedy this you need to call:
. after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.
2 years ago
Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.
If you use something like «header(‘text/javascript’);» to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.
The proper MIME-setting function is «header(‘Content-type: text/javascript’);».
14 years ago
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding
Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header(‘Content-Transfer-Encoding: binary’);
Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header(‘Content-Encoding: gzip’);
15 years ago
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn’t show until a long time or never.
header ( «Content-Disposition: attachment; filename keyword»>. urlencode ( $file ));
header ( «Content-Type: application/force-download» );
header ( «Content-Type: application/octet-stream» );
header ( «Content-Type: application/download» );
header ( «Content-Description: File Transfer» );
header ( «Content-Length: » . filesize ( $file ));
flush (); // this doesn’t really matter.
$fp = fopen ( $file , «r» );
while (! feof ( $fp ))
echo fread ( $fp , 65536 );
flush (); // this is essential for large downloads
>
fclose ( $fp );
?>
5 years ago
/* This will give an error. Note the output
* above, which is before the header() call */
header ( ‘Location: http://www.example.com/’ );
exit;
?>
this example is pretty good BUT in time you use «exit» the parser will still work to decide what’s happening next the «exit» ‘s action should do (’cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
?php
?>
‘CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE.
there are many situations with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!
Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez.
14 years ago
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example.
PHP, by default, always returns the following header:
Which your entire header response will look like
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
If you call the header name with no value like so.
?>
Your headers now look like this:
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close
13 years ago
After lots of research and testing, I’d like to share my findings about my problems with Internet Explorer and file downloads.
Take a look at this code, which replicates the normal download of a Javascript:
if( strstr ( $_SERVER [ «HTTP_USER_AGENT» ], «MSIE» )== false ) header ( «Content-type: text/javascript» );
header ( «Content-Disposition: inline; filename=\»download.js\»» );
header ( «Content-Length: » . filesize ( «my-file.js» ));
> else header ( «Content-type: application/force-download» );
header ( «Content-Disposition: attachment; filename=\»download.js\»» );
header ( «Content-Length: » . filesize ( «my-file.js» ));
>
header ( «Expires: Fri, 01 Jan 2010 05:00:00 GMT» );
if( strstr ( $_SERVER [ «HTTP_USER_AGENT» ], «MSIE» )== false ) header ( «Cache-Control: no-cache» );
header ( «Pragma: no-cache» );
>
include( «my-file.js» );
?>
Now let me explain:
I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the «application/force-download» Content-type is sometimes required to show the download box. Use this if you don’t want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.
Now, here’s my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE. Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!
I hope this saves someone some time!
~Cody G.
3 years ago
I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don’t quite understand it, I hope my posting here does help others with similar issues:
header_remove();
header(«Cache-Control: no-store, no-cache, must-revalidate, max-age=0»);
header(«Cache-Control: post-check=0, pre-check=0», false);
header(«Pragma: no-cache»);
// . and then try redirecting
// 201 = The request has been fulfilled, resulting in the creation of a new resource however it’s still not loading
// 302 «moved temporarily» does seems to load it!
header(«location:$dst», FALSE, 302); // redirect to the file now we have it
8 years ago
Saving php file in ANSI no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
Would give something like this :-
Warning: Cannot modify header information — headers already sent by (output started at C:\www\info.php:1) in C:\www\info.php on line 1
13 years ago
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.
After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to ‘Always perform this operation with this file type’.
As I found out, the problem was in the header directive ‘Content-Disposition’, namely the ‘attachment’ directive.
If you want your browser to simulate a plain link to a file, either change ‘attachment’ to ‘inline’ or omit it alltogether and you’ll be fine.
This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
14 years ago
I just want to add, becuase I see here lots of wrong formated headers.
1. All used headers have first letters uppercase, so you MUST follow this. For example:
Location, not location
Content-Type, not content-type, nor CONTENT-TYPE
2. Then there MUST be colon and space, like
good: header(«Content-Type: text/plain»);
wrong: header(«Content-Type:text/plain»);
3. Location header MUST be absolute uri with scheme, domain, port, path, etc.
4. Relative URIs are NOT allowed
wrong: Location: /something.php?a=1
wrong: Location: ?a=1
It will make proxy server and http clients happier.
20 years ago
If you haven’t used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.
header(«status: 204»); (or the other call)
header(«HTTP/1.0 204 No Response»);
16 years ago
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:
header ( ‘Expires: Sat, 26 Jul 1997 05:00:00 GMT’ );
header ( ‘Last-Modified: ‘ . gmdate ( ‘D, d M Y H:i:s’ ) . ‘ GMT’ );
header ( ‘Cache-Control: no-store, no-cache, must-revalidate’ );
header ( ‘Cache-Control: post-check=0, pre-check=0’ , false );
header ( ‘Pragma: no-cache’ );
8 years ago
DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header(«Location : #whatever»); // -> will not work !
// INSTEAD USE THIS ->
header(«Location: #wahtever»); // -> will work forever !
14 years ago
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need — nor expect — a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1
On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
5 years ago
Setting the «Location: » header has another undocumented side-effect!
It will also disregard any expressly set «Content-Type: » and forces:
«Content-Type: text/html; charset=UTF-8»
The HTTP RFCs don’t call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
«Content-Type: application/xhtml+xml»!
5 years ago
// Beware that adding a space between the keyword «Location» and the colon causes an Internal Sever Error
//This line causes the error
7
header(‘Location : index.php&controller=produit&action=index’);
// While It must be written without the space
header(‘Location: index.php&controller=produit&action=index’);
12 years ago
Setting a Location header «returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set». If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4. It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers). This may have (rare) consequences as mentioned in bug 42969.
- Сетевые функции
- checkdnsrr
- closelog
- dns_check_record
- dns_get_mx
- dns_get_record
- fsockopen
- gethostbyaddr
- gethostbyname
- gethostbynamel
- gethostname
- getmxrr
- getprotobyname
- getprotobynumber
- getservbyname
- getservbyport
- header_register_callback
- header_remove
- header
- headers_list
- headers_sent
- http_response_code
- inet_ntop
- inet_pton
- ip2long
- long2ip
- net_get_interfaces
- openlog
- pfsockopen
- setcookie
- setrawcookie
- socket_get_status
- socket_set_blocking
- socket_set_timeout
- syslog
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
3 способа объявить функцию в JavaScript
Функции в JavaScript можно объявить тремя способами: через декларативное объявление, функциональное выражение или с помощью стрелок. Звучит сложно, но на самом деле всё совсем не так.
Декларативное объявление
Для чего использовать: для любой функции, если вы не планируете записывать её в переменную или передавать в качестве аргумента другим функциями.
Синтаксис и пример использования:
function имяФункции(параметры ) < // Тело функции >; // Пример декларативного объявления function greet(name) < console.log("Привет, " + name + "!"); >;Мы сначала указываем ключевое слово function . За ним идёт имя функции — в нашем случае greet . В круглых скобках пишем параметры, если они есть. Если параметров нет, оставляем просто — () . В фигурных скобках содержится код, который будет выполняться при вызове функции.
️ Тело функции — это код, который выполняется при её вызове.
Плюсы:
- Простой и понятный синтаксис.
- Функцию можно использовать в любом месте в коде, даже до её объявления. Это называется «всплытием функции» (function hoisting).
Минусы:
- Такую функцию нельзя присвоить переменной или передать в качестве аргумента другой функции.
- Функцию можно использовать до её объявления — преимущество легко превращается в недостаток, потому что код сложнее читать и про функцию можно забыть.
Функциональное выражение
Для чего использовать: для функции, которую нужно записать в переменную. А ещё способ полезен, когда функция должна быть доступна только после её объявления.
Синтаксис и пример использования:
const имяПеременной = function(параметры) < // код функции >; // Пример функционального выражения const greet = function(name) < console.log("Привет, " + name + "!"); >;Сначала мы объявляем переменную — у нас это greet . Затем присваиваем ей значение — функцию. Эта функция пишется так же, как и при декларативном объявлении. Но в отличие от него здесь имя функции чаще всего опускается — то есть она является анонимной.
️ Анонимная функция — это функция без имени.
Плюсы:
- Так как функция присваивается переменной, её легко передавать в другие функции.
- Можно создавать функции, которые используются только внутри определённого контекста.
Минусы:
- Нельзя использовать функцию до её объявления, если она анонимна — а так чаще всего и есть.
Стрелочная функция
Для чего использовать: для любых функций, в которых нет контекста this .
Синтаксис и пример использования:
const имяФункции = (параметры) => < // код функции >; // Пример стрелочной функции const sum = (a, b) => < return a + b; >;Стрелочные функции компактны. У них нет имени и ключевого слова function . Вместо них в круглых скобках сразу же пишутся параметры — (a, b) , за которыми идёт стрелка => , а после неё — фигурные скобки с телом функции.
Стрелочную функцию можно записать ещё короче. Если её тело состоит из одного выражения (действия), фигурные скобки и ключевое слово return не нужны:
// Этот пример. const sum = (a, b) => < return a + b; >; // . можно сократить до одной строки const sum = (a, b) => a + b; // А этот пример сократить нельзя — здесь уже несколько действий const sum = (a, b) => < let c = 0; if (a >b) < c = a + b; >return c; >;Если у функции только один параметр, круглые скобки тоже можно отбросить:
// Этот пример. const square = (a) => < return a * a; >; //. можно сократить до одной строки const square = a => a * 2;Но так лучше не делать — скобки визуально отделяют параметры от тела функции и с ними код читать проще. А ещё теряется единообразие в коде, так как это единственный случай, когда скобки можно раскрыть:
const sum = (a, b) => a + b; const square = a => a * 2; const multiplication = () => 2 * 2;Плюсы:
- Компактный синтаксис.
Минусы:
- Порой из-за сокращения ухудшается читаемость кода.
- Не подходит для использования в качестве методов объектов или конструкторов объектов.
- Нельзя использовать функцию до её объявления.
Что использовать
Всё зависит от ваших задач и стандартов оформления кода на вашей работе. Например, в некоторых компаниях принято писать стрелочные функции вместо стандартных функциональных выражений, а где-то наоборот. Главное, чтобы ваш код был единообразным.
Напоследок сравним все способы, чтобы вы могли выбрать подходящий под ваши задачи.
Время создания
- Декларативное объявление: функция создаётся и доступна в любом месте кода до её объявления.
- Функциональное выражение и стрелочная функция: создаётся в момент выполнения кода. Если вызвать до объявления, появится ошибка.
Присваивание переменной
- Декларативное объявление: функция не присваивается переменной. Её нельзя передать другой функции в качестве аргумента.
- Функциональное выражение и стрелочная функция: создаётся и сразу присваивается переменной. Эту переменную можно использовать, чтобы вызывать функцию или передавать в другие функции.
Видимость
- Декларативное объявление: функция становится видимой внутри текущего и будущих блоков кода (функции, циклы, условные операторы и так далее). Это означает, что функцию можно вызывать из любого места внутри блока.
- Функциональное выражение и стрелочная функция: видимость функции ограничена областью видимости переменной, которой она присвоена. Функцию можно вызывать только после присваивания её переменной.
Материалы по теме
- Типы данных в JavaScript. Инструкция для новичков
- Тернарный оператор в JavaScript
- Введение в колбэк-функции в JavaScript
- Как правильно называть переменные
- 9 книг по JavaScript для начинающих
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
Читать дальше

ChatGPT не справляется
Притворитесь нейросетью и решите 101 задачку по JavaScript как можно быстрее.
- 2 ноября 2023

Знакомство с JavaScript
Теперь, когда вы знаете, как создать структуру веб-страницы с помощью HTML и оформить ее стилями с помощью CSS, пришло время оживить её с помощью JavaScript (JS). JavaScript — это мощный язык программирования, который используется для создания интерактивных и динамических веб-сайтов.
Что такое JavaScript?
JavaScript — это язык сценариев, который позволяет вам создавать динамически обновляемый контент, управлять мультимедиа, анимировать изображения и многое другое. Почти все современные веб-сайты используют JavaScript для улучшения пользовательского опыта.
Подключение JavaScript к веб-странице
Вы можете добавить JavaScript в ваш HTML-документ двумя способами:
Встроенный JavaScript: непосредственно в HTML-документ, в тегах :
Внешний JavaScript: подключение внешнего .js файла к HTML-документу:
Основы синтаксиса JavaScript
JavaScript состоит из инструкций, которые выполняются компьютером. Вот пример простого синтаксиса:
var message = "Привет, мир!"; alert(message);Переменные
Переменные в JavaScript — это контейнеры для хранения данных. Вы можете думать о них как о ящиках, на которых есть имена. Переменные объявляются с помощью ключевых слов var , let и const .
var name = "Алиса"; // Старый способ объявления переменной let age = 25; // Современный способ объявления переменной const pi = 3.14; // Константа, значение которой нельзя изменитьФункции
Функции — это блоки кода, предназначенные для выполнения конкретной задачи. Они могут принимать параметры и возвращать значение.
function sayHello(name) < alert("Привет, " + name); >sayHello("Мир");События
События в JavaScript позволяют реагировать на действия пользователя. Например, клик мыши или нажатие клавиши.
document.getElementById("myButton").onclick = function() < alert("Кнопка была нажата!"); >;Условия и циклы
JavaScript также поддерживает условные операторы и циклы для управления потоком выполнения кода.
if (age > 18) < alert("Вы совершеннолетний!"); >else < alert("Вы ещё не совершеннолетний!"); >for (let i = 0; iОбъекты и массивы
Объекты представляют собой коллекции данных, а массивы позволяют хранить упорядоченные коллекции данных.
let person = < name: "Джон", age: 30 >; let numbers = [1, 2, 3, 4, 5];Отметим, что JavaScript не просто добавляет интерактивность к вашим веб-страницам, он также вносит логику и динамичность в ваш сайт. И вот почему это возможно.
Объекты Document Object Model (DOM)
DOM (объектная модель документа) — описывает структуру документа и позволяет программам изменять структуру, стиль и содержание веб-страниц. JavaScript может использовать DOM для манипуляции элементами и атрибутами.
document.getElementById("demo").innerHTML = "Привет, DOM!";Обработка событий
События играют ключевую роль в интерактивности веб-сайтов. JavaScript может отслеживать действия пользователя, такие как клики мышью, нажатия клавиш, перемещения мыши и многие другие.
document.getElementById("myButton").addEventListener("click", function() < alert("Кнопка нажата!"); >);JSON (JavaScript Object Notation)
JSON — это формат обмена данными, легко читаемый как людьми, так и машинами. В JavaScript вы можете легко преобразовывать объекты в JSON и обратно.
let jsonObject = JSON.stringify(< name: "Джон", age: 30 >); let jsObject = JSON.parse(jsonObject);Асинхронность
JavaScript часто используется для асинхронных операций, таких как загрузка данных из интернета без перезагрузки страницы. Промисы и асинхронные функции ( async/await ) являются современными способами работы с асинхронным кодом.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));Замыкания
Замыкания позволяют функции доступ к переменным из области, в которой она была создана, даже после того как эта область перестала существовать. Это мощная концепция в JavaScript для управления приватностью и состоянием.
function createCounter() < let count = 0; return function() < count += 1; return count; >; > const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2Современный синтаксис ES6+
Современный JavaScript включает множество улучшений синтаксиса и новых возможностей, таких как стрелочные функции, классы, шаблонные строки и деструктуризация.
// Стрелочная функция const greet = name => `Привет, $!`; // Класс class Person < constructor(name) < this.name = name; >sayHello() < return `Привет, $!`; > > // Деструктуризация const < name, age >= < name: "Джон", age: 30 >;Подводя итог, JavaScript — это только начало вашего путешествия в создание интерактивных веб-сайтов. Продолжайте изучать и экспериментировать, и вскоре вы сможете создавать сложные веб-приложения.
В следующих статьях мы углубимся в различные аспекты JavaScript, включая современный синтаксис ES6+, асинхронное программирование и работу с фреймворками, такими как React или Vue.
- 1 ноября 2023

Событие onclick в JS на примерах
Интерактивность — ключевой компонент любого современного сайта. И одним из наиболее часто используемых событий для создания интерактивности является событие onclick . В этой статье мы подробно разберёмся, что такое событие onclick , как его использовать и приведем примеры применения.
Событие onclick — это событие JavaScript, которое активируется, когда пользователь кликает на определенный элемент страницы. Это может быть кнопка, ссылка, изображение или любой другой элемент, на который можно нажать.
- 30 октября 2023

Как перевернуть сайт. Самая короткая инструкция
Не представляем, зачем это может понадобиться, но не могли пройти мимо.
Никакой магии. Мы вызываем JavaScript-функцию rotateBody() , которая применяет свойство transform с значением rotate(180deg) к элементу . Когда вы нажмете на кнопку «Перевернуть», всё, что находится внутри будет повернуто на 180 градусов (то есть, встанет вниз головой)
function rotateBody() < document.body.style.transform = 'rotate(180deg)'; >Но такой код повернёт страницу только один раз. Если нужно, чтобы она возвращалась обратно при втором клике, усложним код:
let isRotated = false; function rotateBody() < if (isRotated) < document.body.style.transform = 'rotate(0deg)'; document.body.style.direction = "ltr"; >else < document.body.style.transform = 'rotate(180deg)'; document.body.style.direction = "rtl"; >isRotated = !isRotated; >Надеемся, вы прочитали это описание до того, как нажать на кнопку.
- 25 октября 2023

Как узнать геолокацию: Geolocation API
Geolocation API позволяет сайтам запрашивать, а пользователям предоставлять свое местоположение веб-приложениям. Геолокация может использоваться для выбора города в интернет-магазине, отображения пользователя на карте или навигации в ближайший гипермаркет.
Основной метод Geolocation API — getCurrentPosition() , но есть и другие методы и свойства, которые могут пригодиться.
- 16 октября 2023

Что такое localStorage и как им пользоваться
localStorage — это место в браузере пользователя, в котором сайты могут сохранять разные данные. Это как ящик для хранения вещей, которые не исчезнут, даже если вы выключите компьютер или закроете браузер.
До localStorage разработчики часто использовали cookies, но они были не очень удобны: мало места и постоянная передача данных туда-сюда. LocalStorage появился, чтобы сделать процесс более простым и эффективным.
- 12 октября 2023

Случайное число из диапазона
Допустим, вам зачем-то нужно целое случайное число от min до max . Вот сниппет, который поможет:
function getRandomInRange(min, max)
- Math.random () генерирует случайное число между 0 и 1. Например, нам выпало число 0.54 .
- (max — min + 1): определяет количество возможных значений в заданном диапазоне. 10 — 0 + 1 = 11 . Это значит, что у нас есть 11 возможных значений (0, 1, 2, . 10).
- Math.random () * (max — min + 1): умножает случайное число на количество возможных значений: 0.54 * 11 = 5.94 .
- Math.floor (): округляет число вниз до ближайшего целого. Так, Math.floor(5.94) = 5 .
- . + min: смещает диапазон так, чтобы минимальное значение соответствовало min . Но в нашем примере, так как min = 0 , это не изменит результат. Пример: 5 + 0 = 5 .
- Итак, в нашем примере получилось случайное число 5 из диапазона от 0 до 10.
Чтобы протестировать, запустите:
console.log(getRandomInRange(1, 10)); // Тест- 7 сентября 2023

В чём разница между var и let
Если вы недавно пишете на JavaScript, то наверняка задавались вопросом, чем отличаются var и let , и что выбрать в каждом случае. Объясняем.
var и let — это просто два способа объявить переменную. Вот так:
var x = 10; let y = 20;Переменная, объявленная через var , доступна только внутри «своей» функции, или глобально, если она была объявлена вне функции.
function myFunction() < var z = 30; console.log(z); // 30 >myFunction(); console.log(z); // ReferenceErrorЭто может создавать неожиданные ситуации. Допустим, вы создаёте цикл в функции и хотите, чтобы переменная i осталась в этой функции. Если вы используете var , эта переменная «утечёт» за пределы цикла и будет доступна во всей функции.
Переменные, объявленные с помощью let доступны только в пределах блока кода, в котором они были объявлены.
if (true) < let a = 40; console.log(a); // 40 >console.log(a); // ReferenceErrorВ JavaScript блок кода — это участок кода, заключённый в фигурные скобки <> . Это может быть цикл, код в условном операторе или что-нибудь ещё.
if (true) < let blockScoped = "Я виден только здесь"; console.log(blockScoped); // "Я виден только здесь" >// здесь переменная blockScoped недоступна console.log(blockScoped); // ReferenceErrorЕсли переменная j объявлена в цикле с let , она останется только в этом цикле, и попытка обратиться к ней за его пределами вызовет ошибку.
- 30 августа 2023

Быстрый гайд по if, else, else if в JavaScript
Допустим, вы собираетесь идти на прогулку. Если на улице солнечно, вы возьмёте с собой солнечные очки.
Это можно описать с помощью оператора if .
let weather = "sunny"; if (weather === "sunny")
А если погода не солнечная, а, скажем, дождливая, вы возьмете зонт.
Этот сценарий можно описать с помощью if-else .
let weather = "rainy"; if (weather === "sunny") < console.log("Возьму солнечные очки"); >elseУсловный оператор if-else if-else
Теперь представим, что у вас есть несколько вариантов транспорта для дороги на работу: машина, велосипед, общественный транспорт. Выбор будет зависеть от различных условий, например, погоды и времени суток. Логично, что в дождь безопаснее ехать на автобусе, а в хорошую погоду можно прокатиться на машине или велосипеде, если утро и пробки. То есть схема такая:
И всё это очень легко описывается кодом:
let weather = "sunny"; let time = "morning"; if (weather === "rainy") < // если дождь, то только так console.log("Еду на автобусе"); >else if (time === "morning") < // если не дождь и утро console.log("Еду на велике мимо пробок"); >else < // если второе не дождь и не утро console.log("Еду на машине"); >Ветвление только может показаться сложным, но вообще оно очень логичное, если понять, какие действия после каких условий выполняются. Разберитесь один раз и поймёте на всю жизнь, 100%.
- 30 августа 2023

Как исправить ошибки SyntaxError в JavaScript
Ошибки SyntaxError появляются, если разработчик нарушил правила синтаксиса JavaScript, например, пропустил закрывающую скобку или точку с запятой. Давайте посмотрим, что означает каждая ошибка и в чём может быть проблема.
