Php programming language tutorial for beginners. Personal experience as proof: the PHP programming language is the main one on the Internet. Bootstrap framework: fast adaptive layout

Bootstrap framework: fast adaptive layout

Step-by-step video course on the basics adaptive layout in the Bootstrap framework.

Learn how to typesetting simply, quickly and efficiently using a powerful and practical tool.

Layout to order and get paid.

Free course "Site on WordPress"

Do you want to master CMS WordPress?

Get lessons on website design and layout on WordPress.

Learn to work with themes and cut layouts.

Free video course on drawing a website design, layout and installation on CMS WordPress!

*Mouse over to pause scrolling.

Back forward

PHP Fundamentals: An Overview for Beginners

PHP has been consistently on the list of the most popular programming and web development languages ​​for many years. Of course, there are other languages, but the ubiquity of websites based on WordPress engine in many ways served as an additional impetus for an even greater increase in popularity of this language.

What is PHP?

PHP stands for Hypertext PreProcessor(something like an "HTML preprocessor").

What does this mean? Let's start a little from afar: there are two types of languages. One type is called "client", and the other - "server".

It means that client languages ​​work in each individual's browser. A typical representative of client languages ​​is JavaScript, which you have probably heard about and the results of which you have seen more than once.

If you want to learn more about JavaScript, then check out the material.

All actions and commands that we give, say, to JavaScript, are executed by the browser, which means that the same code written by us is processed in one case Internet browser Explorer, in another - Firefox, in the third - Opera, in the fourth - Google Chrome, i.e. the browser that everyone uses special person to view our page.

The browser thus has alternative name - client.

In case of server-side languages(to which PHP belongs) we see a different picture.

Our website is always located on some server, i.e. powerful computer, specifically designed to host many people's websites.

All commands and scripts written in PHP language, are executed on the server, and nothing else. After the PHP script is executed on the server, the server “gives” the result of its work, which we see in the browser.

It is important to understand the following point: by the source code of the web page, which can be viewed in any browser through an option like "Page source code" it is impossible to determine whether PHP was used to create a given page or not.

It is impossible to do this precisely because PHP scripts are processed on the server, and a ready-made, processed version is transferred to the browser. Basically just HTML code.

The difference compared to regular static HTML pages is one additional stage code processing.

In the case of an HTML page, there is only one step: The browser processes the HTML code, i.e. page layout in accordance with certain rules, as a result of which we see the web page in its normal form.

In the case of a PHP page, there are two steps: first the so-called PHP interpreter(handler) executes the PHP code (as a result, a simple HTML code is obtained), and after that the browser processes the result of this processing, i.e., in fact, the very stage that is unique in the case of HTML is executed. page.

In general, PHP works great when paired with HTML. Moreover, in HTML code you can do PHP inserts-code, and with using PHP output HTML markup. It's important to remember this simple point: It doesn't matter how complex your PHP code is, it will eventually end up as plain HTML.

Why use PHP?

HTML is 100% static. By embedding PHP code into our pages, we can ensure that the content of the same page was different depending on certain conditions (dynamic pages). Over the many years of its existence, the PHP language has established itself as an excellent solution for creating dynamic websites.

Is PHP similar to other languages?

Yes. PHP is similar to ASP.NET, Perl, JavaScript, C#. You may not know any of them right now, but learning PHP will allow you to master other languages ​​with greater confidence in the future.

What do you need to get started?

For full-fledged work with PHP on your computer you need the following things:

1. Apache web server(it is used in most cases);
2. Database Management System (DBMS) MySQL (the content of the site is stored in the database);
3. Installed PHP interpreter;
4. Text editor, in which you will write code;
5. Browser.

Now a little more about the first three points.

1. Web server is designed to simulate on your computer the very server on which your website will then be hosted on Internet hosting. This is necessary so that you can write any PHP scripts on your computer and watch how they work, make changes and edits to them. In a word, this is necessary for so-called debugging.

2. MySQL DBMS needed to store information that will be on your website. In the case of HTML pages, all the content of the site is located directly in them. Each page contains a certain amount of information (content).

At using PHP For the purpose of storing useful information content of a site, a database is usually used. In the vast majority of cases this is MySQL.

3. PHP interpreter is a kind of program that processes PHP code on a web server. Without it, we will not be able to execute our PHP scripts and see the result of their work.

How to install all these components on your computer?

Exists good decision, which greatly simplifies this process and does not require you to have any knowledge in setting up a web server, MySQL and PHP interpreter.

This special set Denwer, which already includes all three components. It installs on your computer as regular program and is ready to work without preliminary settings.

Denwer is ideal solution in the vast majority of cases, and for beginners it will be a lifesaver, as it allows you to start developing websites in PHP without having to learn a bunch additional information on setting up a web server, MySQL DBMS and PHP interpreter.

Basics

In order to tell the server to process PHP code, you must use the following syntax when adding PHP to an HTML document:

Opening a block of PHP code is indicated as ", and closing - "?>" . Now let's change our code as follows:

Please note that in in this example we wrote everything in one line. Spaces and line breaks do not play a role here and will not affect the final result.

In the example we give the server the command echo(command for displaying information on the screen) and indicate that we want to display the phrase This is PHP in action. Each command in PHP is separated from the previous one by a semicolon at the end of that command.

PHP is more strict about strict adherence to syntax and will not forgive you for the absence of a semicolon, brackets, quotes, etc., as might be the case with HTML. PHP in this case will display a message about syntax error, which needs to be corrected and will indicate the line where this error was made.

By the way, in in this case we might not have used a semicolon at the end of the command, since it is the only one we have in this case (command). However, it is always better to stick good practices when working with code.

Declaring Variables

Variable in PHP- this is a kind of container that can contain certain information. In order to create such a “container”, we need to name it and indicate what should “lie” in it. This is done using a sign "$" , which means we are dealing with a variable. Let's put it in a variable named test phrase This is PHP in action.

The result of processing this code will be exactly the same as in the previous example. The phrase will simply be displayed on the screen This is PHP in action. However, before this we directly output this phrase, but now we have added this phrase to a variable test, after which they gave the command to display the value of the variable on the screen test.

How can we add some more text or other information to display on the screen?

Let's look at this with the following example:

As you can see, after outputting the variable test there is a space, then a period, then a space again. After this, quotes open, first there is one space, and then a sentence My name is Dmitry Naumenko., followed by closing quotes.

Let's go through the steps and see what is needed here and why.

After outputting the variable test we seem to be “adding” to an already existing output additional text. This is done using the dot symbol (.) .

The dot symbol means addition in PHP, but not addition of numbers, but addition precisely text information, like the one we work with. After the period, we indicate in quotation marks what exactly we want to add to the conclusion, and write a new sentence.

Note that there is a space after the opening quotes. When displayed on the screen, it will be saved, so our phrases will not merge. Those. we will get you output:
This is PHP in action. My name is Dmitry Naumenko.

If you remove that space, you get:
This is PHP in action. My name is Dmitry Naumenko.

I would also like to draw your attention to the spaces on both sides of the addition point. These spaces do not play any role and are used only for clarity and ease of perception. The following code will give us exactly the same result:

Therefore, write in the way that is most convenient for you in this case.

Inserting comments in code

First question - "What are they even for?"

Comments are needed so that you can make notes, notes, explanations, etc. in your or someone else’s code. while working with the code. Now it seems to you that everything is clear and obvious. As long as you remember perfectly well why this variable is needed and what that function does.

Not much time will pass and without comments you will hardly be able to understand even your own code, not to mention other people's scripts. Therefore, proper use of comments is an urgent need.

Typically used in PHP two types of comments:

Of course, comments only work within blocks of PHP code And ?> .

Outputting HTML using PHP

As I mentioned earlier, PHP and HTML work great together. Just because we're inside a block of PHP code doesn't mean we can't display text in a paragraph or in bold.

This is the text in bold."; ?>

As you may have guessed, the result of this code will be the output of this line in bold to the browser.

Create the first function

First of all, a few words about what a function is.

Function- this is a kind of mini-program that performs a certain useful work and gives us the result.

It makes sense to use functions in cases where you need to perform similar, template actions. In this case, we write such a mini-program, which significantly reduces the amount of code and, accordingly, our efforts.

The syntax when creating a function is as follows:

Let's say if we want to write a function that calculates the sum of the numbers 10 and 5, we can do this:

We create a function called sum and in its body we indicate that it should display the sum of the numbers 10 and 5. After this, we call the function sum. Calling a function essentially means executing it.

In this example we do not use any arguments (see function syntax above). What are arguments and what are they needed for, we will look directly at the example. Let's modify the code that we have, making it more flexible and functional:

Now when creating a function sum we indicate two arguments in parentheses, separated by commas - $slagaemoe1 And $slagaemoe2. In the body of the function, we add and display not specific numbers, but the values ​​of variables $slagaemoe1 And $slagaemoe2(i.e. these same arguments).

Now we just need to call the function, passing it two arguments in parentheses that it “expects”. We specify the numbers 10 and 5, resulting in 15. By passing the function sum other numbers, of course, we will get a different answer.

I hope that this review helped you understand what PHP is and what it is needed for, what advantages it has over static HTML, and how you can use some of its simplest features.

Dmitry Naumenko.

P.S. Do you want to move further in mastering PHP? Pay attention to premium lessons on various aspects of website building, including PHP programming, as well as free course to create your own CMS system in PHP from scratch. All this will help you master this powerful web development language faster and easier:

Did you like the material and want to thank me?
Just share with your friends and colleagues!


From the author: Is it necessary to know the PHP programming language? If you are going to throw in your lot with website building, you will have to. Even if you really don’t want to! Why is that? We will try to answer all the common “whys” associated with this language in our material.

The solution that “holds” the Internet together

This is exactly how one of my acquaintances, who has been creating Internet resources for more than a decade, described PHP. And he’s right, probably 200% percent (or maybe more).

The very history of the emergence of this language suggests that it was born to “blind” the current version of the Network to which we are so accustomed. This is probably why some people still cannot realize its power, even after learning the basics of PHP programming.

Proving the role of PHP in creating the Internet is a thankless task. Here, as they say, supporters of other server-side languages ​​can begin to speak out. They say that the “hypertext preprocessor” (as the abbreviation PHP stands for) has already outlived its usefulness. Many of its functions are implemented even in…

Well, shouting and waving your arms, extolling your programming language, which you specialize in, is a simple matter. But the best “evidence” indicating the demand for PHP is its prevalence.

Next rating program languages, compiled by TIOBE specialists last summer, tells us that PHP has been consistently among the top for several years. You haven't started searching by programming language yet PHP tutorial? You'll be running soon.

If you are wondering why Java has jumped so much, then the answer is: thanks to the Android mobile operating system, applications for which are developed in this language.

Own rake

Back in the early 2000s, I was engaged in “research” in the field of programming. I kept trying to figure out which “party” of developers I should join, which discipline I should devote my life to studying.

In principle, I did not consider PHP as a programming language for beginners. He seemed too confused. Here's the other thing about ASP.NET: a commercial language based on C#. Oh, what castles in the air I built back then! And there were all the prerequisites for this:

The technology was developed by such a “thought giant” as Microsoft.

Availability of specialized software – powerful editor Visual Studio.

Extensive and well described documentation.

Hope for a “healthy” future.

ASP.NET, unlike PHP, was much easier for me. Visual Studio automated a large number of operations for writing server scripts. For example, thanks to the excellent visual editor it only took a few minutes to create a web page. By dragging and dropping controls and styling them in the editor, you could make a website in less than an hour!

But the PHP programming language from scratch didn’t work out for me right away. Honestly, I tried to make friends with him (I had to pass the exam somehow). But when studying its basics, it seemed callous and even cold to me.

In general, I took up ASP.NET. I created my first website. Well, everything seems to be working in the development environment. Cross-browser compatibility checked in several popular browsers. I think it’s time to “fight.” So to speak, show your “brainchild” to the whole country (at least). This is where the “rakes” turned out to be.

My attempts to find hosting with ASP.NET support on the RuNet were never successful. There were, of course, several paid platforms, but the prices for hosting a website on them were clearly not “student” prices.

Somehow I dug up in Burzhunet free option hosting (by the way, sponsored by Microsoft). Well, I clicked, enjoyed the breadth of my thoughts, but things didn’t go any further. And all due to the fact that most of the sites were already made in PHP.

After you decide and understand for sure that you are ready to learn the PHP programming language, look for a tutorial for beginners “for yourself.” The main thing is that you understand what the author of the publication wants to convey to his readers. Immediately get ready to pay a good amount of money for quality literature.

But it's better to apply A complex approach- add also sensible. This will allow you to hone your skills immediately practical examples. And my advice to you is to do less copy-pasting code! I’ll explain why now.

When you type example scripts yourself, you will quickly get used to it and remember the features PHP syntax. As for literature, choose a tutorial with the basics of programming in PHP. And it is advisable that the author post the code of all the examples given on his resource on the Internet.

Also, immediately before starting training, download and install Open Server. This software package includes all the environments you need to write and test code.

Well, let me take my leave for today. Forgive (if anything) for the excessive overview of the content of the article, but this is necessary to understand the features of this language (after all, it is server-based). I wish you to quickly grasp the basics of the PHP programming language and start real coding!

I had an idea to tell you about the language PHP. The main site of the developers of this language is http://www.php.net, where you can download the language interpreter and learn almost everything about the language (for those who are not afraid of English).

I won’t tell you anything about who, when and why created this language. Does it really matter?! If you are interested, you can easily find information about this on the Internet. Let me just say that it is a simple and very powerful language for creating dynamic web pages. It was specially developed for this purpose and therefore any work with text and data in any form on PHP done easily and beautifully.

Now we won’t say anything about setting it up. Most likely you are already using ready-made hosting with installed PHP, so it has already been set up for you. The qualifications and knowledge of the server administrator are not known, because it is difficult to say how it was set up. I want to dedicate this step to exactly that. My task is to scare you terribly, so that when developing your programs you will be afraid for everything. The Internet is full of scammers, hackers, lammers and other computer entities :) Your program must be able to withstand everyone. It must cope with configuration errors made by the administrator, it must adequately handle tricky requests that a hacker tries to feed it, or erroneous requests sent by others. Simply put, you must learn to develop programs for the Internet using PHP so that they are ready for anything. This is the only way to talk about the correct operation, and most importantly, the security of your data, website and possibly even your entire business.

I will briefly try to formulate the basic requirements for a good program for PHP, with which there will be few problems.

The first is embedding the program in code HTML pages. I think it's no secret to you that PHP file is regular file HTML with special inserts code in a language very strongly reminiscent in syntax C/C++ And Perl. So these code insertions are separated from HTML document special characters start of code and its end ?> :

HTML document

Hello world in PHP

"; ?>

Again an HTML document

Knowledgeable people will immediately ask, why is this so? After all, you can separate in short, using symbols or <% %> .

And I will answer, you are right... But you are mistaken :) And I will explain why. This code highlighting style is given by special options in the configuration file, namely options short_open_tag it is for and option asp_tags For <% %> . From initial installation"good luck" I believe that the administrator has configured your PHP little toe of my left foot, so I don't want to rely on the quality of this work. Therefore, I just say “throw it out of your head” so as not to suddenly discover that your sophisticated script is PHP doesn't work at all.

The second is code error control. If you configure the interpreter PHP so that he controls everything possible mistakes, then you will immediately protect yourself from many pitfalls. There are several options for this setting. error_reporting And display_errors. The first of them controls the “depth” of error control, and the second is the ability to display errors directly in the body of the created document. Our preference is to print all errors, no matter how configured PHP administrator. In this case, we will receive a warning about any flaw already at the development stage. In order to set your own values ​​for these parameters while the program is running, there is a function ini_set(). Let's try two versions of the program.

First option:

Second option:

The first line is to enable error output if it is disabled. The second line sets a filter for errors based on their importance. The first option uses E_ERROR for withdrawal only critical errors, and in the second E_ALL causes all messages to be displayed.

Variable $i=""

And in the second case:

Variable $i=" Notice: Undefined variable: i in /home/www.site/1.php on line 4 "

As you can see, we variable $i We haven’t defined it anywhere, but we are trying to deduce its meaning. In principle, this error is not critical, so in the first case no warnings were displayed, but the second inserted a threatening warning right between the quotes. In the case where you have a large code with hundreds of different variables, one single typo can lead to incorrect operation, and if the execution of the program goes into dangerous situations where data is deleted or modified, then the typo can be very expensive. Therefore, displaying warnings about the use of non-existent variables becomes very important when debugging code before putting it into battle.

At parameter error_reporting there is another meaning E_STRICT, which was introduced in version PHP 5 to further check the compatibility and functionality of the code at runtime. Therefore, for compatibility with other versions, we will write the following code:

")==1) ( ini_set("error_reporting", E_ALL | E_STRICT); ) else ( ini_set("error_reporting", E_ALL); ); ?>

The resulting code, depending on the version PHP, will automatically adjust to the desired level of error message output in the code. I recommend that you insert this piece into any new file, which you create, at least during the development and debugging phase.

This article will not teach you how to program in PHP, but will simply put you on the right path. I will try to talk about how to learn this language correctly (in principle, this will apply not only to PHP). I won’t talk about syntax and functions - there’s no need. There are articles that explain all this very well. I will try to give the best links to PHP textbooks and help.

First, a little theory.
PHP is scriptable server language programming, the code of which is inserted directly into the html code. Rasmus Lerdorf is considered the "father" of PHP. PHP currently stands for "PHPHypertext Processor", although it was originally "Personal Home Page". I'll bring you small example inserting php into html code:

<? print "Hello world!"; ?>

The resulting message "Hello world!" will be displayed in the window title. Everything is very simple. This, I hope, is clear. Let's move on...

As you understand, this is a completely unnecessary function, because the message "Hello world!" can be displayed without PHP. But you can do a lot more with PHP than you might imagine. Much.

In fact, even if you have never tried programming before, it will still not be difficult, at least if you studied mathematics in high school. I think so. Compared to languages ​​like Perl or Java, PHP is a fairly simple language. It was created for developing small applications, so there is nothing complicated about it. Well, if you already have some experience (for example, programming in Pascal), then it will be even easier for you.

If you want to learn how to program in PHP, just find a good textbook (or better yet, buy it if you have the means). The most important thing in this matter is a good one, and one at that. There is no need to “spray yourself”, as I did when I got acquainted with this programming language. One tutorial that you will just read for reference, a function reference that you will use when composing scripts, and, of course, forums and friends who know PHP. That's all! The most important thing in this matter is practice. Do not re-read all the articles that you come across on the Internet - you will only waste your time (although theory, of course, is needed). Just practice - that's the most important thing in this matter. If something doesn’t work out, ask on a specialized forum. I would like to recommend the PHP Developers Club: www.phpclub.ru.

Now about the documentation. If these same means do not allow you to buy a book, you will find them on the Internet: there are many of them there. Do you know English? Actually, great. The best documentation in English. But if you don’t know English, don’t despair. There is a lot of good literature in Russian.

Well, now for links to the documentation itself. The best documentation, in my opinion.
English:
www.php.net - official website.
www.php.net/manual/en - documentation for English language.

PHP (Hypertext PreProcessor) is one of the most popular server-side web programming tools. How PHP actually works simple version comes down to processing the client's http request. Processing the request, in turn, consists of programmatically generating hypertext in accordance with the request parameters, after which the resulting markup is returned to the client. When a client (Internet browser) requests a regular static Internet page (most often with html extension), the server returns the contents of this page without changes “as is” as a response. If requested php page, then during request processing the contents specified page is first processed by the PHP interpreter, and only then the result of this processing is sent to the client.

In other words, PHP is a hypertext preprocessor, as reflected in its name. Pre processor because the hypertext undergoes final processing on the client side, the result of which we see in the browser window (the hypertext processor is the browser itself). We can say that PHP is a hypertext generator, since in most cases its work is programmatic generation from the contents of a database or from any other structured information hosted on the server. The abbreviation looks like PHP, and not like, for example, HPP or otherwise, since it originally stood for Personal Home Page Tools– tools for creating personal internet pages. Thus, the first version of PHP decryption reflected its purpose, and the current one reflects the principle of operation.

PHP is a programming language, which supports almost everything: variables, conditional statements, loops, functions, etc. PHP is object-oriented programming language– it supports , as well as conventional inheritance at the class level. PHP is a web programming language because it is primarily created for developing dynamic Internet sites and therefore contains a large number of ready-made solutions used in this area, such as:

  • processing and extraction of parameters http requests GET and POST;
  • formation and sending http headers;
  • storage infrastructure session data;
  • software services for working with cookies;

    cookies- text data saved by the browser on the client’s computer, which most often contains access parameters (login and password) or personal settings user. Cookies are generated by the browser and automatically sent to the server during each remote access. http headers request.


  • working with files FTP protocol;
  • working with databases using ;
  • support
  • support HTTP authorization;
  • messaging via e-mail and much more.

In this section I plan to briefly review key points PHP applications for creating simple web applications. The materials will be organized into several sections, each of which will contain examples with their source code. For independent experiments you need or any other site to which you have access full access, and on the server of which PHP is installed.

PHP Programming Basics

Adding PHP code to markup and the result of the hypertext preprocessor

PHP code is added directly anywhere HTML markup. The HTML markup itself may not exist at all, but source page can only be represented by a fragment of a PHP program. In any case, to insert PHP you need to use a special tag and place the program text inside it. This is done as follows:

program code ?>

During the operation of the PHP interpreter sectionare replaced with markup generated as a result of the operation of the program code located in them. To display the result of the preprocessor, the operator is used echo, the arguments of which can be constants, variables, functions or various kinds of expressions, and the result is text. The simplest option might look like this:

"; ?>

If you open the source code of the resulting page in a browser, then there will no longer be any PHP there (unless, of course, a PHP interpreter is installed on the server). There's not much point in using the echo operator this way. The beauty of PHP is that the HTML generated can depend on request parameters, database contents, security policies, and much more. Analysis and processing of all this is done using familiar ones to almost everyone, such as loops, conditions, functions, etc. Looking ahead, I will give a small example of a PHP program using a loop and conditional operator, so that the initial understanding of the hypertext preprocessor becomes more complete. Next program Prints the factorial values ​​of numbers from 1 to 9.

Example program in PHP This markup is generated programmatically by the PHP interpreter."; $f=1; for ($i=1; $i<10; $i++) { if ($i>1) $f=$f*$i; echo $i,"!=",$f,"
"; } ?>

The result of its operation will look something like this in the browser:

1!=1 2!=2 3!=6 4!=24 5!=120 6!=720 7!=5040 8!=40320 9!=362880

Organizing an application from multiple PHP files

Short conditional or ternary operator

Below is general form conditional assignment operator using ternary operator:
$result = condition? expression if true: expression if false;

Example:
$result = ($a>5) ? $a+$b: $a-$b;

If a is greater than 5, then the result variable is assigned the value a+b, otherwise a-b.

Alternative to if statement with big amount elseif constructs. Execution of statements begins with the case section whose value matches the value of the expression and continues through all subsequent cases until the break command is encountered - complete execution. The default section is an alternative to the else section in a conditional statement.

Switch ( expression) (case value 1: operator 1; case value 2: operator 2; case value 3: operator 3; default: default operator; ) do loop body; while ( condition);

Same example:

$i=2; $f=1; do ( $f=$f*$i; $i++; echo $i,"!=",$f,"
"; ) while ($i<10);

More details about do...while loop read .

Looping through elements in an array or the foreach operator

A few words will be said separately about arrays, and below is a construction for iterating through its elements in a loop:

Foreach ( array as$ element) an expression where we do something with the $element variable;

$values ​​= array("for", "while", "do", "foreach"); echo "Loops in php:","
"; foreach ($values ​​as $operator) echo $operator, "
";

Loops and the selection operator in PHP, as well as in many other programming languages, support instructions break– early completion of the cycle and continue– early completion of the current iteration of the cycle (transition to the beginning of the cycle). Read more about them.