It's no secret that the most common way an HTML page interacts with a website is a form. The form (that is, the HTML element formed by the form tag) is also used by free postal services, electronic stores and many other types of sites.

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


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

Text fields

In this article, text fields refer to elements created by input tags with a type parameter value 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 the HTML markup for such a form.






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

n"; ?>

Switches

In this article, checkboxes are elements created by input tags with a type parameter value of checkbox . The form for using a variable number of “switches” is built in exactly the same way. Note that the choice of the 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 differs from the processing described for text fields. In this case, it is necessary to determine whether a site visitor has turned on this or that switch. If enabled, then the corresponding array element exists; if not, then it is missing. The following listing is an example PHP script that prints the enabled radio buttons:

Radio buttons

Before describing the processing of radio buttons, it is necessary 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. Buttons are combined into a set very simply: all buttons in the 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. Just as with text fields and radio buttons, the names of sets of radio buttons should be formatted as names of array elements in PHP. An example of such a form is given in the following listing:

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

Processing radio buttons combines the ideas of 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 in the array (as for radio buttons).

If the button is selected, then the corresponding array element will contain its value (as for text fields). Below is an example listing that processes a form with multiple sets of radio buttons.

n"; ?>

Thus, there is nothing complicated in processing complex shapes.

Often on Web sites you can find pages with HTML forms placed on them. Web forms are a convenient way to receive information from visitors to your site. An example of this is the guest book, which provides feedback with site visitors and developers. Forms are also convenient for site developers when developing a CMS, which allows them to maintain the main property of the site - relevance. This article is devoted to the basics of creating HTML forms, their processing, and ways to transfer data from screen forms to PHP scripts.

1) Create a simple form

Tags

And
define the beginning and end of the form. Starting form tag
contains two attributes: action And method. The action attribute contains the script URL that must be called to process the script. Attribute method tells the browser what kind HTTP request must be used to submit the form; possible values POST And GET.

Comment

The main difference between the POST and GET methods is the way information is transferred. In the GET method, parameters are passed through the address bar, i.e. essentially in the HTTP request header, while in the POST method the parameters are transmitted through the body of the HTTP request and are not reflected in any way in the address bar.

$text = nl2br($_POST["mytext"]);
?>

Task: Suppose you need to create a drop-down list with years from 2000 to 2050.
Solution: Need to create HTML form with the SELECT element and PHP – script for processing the form.

Discussion:

First, let's create two files: form.html And action.php. In file form.html will contain an html form with a drop-down list. Moreover, the values ​​in the list can be specified in two ways:

I. Manual data entry:

II. Entering data through a loop:

As you can see, the second example with a loop is more compact. I think there is no need to provide the handler script for this form, because it is processed exactly the same as a text field, i.e. list values ​​can be retrieved from a superglobal array $_POST.

Description:

Let's create an HTML form to send a file to the server.




This html form contains an element browse, which opens a dialog box for selecting a file to upload to the server. When you press the button "Transfer file", the file is passed to the handler script.

Then you need to write a handler script action.php. Before writing the handler, we need to decide in which directory we will copy the file:

if(isset($_FILES [ "myfile" ])) // If the file exists
{
$catalog = "../image/" ; // Our catalog
if (is_dir($catalog)) // If such a directory exists
{
$myfile = $_FILES [ "myfile" ][ "tmp_name" ]; // Temporary file
$myfile_name = $_FILES [ "myfile" ][ "name" ]; // File name
if(! copy ($myfile, $catalog)) echo "Error copying file". $myfile_name // If the file copy failed
}
else mkdir ("../image/" ); // If there is no such directory, we will create it
}
?>

Comment

If you trust users to upload any files to your server, you need to be extremely careful. Attackers can embed “bad” code into a picture or file and send it to the server. In such cases, you need to strictly control the downloading of files.

This example demonstrates creating a directory and copying a file into that directory onto the server.

I would also like to demonstrate an example with the element checkbox. This element is slightly different from other elements in that if not one of the elements checkbox’a is not selected, then the superglobal variable $_POST will return empty value:


Blue
Black
White

if (!empty($_POST [ "mycolor" ])) echo $_POST [ "mycolor" ]; // If at least 1 element is selected
else echo "Select value";
?>




If you have any other questions or something is not clear - welcome to our

All languages ​​of the world have the word "switch"
and only in Russian - “switch”!
Mikhail Zadornov

Today we will talk about such a syntax element PHP, like switches. It should not be confused with an HTML tag , which also creates switches. So,

switch statement

Task: depending on what the user chooses, display the required option. Let's look at the code:

Example 1. HTML page with a form:

Social survey

Enter your grade in Russian:

And here is the handler code:

Example 2. Form handler (cup6.php file):

if (! $score ) (
echo();
) elseif ($score == 1 ) (
echo ("Horror!" );
) elseif ($score == 2 ) (
echo ("Fail %-(" );
) elseif ($score == 3 ) (
echo ("Ud...");
) elseif ($score == 4 ) (
echo("Okay");
) elseif ($score == 5 ) (
echo("Great!");
) else (
echo ( "Interesting assessment...");
}
?>

I think that you all easily understood the code and understood how it works. Generally speaking, this code is correct, and there are no errors in it (it seems...), but it is very inconvenient: a whole bunch of conditions, it’s quite difficult to keep track of where everything is. What to do? Now we will need the switch switch.

Appearance switch like this:

Example 3. Appearance of the switch:

switch (expression) (
case value1 :
// commands that are executed if expression = value1
break; // optional
case value2 :
// commands that are executed if expression = value2
break; // optional
...
default:
// commands that are executed if not found
// no matches
break; // optional
}

How this whole block works:

  1. The value of the expression is calculated.
  2. The value of the expression is checked against the value 1. If they are equal, then the code located after the case value1 command is executed:
  3. If the value of the expression is not equal to the value 1, it is checked against the value 2, 4, and so on.
  4. If no matches were found, the code in the default block is executed.

The default block is optional: it can be omitted.

break() command; after each block of code is needed so that after the code has been executed, all subsequent cases are simply skipped.

Now let's change the code of the second example to be more convenient! For example, like this:

Example 4. Modified code from example 2 (file cup6.php):

switch ($score) (
case 0 :
echo ( “You still need to enter a rating...”);
break;
case 1 :
echo ("Horror!" );
break; case 2:
echo ("Fail %-(" );
break;
case 3:
echo ("Ud...");
break;
case 4:
echo("Okay");
break;
case 5:
echo("Great!" );
break;
default:
echo (
"Interesting assessment...");
}
?>

Like this. Simple and convenient. The results of this work are depicted in the figures:

Before After

Connection

It is often much more convenient to break the code into several parts and display them in the right places. To include the contents of one file in another file, we can use two commands: require(); and include();

require()

Team appearance:

Example 6. Appearance of the require() command:

require("filename" );

Before starting the script PHP finds all require() commands; And replaces them (commands) with the contents of the specified file.

The replacement only happens once before the script starts running, so you won't be able to include the require() command; into the body of the cycle!

The file that you include with the require() command; may contain PHP-code. This code will be executed.

include()

Team appearance:

Example 7. Appearance of the include() command:

include("filename");

include() command; inserts and executes the contents of the specified file, and this happens during script execution every time the inlcude() command is encountered; .

Despite the obvious similarity, the require(); commands and include(); are seriously different: the require() command; is executed once before the script starts executing, and the inlcude(); every time it occurs in the code and you can easily put the command inlcude(); into cycles.

How this can help in life: on almost every site there are parts of the page that do not change throughout the site - for example, the header (header) of the site and the footer (bottom) of the site. In order not to print them again on each page, you should take them out in two separate file(for example, header.php and footer.php) and connect as needed.

The code for such a page might look, for example, like this:

Example 8. Connecting the header and bottom of the page from external files:

require("header.php" ); // here is the text of the current page
require("footer.php" );
?>

Using require() in this example is preferable since we are only including these files once.

require_once() and inlcude_once()

If you need to make sure that a certain file is included in the code only once, then instead of require(); and include(); need to use require_once(); and require_once();

Look at the examples:

Example 9. Double use of include_once():

include_once("top.php" );
// some code here include_once("top.php" );
?>

In the previous example, the top.php file will be included in the page code only once, despite the fact that there are two commands in the code.

That's it...

Well, that seems to be all I wanted to tell you for today. Will there be any problems with PHP- write to me, I will help!

As homework: make a simple calculator. As a hint, here is a picture for you:

And here’s another thing: is it worth setting such “homework” at all?

In this tutorial we will create a simple design template switcher using PHP variables and CSS.

There are many similar switches, and I have already translated lessons on this topic a couple of times. You can change the design completely using special PHP scripts, or you can use JavaScript. In this case, the scripts simply change the style sheets. What if we need to change just a few styles on the page? We won’t create several different CSS files because of this.

Fortunately, there is a way out of this situation. PHP variables will help us with this; they will change some lines in the style sheet and, accordingly, our design will change.

First of all, we need to create a PHP file for the content of our page. We will make it extremely simple, but you can develop more complex circuits applications. Please note that our style sheet has a .php extension and is located in the CSS folder.


< html >

PHP Variables In CSS Demo
< meta http -equiv="Content -Type" content="text /html; charset = utf-8" />










Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.





I created some content with a small navigation that will allow us to change the template (in our case the header will change).

We will use a query string to change the current theme by passing the name value to the same PHP file. We also need the script to remember what design we are currently using and it remains throughout the site.

Insert the following code before the doctype:

session_start();


$_SESSION["template"] = $_GET["template"];

) elseif (isset($_SESSION["template"])) (
$template = "?template=".$_SESSION["template"];
) else (
$template = "";
}
?>

So here's what this code does. Since we are using sessions, we first need to start a session. Next, we check to see if the query string contains the value of a template variable. If it doesn't, we then set the session variable to the value of the template. Next we create a local variable with a string that we will add to the location of the CSS file. It will allow us to pass the name of the template that we want to use in the PHP file, create CSS styles.

Now we can create a template switcher. We use numbers 1-3 to identify the desired pattern:

switch theme:
1
2
3

We also need to change the location of the PHP file that is responsible for generating the CSS.

Now we are ready to create the PHP file that will be responsible for creating our template. We need to let the browser know at the very beginning of the file that CSS styles will be contained here. The following line of code will help us with this:

Header("Content-type: text/css; charset: UTF-8");

Now you can simply use this file as a normal style sheet with the ability to insert PHP variables. This opens up great opportunities for you not only to change the appearance of the page, but also to dynamically replace the content.

Since we only have 3 possible patterns, we need to make sure that only those 3 digits can be used. If suddenly someone tries to pass a different value in the query string, the default template will open before their eyes (in our case it is “1”).

$numberoftemplates = 3;
if (isset($_GET["template"])) (
$template = $_GET["template"];
if ((!is_numeric($template)) || ($template > $numberoftemplates) || ($template< 0)) {
$template = 1;
) else (
$template = round($template);
}
) else (
$template = 1;
}

We now have a local variable $template that contains the number of the template to use. For clarity, you can check this by using it as a comment to the CSS code:

Echo "/*====== template used: ".$template." ======*/";

After this, you can refer to the style.php file and see the following inscription in the source code: “/*====== template used: 1 ======*/”. If you access style.php?template=2 in the browser, then there will be a different value.

Since we don't create a separate style sheet for each template, we only need to indicate the differences between our designs in one file. We can write these changes into an array:

$css = array(
"header-background" => array(
1 => "url(../images/header-bg-1.jpg) no-repeat",
2 => "url(../images/header-bg-2.jpg) no-repeat",
3 => "url(../images/header-bg-3.jpg) no-repeat"
),
"header-h1-colour"=> array(
1 => "#fff",
2 => "#fff",
3 => "#666"
),
"header-h1-font"=> array(
1 => "bold normal 35px Helvetica, Arial, sans-serif",
2 => "bold normal 35px Trebuchet MS, Arial, sans-serif",
3 => "normal normal 35px Georgia, serif"
);

As you can see, I have allocated 3 elements in the array for each CSS selector.

Now we just need to substitute in the right place:

Background:;

and depending on the template, we will have a different background image.

That's all you need. Use these constructs throughout the file. This way you can replace many different elements on the page. Full style sheet:

* {
margin:0;
padding:0;
}
body (
font-size:.8em;
background:#F3F4F9;
font-family:Arial;
text-align:center;
}
#wrap (
width:990px;
margin:0 auto;
text-align:left;
}
#nav (
padding:10px 0;
width:990px;
overflow:auto;
}
#logo (
float:left;
}
#switcher (
float:right;
width:170px;
text-align:right;
padding:45px 20px 0 0;
}
#switcher span (
float:left;
padding:6px 10px 0 0;
}
#switcher a (
display:block;
float:left;
padding:4px 8px;
border:1px solid #ccc;
background:#eee;
margin:0 0 0 2px;
}
#switcher a:hover (
background:#fff;
}
#header (
clear:both;
background:;
height: 206px;
}
#header h1 (
text-align:right;
padding:155px 25px 0 0;
color:;
font:;
}
#col1 (
width:450px;
float:left;
margin:20px 0 0 0;
}
#col2 (
width:450px;
float:right;
margin:20px 0 0 0;
}

That's it! Enjoy!


Close