If, when you test the file in a browser, you see the HTML code rather than your greeting, it may be because you launched the page by dragging it to your browser. The URL should start with 'http://' NOT 'file://'
Первая страница на PHP
Создайте файл с именем hello.php в корневом каталоге веб-сервера (DOCUMENT_ROOT) и запишите в него следующее:
Пример #1 Первый скрипт на PHP: hello.php
<html>
<head>
<title>Тестируем PHP</title>
</head>
<body>
<?php echo '<p>Привет, мир!</p>'; ?>
</body>
</html>
Откройте данный файл в браузере, набрав имя вашего веб-сервера и /hello.php. При локальной разработке эта ссылка может быть чем-то вроде http://localhost/hello.php или http://127.0.0.1/hello.php, но это зависит от настроек вашего сервера. Если всё настроено правильно, этот файл будет обработан PHP и браузер выведет следующий текст:
<html> <head> <title>PHP Test</title> </head> <body> <p>Hello World</p> </body> </html>
Эта программа чрезвычайно проста, и для создания настолько простой странички даже необязательно использовать PHP. Всё, что она делает, это вывод Hello World, используя инструкцию PHP echo. Заметьте, что файл не обязан быть выполняемым или еще как-то отличаться от других файлов. Сервер знает, что этот файл должен быть обработан PHP, так как файл обладает расширением ".php", о котором в настройках сервера сказано, что подобные файлы должны передаваться PHP. Рассматривайте его как обычный HTML-файл, которому посчастливилось заполучить набор специальных тегов (доступных также и вам), способных на кучу интересных вещей.
Если у вас этот пример не отображает ничего или выводит окно загрузки, или если вы видите весь этот файл в текстовом виде, то, скорее всего, ваш веб-сервер не имеет поддержки PHP или был сконфигурирован неправильно. Попросите вашего администратора сервера включить такую поддержку. Предложите ему инструкцию по установке: раздел Установка данной документации. Если же вы разрабатываете скрипты на PHP дома (локально), то также прочтите эту главу, чтобы убедиться, что вы всё настроили верно. Убедитесь также, что вы запрашиваете файл у сервера через протокол http. Если вы просто откроете файл из вашей файловой системы, он не будет обработан PHP. Если проблемы все же остались, не стесняйтесь попросить помощи одним из » множества доступных способов получения поддержки по PHP.
Цель примера - показать формат специальных тегов PHP. В этом примере мы использовали <?php в качестве открывающего тега, затем шли команды PHP, завершающиеся закрывающим тегом ?>. Таким образом можно где угодно "запрыгивать" и "выпрыгивать" из режима PHP в HTML файле. Подробнее об этом можно прочесть в разделе руководства Основной синтаксис.
Замечание: Замечание о переводах строк
Переводы строк немногое означают в HTML, однако считается хорошей идеей поддерживать HTML в удобочитаемом виде, перенося его на новую строку. PHP автоматически удаляет перевод строки, идущий сразу после закрывающего тега ?>. Это может быть чрезвычайно полезно, если вы используете множество блоков PHP-кода или подключаете PHP-файлы, которые не должны ничего выводить. В то же время, это может приводить в недоумение. Можно поставить пробел после закрывающего тега ?> и тогда пробел будет выведен вместе с переводом строки, или же вы можете специально добавить перевод строки в последний вызов echo/print из блока PHP-кода.
Замечание: Пара слов о текстовых редакторах
Существует множество текстовых редакторов и интегрированных сред разработки (IDE), в которых вы можете создавать и редактировать файлы PHP. Список некоторых редакторов содержится в разделе » Список редакторов PHP. Если вы хотите порекомендовать какой-либо редактор, посетите данную страницу и попросите добавить редактор в список. Использование редактора с подсветкой синтаксиса может быть очень большим подспорьем в вашей работе.
Замечание: Пара слов о текстовых процессорах
Текстовые процессоры (StarOffice Writer, Microsoft Word, Abiword и др.) в большинстве случаев не подходят для редактирования файлов PHP. Если вы все же хотите использовать какой-либо из них для тестового скрипта, убедитесь, что сохраняете файл как простой текст (plain text), иначе PHP будет не в состоянии прочесть и запустить ваш скрипт.
Замечание: Пара слов о Блокноте Windows
При написании скриптов PHP с использованием встроенного Блокнота Windows необходимо сохранять файлы с расширением .php. (Блокнот автоматически добавит расширение .txt, если вы не предпримете указанные ниже меры.) Когда во время сохранения файла вас попросят указать его имя, введите имя файла в двойных кавычках (например, "hello.php"). Кроме этого, можно кликнуть на выпадающее меню "Текстовые документы" в диалоговом окне сохранения файла и выбрать в нем пункт "Все файлы". После этого можно вводить имя файла без кавычек.
Теперь, когда вы успешно создали работающий PHP-скрипт, самое время создать самый знаменитый PHP-скрипт! Вызовите функцию phpinfo() и вы увидите множество полезной информации о вашей системе и настройке, такой как доступные предопределенные переменные, загруженные PHP-модули и параметры настройки. Уделите некоторое время изучению этой важной информации.
Пример #2 Получение информации о системе из PHP
<?php phpinfo(); ?>
save your php script without the BOM when using UTF-8 or you will see "锘" in front of any output. A solution is save it without BOM(available in editplus and notepad++)
If you save your code as UTF-8, make sure that the BOM (EF BB BF) is not present as the first 3 bytes of the file otherwise it may interfere with the code if the PHP need to be run before any output (e.g. header()).
Well, but PHP file ownership is important when server has safe_mode enabled - HTTP server checks it, uses it to set UID of process which executes it, or may even refuse to execute such a file - e.g. if one user is owner of main PHP file, and the main file includes another, owned by other user, this is considered to be security violation (quite reasonably).
On Windows, if file extensions can be hidden, you may not SEE that you have accidently saved a file as 'Text Documents' (and that the browser has added '.txt' to the end of your 'page.html', resulting in 'page.html.txt'.) You still see only 'page.html' even though it's really 'page.html.txt'. Also, if you try to rename it, it won't work because it's not overwriting the '.txt' part and not changing the filetype.
By the way, the hiding of file extensions is ALSO a way malicious crackers get you to click on an executable virus, fooling you into thinking it's an innocent document. You should always be able to view the extensions of all files on your system.
To view all extensions, open Windows Explorer. Click the 'Tools' menu, then 'Folder Options'. In the dialog box that appears, click the 'View' tab. In the 'Advanced Settings Box', scroll down to 'Hide extensions for known file types' and click the checkbox next to it to REMOVE THE CHECKMARK. Click the 'Apply to All Folders' button near the top of the dialog. This may or may not take a few minutes. Then click the 'OK' button to close the dialog.
Now, if something accidentally gets saved as the wrong filetype, resulting in another file extension automatically appended to the one you typed, you will see it and be able to rename it.
Of course, a badly-named file can be renamed simply by using 'Save As' and saving it as the proper filetype, but if you can't see the file extension, you may not know that is the problem. Also, renaming is easier than opening, resaving as a new filetype, and then deleting the old version!
document_root variable is located in your web server configuration file
OS X users editing in TextEdit will need to make sure their TextEdit preferences are set to allow plain text files. Under the TextEdit pull-down menu, choose PREFERENCES, then under NEW DOCUMENT ATTRIBUTES in the window that pops up, click PLAIN TEXT.
Then, in the section of that same window called "saving," DESELECT "append .txt extension to plain text files." This will allow you to save your files with a .php extension.
Then close the PREFERENCES window. You're good to go.
Expansion on saving w/ notepad/wordpad: (tested on XP; but should work on 2000,NT, and 98)
You can associate the .php file extension w/ Windows w/o going into the registry.
Open up My Computer or MSIE in file mode. Go to folder options > File types tab. Now click new. Add the extension as PHP or php. If you can't find the PHP application in the dropdown list under advanced, just go OK, for now. At least the extension is in place.
Now, try and create a php file by using the directions from this page of the PHP tutorial (should save it with the rest of your HTML files, i.e. your DocumentRoot). If you go to view your php file listed in the directory, and you see that it's still a .txt file, right-click the icon to see if you can locate "open with." If so, you should be able to browse for the appropriate file, which should be at (may vary, depending on where you installed PHP):
C:\PHP\php.exe
Click that as the default program, and the PHP logo should appear on all your scripts, and no problems saving should occur w/ any program.
Good luck.
Note on permissions of php files: You don't have to use 'chmod 0755' under UNIX or Linux; the permissions need not be set to executable. Again, this is more like a html file than a cgi script. The only mandatory requirement is that the web server process has read access to the php file(s). With many Linux systems, it is popular for Apache to run under the 'apache' account. Given that HTML and other web files, like php, are often owned by user 'root' and group 'web' (or another similar group name), acceptable permissions might be those achieved with 'chmod 664' or 'chmod 644'. The web server process, running under the 'apache' account, will inherit read only permissions. The 'apache' account is not root and is not a member of the 'web' group, so the "other" portion of the permissions (the last "4") applies.
