File Information in PHP

In this class you will learn file information in php basics.

How to find out the file size

The file size can be obtained using the filesize () function . The result will be a number in bytes:

<?php
    $size = filesize('file.txt');  
    echo "File size in bytes: $ size <br>";
    echo 'File size in megabytes:'. round ($ size / 1024/1024, 2);

File creation and modification date

The filemtime () function returns the time the file was last modified as a UNIX timestamp:

<?php
    $unix_time = filemtime('file.txt');

    echo date('d.m.Y', $unix_time); 
// display the date in the format DD.MM.YYYY
    echo date ('d.m.Y H: i: s', $ unix_time); // display the date and time in the format DD.MM.YYYY HH: MM: SS

Unfortunately, in UNIX there is no concept of file creation date, so you have to store it somewhere yourself, for example in a database or in a file name.

For Windows, you can use the filectime () function :

<?php
    $unix_time = filectime('file.txt');
    echo date('d.m.Y', $unix_time);

Folder, name and file extension

The pathinfo () function allows you to get the folder, name and extension from the path to a file:

<?php
    $info = pathinfo('D:\OpenServer\domains\phpclassroom.com\script.php');
    print_r($info);

Result in the browser:

Array
(
    [dirname] => D:\OpenServer\domains\phpclassroom.com
    [basename] => script.php
    [extension] => php
    [filename] => script
)

If you only need one of the parameters, you can immediately get it using the built-in constants PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION and PATHINFO_FILENAME , for example:

<?php
    echo pathinfo('D:\OpenServer\domains\phpclassroom.com\script.php', PATHINFO_BASENAME);
    // script.php

Current script directory

The magic constant __DIR__ allows you to quickly get the absolute path to the folder of the current script:

<?php
    echo __DIR__;

Working with Files in PHP

It is very easy task to learn working with files in php. follow this steps to get master in working with files in php.

Reading a file: file_get_contents ()

Using the file_get_contents () function, you can get the contents of a file:

<?php
    # Getting information from a file
    $data = file_get_contents('data.txt');

    var_dump($data);

We can also get the html-code of a page on the Internet:

<?php
    echo '<textarea>';
    echo file_get_contents('https://ya.ru');
    echo '</textarea>';

But this does not work for all sites, many have protection against such primitive parsing.

Reading a file: file ()

The file () function allows you to get the contents of a file as an array. The element separator is a line feed character.

Create a data.txt file at the site root with the following content:

Vasya
Petya
Gosha

Now let’s run the index.php script with the following code:

<?php
    $arr = file('data.txt');
    echo '<pre>';
    var_dump($arr);

When we run this script, we get in the browser:

array(3) {
  [0]=>
  string(7) "Vasya
"
  [1]=>
  string(7) "Petya
"
  [2]=>
  string(5) "Gosha"
}

Notice that the first two lines are 7 characters long instead of 5? This is because each line contains a line break at the end.

Most often we do not need them, so they can be removed by passing the FILE_IGNORE_NEW_LINES constant as the second parameter :

<?php
    $arr = file('data.txt', FILE_IGNORE_NEW_LINES);
    echo '<pre>';
    var_dump($arr);

Now all lines will have 5 characters.

If we need to get only filled lines in the file and skip empty ones, we can pass the FILE_SKIP_EMPTY_LINES constant as the second parameter :

<?php
    $arr = file('data.txt', FILE_SKIP_EMPTY_LINES);

Of course, we can pass two constants at once:

<?php
    $arr = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Create a file and write to a file: file_put_contents ()

The file_put_contents () function creates a file and populates it with data.

The function accepts the path to the file as the first parameter, and the data string as the second. To create an empty file, pass an empty string as the second parameter.

<?php
   
    // Create a file and write the string 'Vasya' into it
    file_put_contents ('data.txt', 'Vasya');

    // Create an empty file
    file_put_contents ('data.txt', '');

If the file does not exist, it will be created. If it exists, the data in the file will be overwritten.

In order not to overwrite the data, but to add it to the end of the file, you need to pass the FILE_APPEND constant as the third parameter :

<?php
    file_put_contents('data.txt', 'Data', FILE_APPEND);

You can also pass an array as the second parameter:

<?php
    file_put_contents('data.txt', ['One', 'Two', 'Three'], FILE_APPEND);

But this option is not very convenient, since all elements of the array will be written in a row, without any separators. To add them, you can use the implode function:

<?php
   
    $arr = ['One', 'Two', 'Three'];

    // Separate items with a comma
    $str = implode (',', $ arr);

    // Or you can separate them with a line break
    $str = implode ("\ n", $ arr);

    file_put_contents('data.txt', $str);

Create a folder or folder structure

You can create a folder using the mkdir () (make directory) function :

<?php
    mkdir('new_folder');

The second parameter specifies the permissions to the file as an octal number, by default it is 0777 , which means the widest rights. For Windows, this argument is ignored.

<?php
    mkdir('new_folder', 0755);

In addition, the second parameter can be ignored for the given umask (user mask, which is needed to determine the final access rights). In this case, you can forcibly change permissions using the chmod () function :

<?php
    mkdir('new_folder', 0777, true);
    chmod('new_folder', 0777);

We can also create the folder structure recursively, for this we need to pass true as the third parameter :

<?php
    mkdir('folder1/folder2/folder3', 0755, true);

But in this case, the permissions will be set only for the destination folder. To change the rights for each of the folders, you will have to specify the rights manually:

<?php
    mkdir('folder1/folder2/folder3', 0755, true);
    chmod('folder1', 0755);
    chmod('folder1/folder2', 0755);
    chmod('folder1/folder2/folder3', 0755); 
// If you need to ignore the umask

Access rights are a separate large topic, so now we will not consider it for now.

Checking if a file or folder exists

You can check the existence of a folder or file using the file_exists () function :

<?php
if(file_exists('data.txt'))
    echo '
File or folder exists';

If you want to check the existence of only a folder or only a file, there are special functions is_dir () and is_file () for this :

<?php
    $path = 'data.txt';

    if(is_file($path))   
    echo 'This is a file';
    elseif (is_dir ($ path))
        echo 'This is a folder';
    else
        echo 'Not found';

Access rights check

The is_readable () and is_writable () functions check if the user on whose behalf PHP is running has read and write permissions to a file or folder:

<?php
$path = 'data.txt';

if(is_readable($path))
   echo 'You have read permissions.';

if (is_writable ($ path))
    echo 'Write permission available.';

Copying, moving and deleting a file

The unlink () function is used to remove files :

<?php
    unlink('data.txt');

To copy a file, use the copy () function :

<?php
    copy('data.txt', 'new_data.txt');

The rename () function is used to rename and move the file to another folder :

<?php
    rename('data.txt', 'new_data.txt');

Working with files with fopen ()

The file () , file_get_contents (), and file_put_contents () functions are sufficient for most file management tasks.

But sometimes situations arise when we need more advanced tools. For example, if we have a large text file and we want to read it line by line, and not all at once, to save RAM.

So, you can open (or create and open) a file using the fopen () function :

<?php
    # If there is no file, it will be created$f = fopen('data.txt', 'w');

The fopen () function returns a so-called descriptor. This is a link, a pointer to a file, we will pass it to other functions. By the way, the data type of this descriptor is resource .

The first parameter is the path to the file, the second is the file access modifier. The most popular modifiers are listed below:

  • r – open for reading, the pointer goes to the beginning of the file.
  • r + – open for reading and writing, the pointer goes to the beginning of the file.
  • w – open for writing, the pointer goes to the beginning of the file. If there is no file, it is created, if there is, it is cleared of data.
  • w + – open for reading and writing, otherwise similar to w .
  • a – open for writing, the pointer goes to the end of the file. If there is no file, it is created.
  • a + – open for reading and writing, otherwise similar to a .
  • x – create and open for writing, the pointer goes to the beginning of the file. If the file exists, PHP will show an error.
  • x + – create and open for reading and writing, otherwise the same as x .

A pointer is something like a cursor. You can move it anywhere in the file to add or edit specific data.

To write data to a file, there is the fwrite () function . Let’s try to create a file and write some data to it:

<?php

# If the file does not exist, it will be created, if it exists, it will delete the old data
$ f = fopen ('data.txt', 'w');

# Add something to the file
fwrite ($f, 'First record');

# Add something else
fwrite ($f, 'Second entry');

# Close the file connection
fclose ($f);

# Now the file contains the text "First Record Second Record"

Note that due to the w modifier , each time the script is run, the data in the file is erased and re-added. If the modifier is replaced with a , the data will not be overwritten, but appended to the end of the file.

To read the file line by line, use the fgets () function :

<?php
$f = fopen("data.txt", "r");

while($line = fgets($f, 4096))
    echo $line, '<br>';

fclose($f);

On each run fgets gets the next line and returns it in $line . The second parameter is the maximum length of the string. This means that if the line is too long, it will be truncated.

There are also many other useful functions in PHP that work with the file descriptor. You can read about them in the documentation .

Absolute and Relative Paths in PHP

File paths are a topic that usually blows the mind of newbies. But don’t worry, now we’ll put everything on the shelves.

How PHP and URL paths differ

When we watch our favorite movie or TV series, we only see the finished product.

And behind the scenes there is a completely different world, invisible to us: stylists and make-up artists, artificial decorations, the imposition of special effects and much more.The process of filming a music video

The same division exists in PHP. On the one hand, there is a real file system with real folders and files, on the other hand, URLs that may have nothing to do with the real file structure.

If you see a page with the URL / category / monitors on some site , it does not mean at all that the site has a script /category/monitors/index.php .

It is likely that such a folder is not there either, and all URLs are processed by one single PHP file.

And even if the file extension is present in the URL, for example /about.html , this also does not indicate the existence of the about.html file . It may or may not be there.

Newbies often confuse real file paths with URLs. Now I will analyze a couple of such mistakes, by the example of which you can feel the difference.

Mistake # 1: Substituting a Physical Path in a URL

A very common mistake for beginners is to try to substitute a link to a physical file in the URL, like this:

<a href="D:\OpenServer\domains\test.com\article.php">Article</a>

It is not right. The browser cannot see the real file structure of the server. He doesn’t see any D drives, he only sees the URLs.

The correct link looks like this (I’ll explain the difference a little later):

<a href="http://test.com/article.php">Article</a>
<a href="/article.php">Article</a>
<a href="article.php">Article</a>

Mistake # 2: Including scripts by URL

Sometimes newbies try to connect a physical file by its URL:

require 'http://test.com/article.php';

It is not right. First, not the script itself will be connected, but the result of its work. Secondly, it is a very dangerous idea to include some files via a URL.

How correctly:

require 'config.php';
require 'D:\OpenServer\domains\test.com\config.php';
require __DIR__ . '/config.php';

Absolute path in PHP

An absolute path is the full path to a folder or file. Here are a couple of examples for different operating systems:

  • D: \ OpenServer \ domains \ test.com \ index.php – for OpenServer on Windows
  • /var/www/html/test.com/index.php – for Ubuntu

As you can see, this is the full path from the root of the drive to a specific file or folder. Starts with a slash or drive letter (Windows).

You can get the absolute path of the script using the __FILE__ magic constant :

<?php
    echo __FILE__;

There is a magic constant __DIR__ to get the absolute path to the folder where the script is located :

<?php
    echo __DIR__;

How to use it. Let’s say we have index.php and config.php files at the site root and we want to connect the second one to the first one.

If we want to include config.php with its absolute path, there are two ways to do it:

<?php
    # Specify the path manually
    require 'D:\OpenServer\domains\test.com\cpnfig.php';

    # Substitute path to current folder and add file name manually
require __DIR__ . '/config.php';

Since the __DIR__ constant does not add a slash after the last folder, we specify it manually.

PHP relative path

There is one catch with relative paths in PHP – they can be built relative to the wrong folder from which we expect.

The fact is that when we include the script on the relative path require (‘config.php’); PHP will search for it using the following algorithm:

  • PHP will first try to find this file in the folders specified in the include_path directive. You can see what is specified in this directive specifically for you using var_dump (get_include_path ()); , folders are separated by ;If we specify the path to the script like this: require (‘./ config.php’); then this step will be skipped.
  • Then PHP will try to find the file in the folder where the include script is located (in our case index.php).
  • PHP will then try to find the file in the current working directory folder.For example, if we have included the scripts / script.php file in index.php, and in this very script.php we are already trying to include the file by a relative path, then the file will be searched for in the scripts folder too.

The last two points are the main problem with relative paths. We cannot be sure that the exact file that we need will be included.

It is for this reason that I urge you to stop using relative paths in PHP .

Some of the practicing developers may not like this phrase, but I think this is the only reasonable solution.

Moreover, there is nothing difficult in adding the __DIR__ constant in front of the script name, which will automatically make the path absolute.

<?php
    # We refuse
    require 'config.php';

    # 
We use
    require __DIR__ . '/config.php';

Absolute path in URL

An absolute path in a URL means the path from the site root . Site root is the folder that contains the public part of the site, i.e. accessible from the outside.

By default, the site root is the site folder itself, for example site.ru , but it is often changed to site.ru/public so that some of the scripts cannot be run via a direct link in the browser.There are several ways to specify an absolute path in a URL:

  • http://test.ru/article.php – full path with protocol and domain
  • //test.ru/article.php – full path without protocol (taken from the current page). Contains two leading slashes.
  • /article.php – full path without protocol and domain (taken from the current page). Contains a slash at the beginning.

The second and third options are convenient because when migrating from http to https and vice versa, all links will automatically change the protocol, you will not need to run around the entire site and change manually.

Personally, I almost always use the third option, except when I need to provide a link to another subdomain (blog.site.ru, shop.site.ru, etc.).

Relative path in URL

Relative paths in the URL are indicated without a slash at the beginning of the link, for example:

<a href="articles">Link</a>

Relative URL paths are more predictable than PHP. But I recommend using them only where you really need to.

More often than not, their use leads to confusion. And here are a couple of common problems that newbies often face.

Mistake # 1: relative paths to styles, scripts and other files

Let’s imagine that we decided to add styles to our site:

<link rel="stylesheet" type="text/css" href="style.css">

The developer specifies the relative URL style.css and sees that everything works. At least on the home page.

But when you click on any link like / products / 15 , the styles stop working.

And the reason is that the relative path is built from the current URL, which means in our example it has changed from style.css to /products/15/style.css .

Mistake # 2: Recursion in links

When using relative paths, you run the risk of accidentally creating endless links on your site. Here’s one of those ways:

<a href="articles/about">
About Us</a>

A single entry point must be configured for this code to work.

The problem is that with each click on this link, the current URL will not be rewritten, but added, as a result, after a few clicks, we will get something like http://test.ru/articles/articles/articles/articles/about .

Current and parent directories

In addition to specifying specific folders, we can also add the instruction “go to the folder above” in the path, for example:

<?php
    include '../config.php';

In the code above, we will include the config.php file, which is located not in the current folder, but in the parent. This also works for absolute paths:

<?php
    include __DIR__ . '/../config.php';

And with urls too:

<a href="../article.php">Article</a>

We can also specify a link to the current directory, which is relevant in some operating systems:

<?php
    include './config.php';

Including Files in PHP

PHP has the ability to connect PHP (and not only) files to others. Thanks to this, we can divide a large script or site layout into several parts.

Include function

Let’s imagine that we have index.php and config.php files at the site root. And we want to connect the second to the first file. You can do it like this:

index.php

<?php
    include 'config.php';
    echo 'Home';

config.php

<?php
    echo '
Config.';

The include function includes the contents of the config.php script as if the script code were in index.php itself.

The result of running the script index.php:


Config. Main.

In this example, we have specified the relative path to the script, i.e. path relative to the calling script. We’ll take a closer look at this topic in the Absolute and Relative Paths in PHP lesson .

Require function

The require () function includes the file just like include () .

The difference is that if it is impossible to connect the file (the file is missing or there is not enough rights), the include () function will show an error and continue working, while require () will show an error and stop the script execution.

Include_once and require_once functions

When using functions with the _once prefix , you prevent the script from reconnecting. PHP will generate an error when trying to reconnect.

After this error, include_once () will continue and require_once () will stop the script.

Getting data from a plug-in script

The included script can pass any data to the connecting script using the return statement :

index.php

<?php
    $config = include('config.php');
    echo $config['site_name'];

config.php

<?php
    return [
        'site_url' => 'www.phpclassroom.com',
        'site_name' => 'PHP Eduket'
    ];

In the code above, the config.php script returns an array, which we accept in the index.php file and save it to the $ config variable.

Scope of include files

All variables, functions, etc., declared in the include file will be visible in the source. In this case, the variables are connected to the current scope. Those. if you connect a file inside a function, then the variables will be visible only in it:

index.php

<?php
    function get_config()
    {
        $config = include('config.php');
        return $config;
    }

    // 
Error, $ config variable is visible only inside the function
get_config
    echo $config['site_name'];

Dynamic Pages in PHP

A dynamic page is a PHP script that displays different content depending on the URL.

In this tutorial, we will create such a page using GET parameters.

Creating a dynamic page

To show the user different pages, you first need to prepare content for each page. Let all the pages lie in a two-dimensional array:

<?php
    $articles = [
       
         [
            'title' => 'Create dynamic pages',
            'content' => 'Text of the article about dynamic pages.'
        ],
        [
            'title' => 'How to catch a kitten',
            'content' => 'Text of the article about kittens.'
        ]
    ];

The content is ready, now let’s define the page navigation.

Let’s say the URL of our script is /index.php . We need to make a unique URL for each page.

To do this, we will add a GET parameter to the URL called id, which will contain the article number. For example /index.php?id=5 would mean to display the fifth article.

As numbers, we can use the keys of the array with articles. We now have 2 articles, one with index 0, the other with index 1, right?

Array
(
    
[0] => Array
        (
            [title] => Create dynamic pages
            [content] => Text of the article about dynamic pages.
        )

    [1] => Array
        (
            [title] => How to catch a kitten
            [content] => Text of the article about kittens.
        )
)

These numbers will be our identifiers. Now let’s write a simple menu with new URLs:

<!-- Display the menu -->
<a href="/"> Home </a>
<br>
<?php foreach($articles as $id => $article): ?>
    <a href="/index.php?id=<?= $id ?>"><?= $article['title'] ?></a>
    <br>
<?php endforeach; ?>

In the code above, we display a link to the main article and a personal link for each article.

Now we need to display the content of the corresponding article with the id GET parameter. The id itself lies in the $ _GET [‘id’] variable .

It is very easy to get an article by id:

$article = $articles[$_GET['id']];
echo $article['title'];

Those. we get an array with this article by the article ID.

Further, it makes sense to add 2 conditions: for the presence of an id in the URL and for the existence of an article with a specific id. If there is no id, then we will indicate that this is the main page, and if there is an id, but incorrect, you can show an error message:

<?php
// 
If id is not in the URL - display the main page
if (! isset ($_GET ['id']))
    echo '<h1> Home </h1>';

// If there is an id, but there is no article with this id, show an error
elseif (! isset ($ articles [$ _ GET ['id']]))
    echo '<h1> Error: The page does not exist. </h1>';

// If there is an id and an article with this id exists, display the article
else
{
    $article = $articles[$_GET['id']];

    echo '<h1>' . $article['title'] . '</h1>';
    echo '<p>' . $article['content'] . '</p>';
}

The dynamic page is ready! Once again, all the code:

<?php
    $articles = [
        ['title' => 'Create dynamic pages',
            'content' => 'Text of the article about dynamic pages.'
        ],
        [
            'title' => 'How to catch a kitten',
            'content' => 'Text of the article about kittens.'
        ]
    ];
?>

<! - Display the menu ->
<a href="/"> Home </a>
<br>
<?php foreach($articles as $id => $article): ?>
    <a href="/index.php?id=<?= $id ?>"><?= $article['title'] ?></a>
    <br>
<?php endforeach; ?>

<?php
// If id is not in the URL - display the main page
if (! isset ($_GET ['id']))
    echo '<h1> Home </h1>';

// If there is an id, but there is no article with this id, show an error
elseif (! isset ($ articles [$ _ GET ['id']]))
    echo '<h1> Error: The page does not exist. </h1>';

// If there is an id and an article with this id exists, display the article
else
{
    $article = $articles[$_GET['id']];

    echo '<h1>' . $article['title'] . '</h1>';
    echo '<p>' . $article['content'] . '</p>';
}

Now you can create dynamic sites where the number of pages depends only on the number of array elements, and no dozens of html files. 🙂

If the site should have different types of pages, for example, an article and a product, you can add one more GET parameter that is responsible for the page type: /index.php?type=article&id=5 .

Of course, this system is not perfect. Much more interesting would be a URL like / articles / 5 or / dinamicheskie-stranicy-v-php (like the article you are reading now).

In the near future I will add a new article about full-fledged CNC (human-like URLs) and explain in detail how this is done.

Passing Arrays Through a Form in PHP

You can combine multiple form elements and retrieve them as an array on the server. This is done by manipulating the name attribute .

This is how you can pass an associative array:

<form>
    <input type="text" name="product[name]">
    <input type="text" name="product[article]">
    <input type="text" name="product[price]">
    <input type="submit">
</form>

When the form is submitted, the contents of $ _GET will be like this:

Array
(
    [product] => Array
        (
            
[name] => Name
            [article] => Article
            [price] => Price
        )
)

An example of a handler for this form:

<?php
    if(!empty($_GET['product']))
    {
        
// You can iterate over all fields
        foreach ($ _ GET ['product'] as $ k => $ v)
            echo "$ k: $ v <br>";

        // Or refer to a specific field
echo $_GET['product']['name'];
    }
?>

<form>
    <input type="text" name="product[name]">
    <input type="text" name="product[article]">
    <input type="text" name="product[price]">
    <input type="submit">
</form>

Of course, ordinary numbers can also be keys. And if you need the keys to go in order, you can simply not specify anything in square brackets:

<form>
    <input type="text" name="values[]">
    <input type="text" name="values[]">
    <input type="text" name="values[]">
    <input type="submit">
</form>

The content of $ _GET will be like this:

Array
(
    [values] => Array
        (
            [0] => Value 1
            [1] => Value 2
            [2] => Value 3
        )
)

You can also transfer multidimensional arrays, for example, to edit several records in a database at once:

<form>
    <input type="text" name="images[10][title]">
    <input type="text" name="images[10][url]">
    <input type="text" name="images[11][title]">
    <input type="text" name="images[11][url]">
    <input type="submit">
</form>

An example of a handler for this form:

<?php
    if(!empty($_GET['images']))
    {
        foreach($_GET['images'] as $id => $data)
        {
            echo "ID: $id, ";
            echo "Title: $data[title], ";
            echo "URL: $data[url] <br>";
        }
    }
?>

In one form, you can specify ordinary fields and arrays together:

<form>
    <input type="text" name="id">
    <input type="text" name="product[name]">
    <input type="text" name="images[15][title]">
    <input type="submit">
</form>

Form Handling in PHP

What is form

From a developer’s point of view, a form is a collection of HTML elements, such as <input> , <select> , <textarea>, and so on, that are filled in by the user, sent to the server, and processed using PHP.

Simple example of a form:

<form>
    <input type="text" name="title">
    <textarea name="content"></textarea>
</form>

This form has 2 fields for filling (input and textarea) and also a button to submit the form.

If we fill in this form with any values ​​and click on the button, we will be redirected to a page with something like this URL: /? Title = 123 & content = 456 .

So, let’s figure out what’s going on here.Understanding PHP Form Processing

Form Handling in PHP – processing with GET parameters

Forms can be submitted using the GET and POST methods. The method is specified using the method attribute of the form tag :

<form method="POST">
</form>

If no method is specified, then by default the form is sent using the GET method.

Forms submitted with the GET method submit data via a URL.

Accordingly, a GET parameter is a parameter passed in a URL. For example, let’s parse the URL /index.php?name=Vasya&price=1000 in parts:

  • /index.php – link to the script itself
  • ? – the symbol with which the enumeration of GET parameters always begins
  • name = Vasya is the first GET parameter with the key name and the value Vasya
  • & – separator between GET parameters
  • price = 1000 is the second GET parameter with the price key and the value 1000

Well, since we have passed these parameters, now we can get them in PHP. There is a superglobal array $ _GET for this .

Unlike ordinary variables, this array is visible in any scope, incl. inside functions. Inside this array, the GET parameters of the current request are stored as an associative array.You can access these parameters like this:

<?php
    echo $_GET['name'] . ' ' . $_GET['price'];

When you submit the form, the browser receives the key and value of each element (the key is specified in the name attribute , the value is what the user entered) and substitutes them in a new URL, which it then navigates to.

Therefore, it is important to specify the name attribute on each form element, otherwise this element will not be sent to the server.

So, let’s create a simple form and add a PHP handler to it:

<?php
    if(isset($_GET['form'])) {
        echo $_GET['title'] . ' : ' . $_GET['content'] . '<br>';
    } else {
        echo 'Form not submitted';
    }
?>
<form>
    <input type="text" name="title">
    <br><br>

    <textarea name="content"></textarea>
    <br><br>

    <button name="form">
Send!</button>
</form>

Now, when submitting a completed form, PHP will display what we have written in this form.

POST method

When you visit any site, you do it with the GET method. Rather, your browser tells the server that the entry is made using the GET method. When you go through the pages of the site, each page is requested by the GET method.

However, this method has a drawback – the GET parameters are visible in the address bar. This means that the login and password entered into the form will be transmitted in the URL, which means they are visible in the browser history, which is very bad.

For this reason, you should always use the POST method to submit forms that may contain sensitive information. When using the POST method, data is passed in the body of the http request, not in the URL.

The GET method in forms is most often used to search for something (products, articles, etc.).

Some developers believe that the data transmitted by the POST method has some kind of special protection that prevents an attacker from stealing or replacing it.

This is not true. The POST method has no additional protection. To protect http requests, you need to use https.

The data sent by the POST method is contained in the $ _POST superglobal array . Now we can rewrite our form so that it sends data using the POST method:

<?php
    if(isset($_POST['form'])) {
        echo $_POST['title'] . ' : ' . $_POST['content'] . '<br>';
    } else {
        echo 'Форма не отправлена';
    }
?>
<form method="post">
    <input type="text" name="title">
    <br><br>

    <textarea name="content"></textarea>
    <br><br>

    <button name="form">Отправить!</button>
</form>

Change the form handler

The form handler is the URL to which the form will submit. By default, the form is submitted to the same URL where it is located.

If you want, you can submit the form not to the current URL, but to some other one. To do this, just specify the path to the script in the action attribute :

<form action="/some_url.php">
    <input type="submit">
</form>

In the example above, the request will be sent to the /some_url.php script .

Checking for Existence and Emptiness in PHP

Situations often arise when you need to check for the existence or emptiness of a variable. PHP provides the isset () , empty () and array_key_exists () functions for this .

Checking for the existence of a variable

The isset () function returns true if the variable exists and its value is not null :

<?php
    
$ name = 'Modi';

    if (isset ($name))
        echo 'Name given';
    else
        echo 'Name not specified';

If you pass several variables to isset, it will return true if all the variables exist:

<?php
    $ name = 'Vasilisa';
    $ age = 20;

    echo isset ($name, $age)? "Vasilisa is": "There is no Vasilisa";
    echo '<br>';
    echo isset ($name,$age, $status)? "Vasilisa is": "There is no Vasilisa";

Result in the browser:

Vasilisa is
Vasilisa is gone

NULL coalescing operators

The PHP 7 appeared combining operator with NULL (NULL-coalescing or operator) ?? … It allows you to get the value of a variable if it is set and not equal to NULL, and otherwise – the default value:

<?php
    // As it was before
    $ name = isset ($ user_name)? $ user_name: 'Unnamed';

    // How it became in PHP 7
    $ name = $ user_name ?? 'Nameless';

PHP 7.4 introduces the NULL assignment operator ?? = . It allows you to conveniently set the value of a variable if this variable is not already set (or is equal to NULL):

// As it was before
$ name = $ name ?? 'Vasiliy';

// As in PHP 7.4
$ name ?? = 'Vasily';

Check for emptiness

Let me remind you that a variable is considered empty (converted to false) if it has one of the following values:

  • 0 (integer or fractional)
  • ” (empty string)
  • ‘0’ (string with number 0)
  • [] (empty array)
  • null

The empty () function returns true if the variable does not exist or is empty:

<?php
   $name = 'Modi';

    if (isset ($name))
        echo 'Name given';
    else
        echo 'Name not specified';

    // Don't forget about the ternary operator :)
    echo isset ($name)? 'Name given': 'Name not set';

The behavior of isset () and empty () can be a little confusing at first: the former returns true if the variable exists, the latter if it does not exist. You just need to get used to it.

In fact, isset () and empty () , similar to echo , are syntax constructs, not functions.

The isset () and empty () functions clear the error of accessing a nonexistent variable. This is one of the reasons why they are not regular functions.

ceil($var); // Notice: Undefined variable: var

isset($var); // 

Existence of an array element

As we learned just above, isset () returns false if the variable exists but is null .

There are situations when we need to know exactly whether a certain element of an array exists or not, even if its value is NULL.

For this, PHP has the array_key_exists () function :

<?php
    $arr = [null];

    var_dump(isset($arr[0])); // false
    var_dump(array_key_exists(0, $arr)); // true

Custom Functions in PHP

PHP allows developers to create their own functions.

Creating functions

The creation of the function looks like this:

<?php
    // 
Function declaration
    function message()
    {
        echo 'hello';
    }

    message(); // 
Function declaration

First, the function keyword is written , then the name of the function (the naming rules are the same as for variables), parentheses (here we can receive data from the user), and in curly braces we write the actions that the function should perform.

The function is executed only when it is called. If we remove the message (); line from the example above ; then the function will not run.

Function arguments

The function can take values ​​from the user:

<?php
    function sum($v1, $v2)
    {
        echo $v1 + $v2;
    }

    sum(5, 15); // Output :20

In the example above, we are passing 2 values ​​to the function. The function puts them in the variables $ v1 and $ v2 , after which we can work with them.

Getting a value from a function

You can get the result of the function using the return statement :

<?php
    function sum($v1, $v2)
    {
        return $v1 + $v2;
    }

    echo sum(5, 15); // Output :20
?>

Great, now the function only performs calculations and returns the result, and we ourselves decide what to do with it next.

Try not to display any information on the screen inside functions.

Otherwise, this feature can be difficult to reuse elsewhere on your site.

Default values

You can specify a default value for a variable:

<?php
    function sum($v1, $v2 = 2)
    {
        return $v1 + $v2;
    }

    echo sum(5, 15); // Output : 20
    echo sum(5); // Output : 7
?>

In the example above, we indicate that if the 2nd parameter is not passed, then the variable will receive the value 2 .

Type hinting (specifying the types of arguments)

PHP 7 introduces full support for so-called type hints. We can specify what data type the value passed to the function should be:

<?php
    function make (int $v1, array $v2)
    {
        return $v1 . ' ' . $v2;
    }

    echo make(1, '
text'); // error, the second parameter must be an array
?>

If we pass a value to the function that can be cast to the required type (for example, instead of a string, we pass a number), the value will be cast to the desired type. If the value cannot be cast (for example, an array cannot be turned into a string), an error will occur:

<?php
function make(string $v)
{
    echo $v;
}

make(1); 
// There will be no error, the number will turn into a string
make ([1,2]); // Error, the array cannot be turned into a string
?>

Return type

Another PHP 7 feature is the ability to specify what type of data a function should return. If possible, the return value will be cast to the desired type, otherwise we will get an error:

<?php
function sum($a, $b): float {
    return $a + $b; // Always returns a fraction, even if the result is an integer
}?>

Function scope

Functions in PHP are scoped locally. This means that only those variables are visible inside the function that were declared inside the function, or passed to it:

<?php
    function show()
    {
        echo $a;
    }

    $a = 5;
    show(); //
Error, $a does not exist inside the function
<?php
    function edit($a)
    {
        $a = 10;
    }

    $a = 5;
    edit($a);

    // 
Will output 5 because $ a inside and outside the function are different variables
    echo $a;

Global variables in functions

Global variables can be used inside functions using the global keyword :

<?php
    $var = 5;

    function show()
    {
        global $var; // We indicate that $var is global
        echo $var;
    }

    show(); // Output:5

The use of globals is bad form. They make the code obscure and confusing, functions begin to depend on external factors.

Whenever possible, never use global variables.

Constants in functions

Unlike variables, constants are visible in any scope:

<?php
    define('LOGIN', 'admin');

    function showLogin()
    {
        echo LOGIN;
    }

    showLogin(); // Output : 'admin'

Built-in Functions in PHP

PHP has a huge number of built-in functions like var_dump () , 

print_r () , unset () , phpinfo () , etc.

To call a function, you need to write parentheses after its name:

<?php
    phpinfo();

It’s pointless to try to remember all the functions, there are simply too many of them.

I recommend studying 1-2 built-in functions in the documentation every day. This will help you gradually memorize the capabilities of PHP’s built-in functions.

Remembering the existence of the function you need, you can easily find its name on the Internet.

Some functions expect us to pass one or more parameters to them. For example, the ceil () rounding function expects you to pass it a number to round:

<?php
    echo ceil(15.5); // output:16

If the function expects multiple values, separate them with commas:

<?php
    echo str_replace(
'language', 'PHP', 'This is the language');

The str_replace function replaces one word (first value) with another (second value) on a specific string (third value). Result in the browser:

This is the PHP

The echo command is not a function. This is a “syntactic construct”, i.e. a special command created by PHP developers for convenience. We will meet with such teams in the future.