PHP Introduction
Before you continue you should have a basic understanding of the following:
If you want to study these subjects first, find the tutorials on our Home page.
What is PHP?
- PHP is an acronym for «PHP: Hypertext Preprocessor»
- PHP is a widely-used, open source scripting language
- PHP scripts are executed on the server
- PHP is free to download and use
PHP is an amazing and popular language!
It is powerful enough to be at the core of the biggest blogging system on the web (WordPress)!
It is deep enough to run large social networks!
It is also easy enough to be a beginner’s first server side language!
What is a PHP File?
- PHP files can contain text, HTML, CSS, JavaScript, and PHP code
- PHP code is executed on the server, and the result is returned to the browser as plain HTML
- PHP files have extension » .php «
What Can PHP Do?
- PHP can generate dynamic page content
- PHP can create, open, read, write, delete, and close files on the server
- PHP can collect form data
- PHP can send and receive cookies
- PHP can add, delete, modify data in your database
- PHP can be used to control user-access
- PHP can encrypt data
With PHP you are not limited to output HTML. You can output images or PDF files. You can also output any text, such as XHTML and XML.
Why PHP?
- PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
- PHP is compatible with almost all servers used today (Apache, IIS, etc.)
- PHP supports a wide range of databases
- PHP is free. Download it from the official PHP resource: www.php.net
- PHP is easy to learn and runs efficiently on the server side
What’s new in PHP 7
- PHP 7 is much faster than the previous popular stable release (PHP 5.6)
- PHP 7 has improved Error Handling
- PHP 7 supports stricter Type Declarations for function arguments
- PHP 7 supports new operators (like the spaceship operator: )
Learn about php programming
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.
PHP Tutorial
This PHP tutorial, whether you’re a beginner or a professional, our tutorial is designed to provide you with in-depth knowledge of the PHP scripting language.
With our PHP tutorial, you’ll learn all the important topics, including control statements, functions, arrays, strings, file handling, form handling, regular expressions, date and time manipulation, object-oriented programming in PHP, mathematical operations, working with PHP and MySQL, integrating PHP with Ajax, harnessing the power of PHP with jQuery, and more.
What is PHP?
The term PHP is an acronym for Hypertext Preprocessor . It is an open-source, interpreted, object-oriented server-side scripting language that is used for web development. PHP is developed by the Rasmus Lerdorf in 1994 with the very first version of PHP that simply designed to set the Common Gateway Interface (CGI) binaries, which are written in C programming language. The latest version of PHP is PHP versions 8 which is released on November 24, 2022. It can be easily embedded with HTML files. HTML codes can also be written in a PHP file. The PHP codes are executed on the server-side whereas HTML codes are directly executed on the browser.
Example: Simple program to print “Hello world!” message on the screen.