- PHP Tutorial: Get started with PHP from scratch
- Start your PHP career for free
- What is PHP?
- Why should you learn PHP?
- What is PHP used for?
- Advantages of PHP
- Your first PHP-enabled page
- PHP Syntax
- Basic PHP Syntax
- Example
- My first PHP page
- PHP Case Sensitivity
- Example
- Example
- PHP Exercises
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Simple coding in php
- 1. Синтаксис
- XAMPP
- 14. Собираем страничку
- Литература
- Шпаргалки
- YouTube-каналы и курсы
- PHP в «Библиотеке Программиста»
- Итог
PHP Tutorial: Get started with PHP from scratch
PHP is the ideal language for new developers. It is simple, fast, and intuitive. It is also very similar to other programming languages, like C, so you can pick other languages up faster with PHP knowledge.
Today we’ll get you started with PHP from the very beginning, breaking down what PHP is, why you should learn it, and some of its unique advantages. Then we’ll walk you through your first PHP “Hello World” program. Finally, we’ll cover the core PHP syntax and work through exercises.
By the end, you’ll have a solid foundation of basic PHP concepts and will be able to advance to intermediate topics. No prior knowledge of PHP is required, but to be successful in this tutorial, some general knowledge of programming will help you get the most from our exercises. For a quick introduction, , check out The Absolute Beginner’s Guide to Programming.
Here’s what we’ll cover today:
Start your PHP career for free
Learn all the basics of PHP with developer-made lessons, tutorials, and quizzes, all free of charge.
What is PHP?
PHP is a recursive acronym for PHP: Hypertext Preprocessor. It is a popular, open source scripting language that is similar to C and especially suited for web development. PHP can be directly embedded into HTML using the instructions. These simple code instructions allow you to jump between HTML and PHP code without the need for extra commands used with C or Perl.
Another unique factor of PHP is that its code is executed on the server rather than client-side, or the side of the internet that a user sees. Once executed, PHP code generates HTML, which is then sent client-side. This makes PHP very secure and ensures that users cannot see what’s going on behind the screen.
Why should you learn PHP?
PHP is a great starting point for any new developer. PHP’s simplicity means it’s easier to pick up than other languages. Even if you don’t want to work in web development, the syntax and object-oriented thinking skills of PHP can give you a significant advantage when learning other OOP languages like Java or C++.
PHP also comes with a massive community. In fact, Github reports that PHP is the 5th most popular language in the world, PHP has the 3rd largest community on StackOverflow. This large community ensures you’ll never be without help if you get stuck.
Finally, PHP is a widely sought skill in the modern digital economy, and demand is growing. Popular sites like Facebook, Wikipedia, Yahoo, and Flickr are all built on PHP. In fact, data collected by Codementor found that PHP is used for 80% of the world’s top 10 million websites and about 40% of all sites on the internet!
PHP has also gained popularity as the go-to for small businesses. This is because intuitive content management systems like WordPress and Wix are written in PHP. A lot of PHP web developers are freelance workers who help launch new websites for businesses. The need for PHP developers is increasing.
What is PHP used for?
PHP is most often used in server-side web development. Thanks to server-side execution, PHP is great for dynamic web pages, a type of site which updates periodically or reacts to certain events. PHP’s secure function-hiding abilities also make it ideal for working with sensitive financial or personal information.
Online stores are a place we can see both of these strengths come into play. For example, PHP is used in the “shopping cart” functions of many sites. This is because PHP only sends the outcome of adding the item or completed transaction without giving access to the function.
Beyond this, PHP is also used in command-side scripting and graphical user interface design (GUI). PHP shows its value as a widely available and generalized language capable of running on nearly any operating system or database.
Advantages of PHP
- Quick and Easy to Learn: PHP is beginner friendly and can be learned quickly relative to other languages. It’s also often considered a great first language.
- Large Community: PHP has a large user base and online support community.
- Widely Applicable: PHP can be used on any operating system or database.
- Open Source: PHP is free to adopt and download along with all of its tools. This also means that the language is highly receptive to community feedback.
- Great Performance: PHP uses its own memory space rather than an overhead server.
Your first PHP-enabled page
Create a file named hello.php and put it in your web server’s root directory ( DOCUMENT_ROOT ) with the following content:
Example #1 Our first PHP script: hello.php
Use your browser to access the file with your web server’s URL, ending with the /hello.php file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server’s configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:
This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the «.php» extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.
The point of the example is to show the special PHP tag format. In this example we used . You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.
Note: A Note on Line Feeds
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren’t supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.
Note: A Note on Text Editors
There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
Note: A Note on Word Processors
Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.
Example #2 Get system information from PHP
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
The default file extension for PHP files is » .php «.
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function » echo » to output the text «Hello World!» on a web page:
Example
My first PHP page
Note: PHP statements end with a semicolon ( ; ).
PHP Case Sensitivity
In PHP, keywords (e.g. if , else , while , echo , etc.), classes, functions, and user-defined functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
Example
Note: However; all variable names are case-sensitive!
Look at the example below; only the first statement will display the value of the $color variable! This is because $color , $COLOR , and $coLOR are treated as three different variables:
Example
$color = «red»;
echo «My car is » . $color . «
«;
echo «My house is » . $COLOR . «
«;
echo «My boat is » . $coLOR . «
«;
?>
PHP Exercises
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:
Thank You For Helping Us!
Your message has been sent to W3Schools.
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.
Simple coding in php
1. Синтаксис
Код в PHP заключается в открывающий теги. Согласно стандарту кодирования PSR-12, закрывающий тег должен быть опущен в файлах, содержащих только код PHP . В конце строки ставят разделитель строк – точку с запятой ; . Если забыть поставить разделитель, то следующая строка кода соединится с предыдущей и интерпретатор PHP выдаст ошибку.
Выведем на экран строку Hello World (заключена в кавычки) с помощью команды echo :
Оператор if выполняет код, если выполняется условие. В противном случае выполняется код после else, который переводится, как «иначе», «в другом случае».
Оператор while выполняет код до тех пор, пока значение условия не станет ложным.
Когда нам известно количество итераций, вместо цикла while лучше использовать цикл for .
Массивы – упорядоченная коллекция элементов с доступом по индексу или ключу. Индексный массив создается двумя способами:
Если мы получили ошибку 404, значит сервер запущен.
XAMPP
Скачаем и установим XAMPP . В папке C:\xampp\htdocs\ создадим папку нашей странички page . Запустим веб-сервер Apache, кликнув по кнопке Start . Узнаем версию PHP, введя в консоли (Shell) команду php -v .
Проверим, запущен ли сервер, перейдя по адресу http://localhost/ . Если появилось приветственное сообщение, значит сервер запущен.
14. Собираем страничку
Теперь создадим несколько PHP-файлов, из которых соберем страничку. Перейдем в папку page и создадим четыре файла: index.php , header.php , body.php , footer.php .
Структура простого HTML-документа выглядит следующим образом:
Литература
- Робин Никсон. Создаем динамические веб-сайты с помощью PHP, MySQL, JavaScript, CSS и HTML5;
- Котеров, Симдянов. PHP 7;
- Веллинг, Томсон. Разработка веб-приложений с помощью PHP и MySQL;
Шпаргалки
YouTube-каналы и курсы
Бесплатные курсы на русском языке:
- Основы php с нуля. Новейший курс 2020 – двадцать четыре урока от основ до регулярных выражений и функций;
- Базовый курс по PHP 7 – узнаете про базовые понятия, GET-параметры, методы, функции и ООП;
- Учим PHP за 1 Час – основы за полтора часа;
- Изучение PHP для начинающих – научитесь работать с массивами, подключать файлы, обрабатывать формы, работать с куки и базой данных MySQL;
- Уроки PHP 7 – много уроков по ООП;
- PHP для начинающих – курс на Stepik для начинающих разработчиков, не требует специальных знаний;
- PHP – первое знакомство – азы программирования на PHP (Stepik).
PHP в «Библиотеке Программиста»
- подписывайтесь на тег PHP , чтобы получать уведомления о новых статьях;
- телеграм-канал «Библиотека пхпшника»;
- книги по программированию в нашем телеграм-канале «Книги для программистов».
Итог
- вы познакомились с синтаксисом PHP и типами данных;
- узнали, как работают условные операторы и циклы;
- запустили веб-сервер в Ubuntu и Windows;
- собрали страничку HTML из файлов PHP.