Computers Windows Internet

Frenzy do php action. PHP and forms. Bad points related to PHP _SELF variable

“Don't use a goto statement”- so the teachers at the academy told us, and indeed, this operator turns the code into a complete mess. The php developers have solved the problem radically - in php3 and php4 it simply does not exist. What were they initially guided by? Maybe they wanted to instill in all of us the correct programming style? Well, we can say they succeeded quite well - we are all already used to it, that is, it is more accurate to say that we have completely lost the habit of this operator, maybe it’s for the better, because at one time I had to come up with a logical structure that completely compensated for this most unfortunate goto.
I don't know how anyone, but I, especially often had a desire to use goto when creating an html form handler, when a lot of data is sent from the user to the server, which the php script must check step by step. This process, as a rule, takes place in several stages: printing the form itself, checking the received data, preliminary display, and, for example, saving. Moreover, some stages can be repeated: if the data check has not passed successfully, we go to print the form, or if the preview does not suit the user, he can return to entering the data. In short, some pieces of code can be used multiple times. It is also not very convenient to use functions in these conditions - there are many input and output variables, the function must perform too complex actions, in general it turns out clumsy and the readability of the code drops sharply.
And I came up with such a design.

do (

switch ($ action) (

default:

break;

case "PRINT_FORM":

We print the main form

break;

case "CHECK_FORM":

Checking the correctness of the data

break;

case "PREVIEW_FORM":

Preview

break;

case "SAVE_FORM":

We save the data

break;

) while (true);

Here's the main multiple choice operator switch enclosed in an endless loop do-while- in this way we group the necessary actions in sections case: break; and we can go from one section to another indefinitely. In the section default: it is convenient to do a preliminary parsing of the data, for example, if there is no input data, then $ action = ‘PRINT_FORM’ we print the form, if there is for example $ _POST [‘submit’] then we send the received data for processing $ action = ‘CHECK_FORM’... The transfer of control between switch blocks occurs by changing the variable $ action, well, exit the loop with break 2; or exit;
So, for example, in the print block of the main form, you can safely put break 2; because the output of the form presupposes the end of the script.
The design is very flexible and readable. But there is one drawback - if the data is incorrectly processed, you can get into an endless loop and the script freezes - it’s unpleasant to have to wait as long as 30 seconds.
Let's set a limit on the number of operator cycles do-while, 20 is enough with your head. Now, if we have added something, the script will wind 20 revolutions, stop and throw out an emergency stop warning.
It is very convenient to debug such a structure - it is enough after the operator swith print the variable $ action and we get the complete sequence of block execution.

DO (// at the beginning of each cycle we print the name // of the executed section, very convenient for debugging echo $ action. ""; SWITCH ($ action) (default: break; case "PRINT_FORM": / * print the main form * / break; case "CHECK_FORM": / * check if the data is correct * / break; case "PREVIEW_FORM": / * preview * / break ; case "SAVE_FORM": / * save the data * / break;) // end switch) WHILE ((($ i ++)< 20) or die("Принудительный останов цикла"));

DO (

// at the beginning of each cycle we print the name

// the executed section is very convenient for debugging

echo $ action. "";< / strong >

SWITCH ($ action) (

default:

break;

case "PRINT_FORM":

we print the main form

break;

Last updated: 1.11.2015

Form processing is one of the main ways of transmitting data to a website. Forms represent special elements of HTML markup that contain various input elements - text boxes, buttons, etc. And with the help of the form data, we can enter some data and send it to the server. And the server is already processing this data.

Form creation consists of the following aspects:

    Element creation

    in HTML markup

    Adding one or more input fields to this element

    Setting the data transfer method: GET or POST

    Setting the address to which the entered data will be sent

So let's create a new shape. To do this, we will define a new file form.php, into which we will put the following content:

Enter the site

Login:

Password:



The action = "login.php" attribute of the form element specifies that the form data will be processed by the script login.php which will be with the file form.php in one folder. And the method = "POST" attribute indicates that the POST method will be used as the data transfer method.

Now let's create a file login.php which will have the following content:

Your password: $ password ";?>

The global variable $ _POST is used to get the form data. It represents an associative array of data submitted using the POST method. Using the keys, we can get the sent values. The keys in this array are the values ​​of the name attributes of the form input fields.

Since the name attribute of the login input field is login ( ), then in the $ _POST array the value of this field will represent the "login" key: $ _POST ["login"]

And since there are situations when the input field will not be set, for example, when you go directly to the script: http: // localhost: 8080 / login.php... In this case, it is advisable to check for data availability using the isset () function before processing the data. And if the variable is set, then the isset () function will return true.

Now we can turn to the form:

And by clicking the button, the entered data by the POST method will be sent to the script login.php:

You don't have to send the form data to another script, you can process the form data in the same form file. To do this, change the file form.php in the following way:

Your password: $ password ";)?>

Enter the site

Login:

Password:



Data security

Data security is very important in PHP. Let's take a look at a few simple mechanisms that can improve the security of our website.

But first, let's take the form from the previous topic and try to enter some data into it. For example, let's enter in the login field "", and in the password field the text"

password

":

After sending the data to the html markup, the javascript code will be injected, which displays a message box.

To avoid this kind of security problem, use the htmlentities () function:

If (isset ($ _ POST ["login"]) && isset ($ _ POST ["password"])) ($ login = htmlentities ($ _ POST ["login"]); $ password = htmlentities ($ _ POST ["password" ]); echo "Your login: $ login
Your password: $ password ";)

And even after entering html or javascript code, all tags will be escaped and we will get the following output:

Another feature, the strip_tags () function, allows you to completely strip out html tags:

If (isset ($ _ POST ["login"]) && isset ($ _ POST ["password"])) ($ login = strip_tags ($ _ POST ["login"]); $ password = strip_tags ($ _ POST ["password" ]); echo "Your login: $ login
Your password: $ password ";)

The result of its work with the same input will be the following output.

24.6K

It's not a secret for anyone that the most common way of interaction of an html page with a site is a form. A form (that is, the html element formed by the form tag) is also used by free postal services, e-shops, and many other types of sites.

Processing simple forms with PHP is easy. However, from time to time there is a need to process a form containing several fields of the same type, while their number can vary in a wide range and their number is not known in advance. PHP provides for such cases processing of the same type of fields as an array of values.


Let's take a closer look at the options for different types of fields.

Text fields

Text fields in this article refer to elements created by input tags with a type parameter of text and a textarea tag. It is easiest to organize the processing of a form consisting of several such fields. The listing below shows a listing with html markup for such a form.






As you can see from the listing, the names for the form elements, from the PHP point of view, are array elements. Therefore, the PHP script that will process this form will treat the entire set of text fields on that form as a single array. Individual elements can be referenced by index or enumerated using the list and each commands, as in the following example.

n ";?>

Switches

Checkboxes in this article are elements created by input tags with a type parameter equal to checkbox. The form for using a variable number of "switches" is built in exactly the same way. Note that the choice of a specific radio button value (that is, the value of the value property) is not important. An example is shown in the listing below:






However, the processing of such a form is different from the processing described for text fields. In this case, it is necessary to determine whether or not the site visitor has turned on this or that switch. If enabled, then the corresponding element of the array exists, if not, then it is absent. The following listing shows an example PHP script that prints out the enabled switches:

Radio buttons

Before describing the processing of radio buttons, you need to remember how they work. The essence of radio buttons (elements created by input tags with the value of the type parameter equal to radio) is that by selecting one button, the user automatically deselects another button from the same set. It is very easy to combine buttons into a set: all buttons in a set have the same name.

But the values ​​(that is, the value parameters) of the buttons in the set are different. And the value of the selected button with the name of the set will be sent to the site. As with text fields and radio buttons, the radio button set names must be formatted as array element names in PHP. An example of such a form is shown in the following listing:

// first set of buttons
// second set of buttons
// third set of buttons

Processing radio buttons combines ideas, using both text fields and radio buttons in processing. If the author of the html page has not set a default value, and the user has not selected a specific button in the set of radio buttons, then this element will not be present in the array (as for radio buttons).

We have created the foundation for a future plugin that will be recognized by the WordPress system. Today we will deal directly with changing the basic functionality of the system.

The system of hooks, actions and filters will help us with this. These three concepts are at the heart of every WordPress plugin.

Hooks

There are two types of hooks in WordPress:

  • Action hook: marks a place in the code that performs a certain action, for example, you need to enter some data and save it in the database.
  • Filter hook: marks a filter that will change some value (variable), so that later the code will use the modified value.

Actions

Working with events

The general logic for managing events in WordPress is simple:

  1. Mark the place where the action should be performed using an action hook with the required parameters.
  2. Create a function that will perform the required actions using the parameters passed by the hook.
  3. Register an event that will be executed when the hook is triggered, with a specific priority.
  4. When WordPress loads the page and finds a hook, the system will execute all functions that are registered to that hook.

To perform the first step, the system provides the 'do_action' function:

Do_action ($ tag, $ arg_1, $ arg_2, ..., $ arg_n);

It accepts the following arguments: $ tag - the name of the "hook", $ arg_1, $ arg_2,…, $ arg_n - the parameters with which the function will be called. There can be any number of arguments, or 0.

The system itself has many hooks already defined:

Do_action ("init");

This is a very simple example with no additional arguments. The data hook is triggered when most of the system is already configured and it's time to create your own objects, categories, posts, etc.

Do_action ("save_post", $ post_id, $ post);

In this example, the hook is triggered when a post is saved with two arguments post_id - the post ID and post - the post itself.

Hook creation is available to any developer to create their own plugin (or theme). This gives us a powerful tool for managing system behavior.

Do_action ("my_truly_custom_hook");

When we created the hook and wrote the function, we need to register the function with "add_action"

Add_action ($ tag, $ function_to_add, $ priority, $ accepted_args_number);

The ‘add_action’ function takes two required parameters: $ tag: the name of the corresponding hook and $ function_to_add: the name of the function to be called. The other two parameters are optional: $ priority: an integer variable that determines the order in which the function is executed (default is 10), $ accepted_args_number: the number of arguments the function accepts (default is 1).

Let's look at an example to understand the whole process. Let's say we want to add a little notice at the bottom of our site. We can use the ‘wp_footer’ hook for this because it is a required part of the code that every theme uses.

Function msp_helloworld_footer_notice () (echo "

Hello, I "m your custom notice
";) add_action (" wp_footer "," msp_helloworld_footer_notice ");

In this example, we created a function that simply outputs the markup for the alert and registered it in ‘wp_footer’. As soon as we add this code to our plugin file (see the previous one), we will see the result on the page:

WordPress Plugin Alert

Working with filters (filters)

Filters work in the same way as events. But filters don't just execute a specific piece of code, they modify the values ​​passed to them by the hook. This means that each filter has an associated value (variable) that it operates on.

The filter function will take this value and transform it for later use. Filter hooks are slightly different from action hooks.

Apply_filters ($ tag, $ value_to_filter, $ arg_1, $ arg_2, ..., $ arg_n);

The ‘apply_filter’ function creates a filter hook named $ tag and the required parameter $ value_to_filter (it can be empty, but must be declared). The rest of the optional arguments work the same way as for events.

Filter_function ($ value_to_filter, $ arg_1, $ arg_2, ..., $ arg_n) (// filter return $ value_to_filter; // value must be returned)

This is a filter skeleton that demonstrates that a filter should:

  1. take at least 1 argument;
  2. return a modified value.
add_filter ($ tag, $ function_to_add, $ priority, $ accepted_args);

The 'add_filter' function registers a function with the name contained in $ function_to_add for the $ tag hook. The rest of the arguments - $ priority and $ accepted_args - work the same way as for event hooks.

For example, a common plugin task is to add something to the end of a post. If we take a closer look at the ‘the_content’ function, which is used to display the post content, we find a hook like this:

$ content = apply_filters ("the_content", $ content);

Using it we can easily add anything to the end of the post.

Function msp_helloworld_post_footer ($ content) ($ content. = "

"; return $ content;) add_filter (" the_content "," msp_helloworld_post_footer ", 100);

Please note that we are using a large number for priority to make sure that all standard filters have been processed before executing ‘msp_helloworld_post_footer’. After including the code in our plugin, we will see the result:


How to find a hook

Now it is clear to us that in order to perform certain actions, we need to know about the existing hooks.

The WordPress Codex provides lists of hooks for Action Reference and Filter Reference filters and events.

Additional actions with hooks

As well as adding, a hook can be removed using a similar syntax.

You can delete events like this:

Remove_action ($ tag, $ function_to_remove, $ priority, $ accepted_args); remove_all_actions ($ tag, $ priority);

As you may have guessed, 'remove_action' removes a specific event registered for the given hook (you must correctly specify the priority and number of arguments, as it was specified during registration), and 'remove_all_actions' helps to remove all events registered for the hook (if the priority is omitted, the function will delete all events).

Filters can be removed in the same way:

Remove_filter ($ tag, $ function_to_remove, $ priority, $ accepted_args); remove_all_filters ($ tag, $ priority);

The WordPress plugin API also provides functions to check if a function is registered for a given hook:

Has_action ($ tag, $ function_to_check); has_filter ($ tag, $ function_to_check);

Both functions check if the given function is registered for the hook and return true on success, otherwise flase. Inside the function, we have the ability to check that the hook called it:

If ("hook_to_check_name" === current_filter ()) ()

Despite the name ‘current_filter’ works not only with filters but also with events.

Non-trivial example

Let's animate the "skeleton" of our plugin, which we prepared in the last lesson.

Let's fill in the ‘core.php’ file (the main part of our plugin, which contains the main part of the functions) with code that solves a problem that can actually arise in the course of work. To solve it, we will use actions and filters.

Let your WordPress site accept posts from different authors from guests, but not allow you to create accounts. This means that the user who published the post and the real author are different people and we need to make sure that the author is listed in the post. We can do this with a taxonomy.

Let's create our own taxonomy for processing the author's name and short biography. We will be able to use the author's name like other taxonomy terms (tags, for example) in the post. Code:

/ ** register filters and events ** / function msp_helloworld_init () (add_action ("init", "msp_helloworld_taxonomies"); add_filter ("the_content", "msp_helloworld_author_block_filter"); add_filter ("post_class", "msp_hellow") addclass ("plugins_loaded", "msp_helloworld_init"); / ** taxonomy ** / function msp_helloworld_taxonomies () ($ args = array ("labels" => array ("name" => "Guest authors", "singular_name" => "Guest author"), "show_in_nav_menus" => false); register_taxonomy ("gauthor", array ("post"), $ args);) / ** author block markup ** / function msp_helloworld_author_block () (global $ post; $ author_terms = wp_get_object_terms ($ post-> ID, "gauthor"); if (empty ($ author_terms)) return; $ name = stripslashes ($ author_terms-> name); $ url = esc_url (get_term_link ($ author_terms)); $ desc = wp_filter_post_kses ($ author_terms-> description) ; $ out = "

"; $ out. ="
This is a guest post by ($ name)
"; $ out. ="
($ desc)
"; return $ out;) / ** add markup to the end of the post ** / function msp_helloworld_author_block_filter ($ content) (if (is_single ()) $ content. = msp_helloworld_author_block (); return $ content;) / ** add CSS class to the post ** / function msp_helloworld_post_class ($ post_class) (global $ post; $ author_terms = wp_get_object_terms ($ post-> ID, "gauthor"); if (! empty ($ author_terms)) ($ post_class = "gauthor";) return $ post_class;)

As you can see, we have created a function to register our own taxonomy and attached it to the 'init' hook. We then created a template for displaying the author block using the WordPress ‘wp_get_object_terms’ function. Then we inserted a block with information about the author at the end of the post using the ‘the_content’ filter. Finally, we added our own CSS class. Result of work:


Creates an event (a hook for an arbitrary function). For the function to be triggered at the time of the event, it must be connected to this event using the add_action () function.

In addition to events, there are also filters in WP, the principle of operation is the same. The only difference is that the filter must return the resulting variable, i.e. it filters (modifies) the data, and the event allows the user-defined function to run when this event is fired. Filters are triggered by the apply_filters () function

✈ 1 time = 0.00007s = very fast| 50,000 times = 0.03s = speed of light

There are no hooks.

Returns

Returns nothing.

Usage

do_action ($ tag, $ arg_a, $ arg_b, ...); $ tag (string) (required) The name of the hook to create. $ arg_a The value of the argument to be passed.
$ arg_b (string / array / number / object / boolean) The meaning of one more argument ...
Default: argument does not exist$ arg_с (string / array / number / object / boolean) Functions can be passed infinitely many arguments ...

Examples of

#1. Usage example

This feature can be used in plugins, themes, etc., when you need to be injected into the code execution process, from somewhere else. For example, we installed the "hook" (do_action) in the plugin, and we will "cling" to it from the functions.php file at the moment when our "hook" is triggered.

Let's say we used this code in a plugin:

Now we can do some action when the do_action function is triggered, and at the same time, we can describe our action, for example, from the functions.php file, by placing the following code in it:

Function do_my_hook ($ a, $ b) (// if the passed variable $ a is true, // then, for example, delete the entry 10 if ($ a === true) wp_delete_post (10); // and here we just display the variable echo "
". $ b; // displays the value of the second variable) // Register the hook via // add_action ($ tag, $ function_to_add, $ priority, $ accepted_args); add_action (" my_hook "," do_my_hook ", 10, 2);

Actions differ from filters in that the data passed by the action is not returned back to the function and is not used there in the future, but is just passed for use in the hook function.

Code do action: wp-includes / plugin.php WP 5.2.2

do_action ($ args); array_pop ($ wp_current_filter); )