How to learn html and php

How to Learn PHP

Monty Shokeen

Monty Shokeen Last updated Oct 15, 2021

Web development is multifaceted. A properly working website requires that things work with proper coordination on both the front-end (the web browser) and the back-end (the server). Creating an interactive feature on the front-end requires you to learn JavaScript. Similarly, working on the back-end requires you to learn a language like PHP or JavaScript. I’ve already written a post that provides a brief overview of what you can do with PHP.

In this tutorial, I’ll help you get started with learning the basic concepts of PHP so that you can use it to build whatever kind of web apps you want.

Getting Started

The code you write in PHP will have to go inside a PHP file. This means that you need to have a basic understanding of what a PHP file is and what it does.

The fact that you can mix PHP and HTML to quickly create a functional website makes PHP one of the most beginner-friendly ways out there to develop a website. Learn how to use HTML within PHP.

Reading the above posts should help you get a rough idea of where and how you can write your own PHP code. Let’s dive into the basics now.

PHP and Numbers

Many web development projects will require you to do at least some kind of mathematical computation. I’ve already written a few tutorials on this topic to help you cover the basics.

  • PHP Integers, Floats and Number Strings—Read this to understand how PHP handles different kinds of numbers and the basic difference between them.
  • Trigonometry, Random Numbers and More With Built-in PHP Math Functions—PHP also comes with a lot of built-in functions that can help you generate random numbers or calculate the values of trigonometric angles. This tutorial also shows you how to apply this knowledge of trigonometric functions to create basic circular design patterns.
  • How to Use the Modulo Operator in PHP—This tutorial will show you some practical applications of the modulo operator when dealing with numbers in PHP.

Arrays in PHP

Arrays are useful for a lot of things. You usually use them to store elements of the same kind together under one name. However, they can store almost anything you want. Arrays in PHP can be very simple with numerical indices or multi-dimensional and associative with non-numeric keys.

Here’s a curated list of tutorials to help you learn the basics of arrays in PHP and how you can use a variety of PHP functions to work more efficiently with arrays.

  • Understanding Arrays in PHP—Read this post to learn about different types of arrays and common array functions in PHP.
  • Working with PHP Arrays in the Right Way—This tutorial will teach you about a bunch of functions and tricks that you can use to write more succinct code when dealing with PHP arrays.
  • How to Sort Arrays in PHP—It is almost inevitable that you will have to sort your data in some way when working with arrays. This tutorial will teach you different ways of doing exactly that. You will learn how to sort arrays by values or keys. It also explains how to sort multi-dimensional arrays or sort with user-defined functions.
  • Get the First and Last Elements of an Array in PHP—You will frequently need to access items at either the beginning or the end of an array in PHP. This tutorial will teach you how to access them without needing to know their keys.

Strings in PHP

You’re probably already familiar with strings if you have done programming in other languages. PHP comes with a huge set of built-in functions that can help you accomplish a lot of common tasks very easily.

Here are a bunch of tutorials that explain how to do different tasks using these string functions in PHP.

  • How to Join Strings in PHP—This is a quick tip post to show you how to prepend, append, or join the text somewhere in the middle of a string in PHP.
  • How to Trim Strings in PHP—Different strings that you deal with will probably have some unwanted text that you want to remove. This post will show you how to do that in different scenarios.
  • How to Replace Strings in PHP—This tutorial will teach you how to replace a substring with some other text using a variety of options.
  • Generate Random Alphanumeric Strings in PHP—Read this tutorial if you are curious about generating random alphanumeric strings for usernames and passwords using built-in functions in PHP.

Learn More Basics

We can move on to some other miscellaneous topics now that you know how to handle numbers, arrays, and strings in PHP. Here are a bunch of tutorials that cover a wide range of topics.

  • The isset() , empty() and is_null() Functions in PHP—You will have to deal with a fair share of variables which are unexpectedly either not set or empty. This post will help you understand how to differentiate between them and proceed accordingly.
  • Using the PHP Switch Statement—Read this post to learn how you can use the switch statement as a replacement for complicated if — elseif — else statements.
  • Crash Course in the PHP Ternary Operator—This tutorial will help you write shorter code to replace a simple if — else statement.
  • Understanding PHP Constructors—Consider reading this beginner-friendly tutorial about constructors if you are looking into starting your OOP journey with PHP.

Some «How To» Tutorials

There are a lot of other topics that you could learn about to get a better understanding of how to do things in PHP. This section contains a small list of such posts which don’t fall inside a specific category.

  • How to Compare Dates in PHP—Follow this tutorial to learn how you can compare and find the difference between two given dates in PHP.
  • How to Work With Cookies in PHP—It is important that you have a basic understanding of handling cookies in PHP when creating websites. This tutorial will help you get a quick head start.
  • How to Use Sessions and Session Variables in PHP—Read this tutorial if you want to learn about sessions in PHP. It also briefly discusses the difference between sessions and cookies.
  • How to Parse JSON in PHP—JSON is a popular format for passing around information. This tutorial will teach you how to read JSON from a file in PHP and how to create your own JSON.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.

Final Thoughts

Learning is a continuous process. In this article, my aim was to help you get started by listing different tutorials that cover a variety of related topics. Reading them should help you gain a basic understanding of the PHP language. However, there are always more topics to learn and explore. Search Envato Tuts+ for much more about learning PHP!

Hopefully, all these tutorials will help you learn how to create something practical by writing your own PHP code.

Источник

How to learn html and php

1. Синтаксис

Код в PHP заключается в открывающий теги. Согласно стандарту кодирования PSR-12, закрывающий тег должен быть опущен в файлах, содержащих только код PHP . В конце строки ставят разделитель строк – точку с запятой ; . Если забыть поставить разделитель, то следующая строка кода соединится с предыдущей и интерпретатор PHP выдаст ошибку.

Выведем на экран строку Hello World (заключена в кавычки) с помощью команды echo :

Рис. 2. Условный оператор if в PHP

Оператор if выполняет код, если выполняется условие. В противном случае выполняется код после else, который переводится, как «иначе», «в другом случае».

Рис. 3. Цикл while в PHP

Оператор while выполняет код до тех пор, пока значение условия не станет ложным.

Рис. 4. Цикл for в PHP

Когда нам известно количество итераций, вместо цикла while лучше использовать цикл for .

Рис. 5. Индексы элементов в массиве PHP

Массивы – упорядоченная коллекция элементов с доступом по индексу или ключу. Индексный массив создается двумя способами:

Рис. 6. Запуск встроенного в PHP веб-сервера

Если мы получили ошибку 404, значит сервер запущен.

XAMPP

Скачаем и установим XAMPP . В папке C:\xampp\htdocs\ создадим папку нашей странички page . Запустим веб-сервер Apache, кликнув по кнопке Start . Узнаем версию PHP, введя в консоли (Shell) команду php -v .

Рис. 7. Запуск сервера с помощью XAMPP

Проверим, запущен ли сервер, перейдя по адресу http://localhost/ . Если появилось приветственное сообщение, значит сервер запущен.

Рис. 8. Запуск сервера с помощью XAMPP на Windows

14. Собираем страничку

Теперь создадим несколько PHP-файлов, из которых соберем страничку. Перейдем в папку page и создадим четыре файла: index.php , header.php , body.php , footer.php .

Структура простого HTML-документа выглядит следующим образом:

Рис. 9. HTML-страница, собранная из php-файлов

Литература

  • Робин Никсон. Создаем динамические веб-сайты с помощью 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.

Источник

Читайте также:  What is context xml in java
Оцените статью