My Second PHP Example

Как написать PHP скрипт

В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.

Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.

Количество просмотров этой статьи: 35 565.

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

Первые шаги с оператором Echo

Изображение с названием Write PHP Scripts Step 1

  • Для запуска «Блокнота» на любой версии Windows можно использовать сочетание клавиш ⊞ Win + R > Notepad.
  • Запустить TextEdit на Mac OS можно через меню «Программы» > TextEdit.

Изображение с названием Write PHP Scripts Step 2

Изображение с названием Write PHP Scripts Step 3

  • В «Блокноте», добавьте расширение .php к названию файла и заключите в кавычки. Таким образом, «Блокнот» уже не будет считать файл текстовым и не станет преобразовывать его в текстовый формат. Если не добавить кавычки, то имя файла автоматически станет следующим: hello world.php.txt. В качестве альтернативного варианта отключения автоматического добавления расширения .txt при сохранении в меню «Тип файла» можно выбрать значение “Все файлы (*.*)». В этом случае имя файла останется таким, каким вы его введете, и вам уже не нужно будет добавлять кавычки.
  • В программе TextEdit не нужно добавлять кавычки в название файла при его сохранении. Вместо этого появится всплывающее окно с запросом на подтверждение того, что вы хотите сохранить файл с расширением .php.
  • Убедитесь в том, что сохраняете файл в корневом каталоге документов вашего сервера. Обычно внутри папки сервера Apache на Windows этот каталог называется “htdocs”. Для Mac каталог по умолчанию расположен в /Library/Webserver/Documents, однако путь может быть скорректирован при настройке сервера.
Читайте также:  Margin element in html

Изображение с названием Write PHP Scripts Step 4

  • Если возникнет сообщение об ошибке, проверьте, что код в файле введен в точности как в примере. Убедитесь в том, что не забыли добавить точку с запятой в конце команды.
  • Также необходимо проверить, что файл сохранен в правильном каталоге.

Источник

Writing Your First PHP Script

In What is PHP? you took an overall look at the PHP programming language, and what you can use it for. In this tutorial, you get to play with PHP and create your very first PHP script. Along the way you’ll learn some important basic concepts of PHP.

What you’ll need

In order to start writing PHP scripts, you need access to a Web server running PHP. Your main options are:

  • Run PHP on your own computer: The easiest way to do this is to install a complete package like XAMPP. This contains the Apache Web server, along with PHP and the MySQL database engine, in one easy-to-install package. XAMPP is available for Windows, Mac OS X, and Linux. (A popular alternative on Windows is WampServer.)
  • Run your PHP scripts on your Web host: If you already have a Web hosting account that supports PHP then you can upload your PHP scripts via FTP and run them on the Web server. The advantage of this approach is that you don’t have to install anything; the disadvantage is that it’s slower to write and test your scripts.

Your first script

Here’s the PHP script that you’re going to create:

As you can see, most of this script is plain XHTML. The PHP code is inside the tags:

The tags tell the Web server to treat everything inside the tags as PHP code to run. (Everything outside these tags is sent straight to the browser as-is.)

This line of code is very simple. It uses a built-in function, echo , to display some text (“Hello, world!”) in the Web page. PHP contains hundreds of functions that you can use to write feature-rich applications.

Notice the semicolon ( ; ) after the PHP code — you need to put a semicolon after each line of code in your PHP scripts.

The semicolon is optional if you’re only writing one line of code, as in this example.

Creating the script

To create your script, you’ll need to use a text editor program. Most computers come with one or more text editors built in — for example:

Copy and paste the script code listed above into a new document in your text editor, then save the file as hello.php in the document root folder — that is, the top level of your website — on your hard drive. If you’re not sure where your document root folder is then consult your Web server manual. Common locations include:

  • XAMPP on Windows: C:/Program Files/xampp/htdocs/
  • XAMPP on Linux: /opt/lampp/htdocs/
  • XAMPP on Mac OS X: /Applications/XAMPP/htdocs/

If you want to run the script on your Web hosting account rather than your own computer then you’ll need to upload the script using FTP instead.

Find out more about the document root, as well as uploading files, in Getting started with your Web hosting service.

Testing the script

Now you’re ready to run your script. To do this, open a Web browser, type the script’s URL into the browser’s address bar, and press Enter . If you’re running the Web server on your own computer then the URL will probably be:

If, on the other hand, you’re running the script on a Web hosting account then you need to use something like:

If all goes well then you should see a page similar to this:

Running your first PHP script

Problems?

If you get an error message or nothing happens, check that your Web server is set up properly (see the Web server’s documentation for help) and that you entered the script code correctly.

If you see the script code displayed in the browser, rather than the expected Web page, or your browser offers to download the script file, then your Web server has not been configured to run PHP scripts.

If you’re still stuck then check out the many PHP support options available.

What next?

If you saw the correct Web page then congratulations — you’ve successfully written, saved, and run your first PHP script! You’ll build on these skills in future tutorials as you learn how to write more complex PHP scripts and applications.

You might also like to browse the PHP language reference to get some ideas for other PHP scripts to write.

Reader Interactions

Comments

Источник

Creating a Simple PHP Script

In the previous chapter we looked at how PHP works. No technology book would be complete without including the obligatory simple example, and PHP Essentials is no exception to this rule.

In this chapter we will look at constructing the most basic of PHP examples, and in so doing we will take two approaches to creating PHP powered web content. Firstly we will look at embedding PHP into an HTML page. Secondly, we will look at a reverse example whereby we embed the HTML into the PHP. Both are perfectly valid approaches to using PHP.

Contents

The PHP Code Delimiters

The first thing to understand is the need to use PHP code delimiters to mark the areas of PHP code within the web page. By default, the opening delimiter is and the closing delimiter is ?>. You can insert as many or as few blocks of PHP into a web page as you need as long as each block is marked by the opening and closing delimiters.

A sample PHP script block would, therefore, appear in an HTML file as follows:

Testing the PHP Installation

Before embarking on even the simplest of examples, the first step on the road to learning PHP is to verify that the PHP module is functioning on your web server. To achieve this, we will create a small PHP script and upload it to the web server. To do this start up your favorite editor and enter the following PHP code into it:

This PHP script calls the built-in PHP phpInfo() function, the purpose of which to output information about the PHP pre-processing module integrated into your web server.

Save this file as phpInfo.php and upload it to a location on your web server where it will be accessible via a web browser. Once you have done this open a browser and go to the URL for this file. If all is well with your PHP installation you will see several pages of detailed information about your PHP environment covering topics such as how and when the PHP module was built, the version of the module and numerous configuration settings.

If you do not see this information it is possible you do not have the PHP module integrated into your web server. If you use a web hosting company, check with them to see if your particular hosting package includes PHP support (sometimes PHP support is only provided with premium hosting packages so you may need to upgrade). If you run your own web server consult the documentation for your particular type of server (Apache, Microsoft IIS etc) for details on integrating the PHP module. There are vastly superior resources available on the internet to assist in installing PHP than we could never match in this book.

A healthy PHP installation should result in output similar to the following:

Phpinfo output.jpg

Embedding PHP into an HTML File

As you may have realized, by testing the PHP module on your web server you have already crafted your first PHP script. We will now go on to create another script that is embedded into an HTML page. Open your editor and create the following HTML file:

  My First PHP Script'; ?> This content was generated by PHP

'; ?>

And this content is static HTML

Save this file as example.php and upload it to your web server. When you load this page into your browser you should see something like the following:

Php simple example.jpg

If you see something like the above in your browser then you have successfully created and executed your first embedded HTML script.

If you do not see the expected output in your browser window then go back and check your file. Something as simple as a missing character can result in no content being generated by the PHP module. As you will learn with experience, problems are almost always the result of subtle mistakes in entering the PHP code.

Embedding HTML into a PHP Script

In the previous example we embedded some PHP scripts into an HTML web page. We can reverse this by putting the HTML tags into the PHP commands. The following example contains a PHP script which is designed to output the HTML necessary to display a simple page. As with the previous examples, create this file, upload it to your web server and load it into a web browser:

\n"; echo "\n"; echo "\n"; echo "\n"; echo "\n"; echo "

Some Content

\n"; echo "\n"; echo "\n"; ?>

When you load this into your browser it will be as if all that was in the file was HTML, and if you use the view page source feature of your browser the HTML is, infact, all you will see. This is because the PHP pre-processor simply created the HTML it was told to create when it executed the script:

    

Some Content

Summary

In this chapter we have looked at how to test that the PHP module is installed into the web server and functioning correctly. We then went on to look at how to add PHP scripts to a web page. In the next chapter we will look at the all important, but all too frequently neglected, topic of adding comments to PHP code.

Источник

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