Lecture
Web programming for the most part is just the processing of various data entered by the user - that is, the processing of HTML forms .
Perhaps there is no other language like PHP that would make your task of processing and parsing so much easier. external variables i.e. variables that came from HTML forms (from the user's browser). The fact is that all necessary features are built into the PHP language, so you don’t even have to think about the features of the HTTP protocol and think about how to send and receive POST forms or even download files. PHP developers have foreseen everything.
Here we will not dwell on the mechanics of the HTTP protocol, which is responsible for delivering data from the browser to the server and back; a special section PHP and HTTP is devoted to this. The principles of working with HTML-forms are also deeply considered.
Now we will consider these mechanisms only from applied positions, without delving into theory.
In order to receive data from users, we need interactive interaction with them.
And now let's try to write a script that takes the username in the parameters and displays:
"Hello, <name>!".
First, consider the easiest way to pass a name to a script — is it directly typed into the URL after the sign ? - for example, in the format name = name . Here is an example:
http://localhost/script.php? name=имя
Our script should recognize the name parameter. That is, to put it simply, the script (script) must accept the name parameter as a variable name , and then display the string "Hello, <name>!" In the user's browser. You can do it this way:
We write a script that takes the name parameter and displays the result in the user's browser, and then saves it as script.php :
<?php
echo "Привет, $_GET['name'] !";
?>
In our example, we used the predefined variable $ _GET ['name'] to "accept" the name parameter. Now, passing the parameter name = Sasha through a GET request, we get the following result:
Привет, Саша !
And now let's try to pass the name parameter not from the browser's request string, but through the HTML form. Create an HTML document as follows:
<form action="http://localhost/script.php" method="GET">
Name: <input type=text name=name><br><input type=submit value="GO!">
</form>
Now we will save this HTML document on our test server (localhost) under the name send.html in the same directory where we already saved the script script.php .
Now run the HTML document in the browser:
http://localhost/send.html
Enter the name in the field and press the button "GO!". The form will transfer the name parameter to our script.php via the GET request. If you did everything correctly and your web server is working properly, you will see the name you entered in the form field! In the address bar of the browser you will see the path and the parameter name you passed.
Now we need to understand how we can transfer a lot of parameters, for a start, at least two .
So, we need the script to output the following:
"Hello, <name>! You are <age> years old!".
That is, we need to transfer 2 parameters to the script: name and age .
Now we will write a script.php script that takes two parameters: name and age , as well as an HTML document with a form that will pass these two parameters to our new script:
<?php
echo "Привет, $_GET['name'] ! Вам $_GET['age'] лет !";
?>
And here is the HTML document send.html , with which we pass the name and age parameters to our script:
<html><body>
<form action="script.php">
Введите имя: <input type=text name="name"><br>
Введите возраст: <input type=text name="age"><br>
<input type=submit value="GO!">
</form>
</body></html>
Now our script takes two parameters name and age and displays the result of the format in the browser: "Hello, <name>! You are <age> years old!".
Pay attention to the address bar of the browser after passing the parameters to the script, it will look something like this (without the Cyrillic URL-coding):
http://localhost/script.php?name=Саша&age=23
Depending on your interpreter’s settings, there are several ways to access data from your HTML forms. Here are some examples:
<?php
// Доступно, начиная с PHP 4.1.0
echo $_GET['username'];
echo $_POST['username'];
echo $_REQUEST['username'];
import_request_variables('p', 'p_');
echo $p_username;
// Доступно, начиная с PHP 3. Начиная с PHP 5.0.0, эти длинные предопределенные
// переменные могут быть отключены директивой register_long_arrays.
echo $HTTP_GET_VARS['username'];
// Доступно, если директива PHP register_globals = on. Начиная
// с PHP 4.2.0, значение по умолчанию register_globals = off.
// Использование/доверие этому методу непредпочтительно.
echo $username;
?>
Here's how it usually happens: We need to write a tiny console backup script that can be run from the crown, and at the same time the script must accept parameters for connecting to the database.
The simplest thing we start to write will look something like this:
cli-argv-argc.php
<? php // Expect the script to be called with the following parameters: // php backup.php dbuser dbpassword database host if ($ argc! = 5) { die (PHP_EOL. 'Use: php backup.php dbuser dbpassword database host'. PHP_EOL); } $ dbuser = $ argv [1]; $ dbpassword = $ argv [2]; $ database = $ argv [3]; $ host = $ argv [4]; $ mysql = mysql_connect ($ host, $ dbuser, $ dbpassword); mysql_select_db ($ database, $ mysql); // ...
Here we used the system variable args to get the number of all parameters. Remember that the zero parameter (script name) is also taken into account here.
And the system variable argv with an array of all parameters.
For the simplest script, this is enough, but what if we want to support and give this script to other developers?
Most likely there will be a lot of swearing in our direction, because it is very easy to make a mistake and interchange the password and database and notice the error will be extremely difficult. Take a look:
php backup.php dbuser database dbpassword host
This is where an extremely convenient parameter parsing function comes to our rescue: getopt
The main power of getopt is that it allows us to use flags, required and optional parameters in arbitrary order.
Let's write a simple but very expressive example of using getopt, and then, look how people used to suffer with regulars to parse the command line :)
backup.php
<? php // Two forms of writing arguments are shown here: short and full // At the same time, if after the parameter there are two colons, then the parameter is optional, // and if one colon means mandatory. // all parameters that are not specified in the configuration will be ignored $ params = array ( '' => 'help', 'h ::' => 'host ::', 'u:' => 'user:', 'p ::' => 'password ::', 'd:' => 'database:', ); // Default values $ host = 'localhost'; $ user = 'root'; $ password = null; $ database = ''; $ errors = array (); $ options = getopt (implode ('', array_keys ($ params)), $ params); if (isset ($ options ['host']) || isset ($ options ['h'])) { $ host = isset ($ options ['host'])? $ options ['host']: $ options ['h']; } if (isset ($ options ['user']) || isset ($ options ['u'])) { $ port = isset ($ options ['user'])? $ options ['user']: $ options ['u']; } else { $ errors [] = 'user required'; } if (isset ($ options ['password']) || isset ($ options ['p'])) { $ socket = isset ($ options ['password'])? $ options ['password']: $ options ['p']; } if (isset ($ options ['database']) || isset ($ options ['d'])) { $ database = isset ($ options ['database'])? $ options ['database']: $ options ['d']; } else { $ errors [] = 'database required'; } if (isset ($ options ['help']) || count ($ errors)) { $ help = " usage: php backup.php [--help] [-h | --host = 127.0.0.1] [-u | --user = root] [-p | --password = secret] [-d | --database ] Options: --help Show this message -h --host Server hostname (default: localhost) -u --user User -p --password Password (default: no password) -d --database Database Example: php backup.php --user = root --password = secret --database = blog "; if ($ errors) { $ help. = 'Errors:'. PHP_EOL. implode ("\ n", $ errors). PHP_EOL; } die ($ help); } $ mysql = mysql_connect ($ host, $ user, $ password); mysql_select_db ($ database, $ mysql); // ....
Now let's run our script with the –help parameter and rejoice that a well-supported and understandable program is so easy to write
php backup.php --help
In short, getopt takes all the arguments from the command line and adds valid parameters to the $ options array. And from the resulting array, we can get all the arguments and, depending on them, produce the result.
Let's add the final touch, which should be in all of our scripts:
1. You can remove the php extension
2. At the beginning of each script, add an option for the interpreter #! / Usr / bin / env php
3. Let's make our scripts executable chmod + x backup.php
After that, you can use the resulting script as a real Unix program:
./backup --help
or
./backup --user = ukko --password = password --database = db1
Chapter 24. Using PHP from the command lineStarting from version 4.3, PHP supports the new SAPI type (Server Application Programming Interface) called CLI , which means Command Line Interface . As the name implies, the main task of this SAPI- type is to develop shell / shell (or desktop) applications using PHP. There are very small differences between CLI SAPI and other SAPIs , which will be further discussed in this chapter. The CLI SAPI was released for the first time with PHP 4.2.0 , but then it was an experiment, and you had to explicitly turn it on with the --enable-cli command when starting ./configure . Beginning with PHP 4.3.0 , the CLI SAPI is no longer experimental and is always embedded and installed as a binary php executable (called php.exe in Windows). Significant differences of CLI SAPI from other SAPI :
Table 24-1. Override php.ini directives
A list of command line options for the PHP executable can be obtained at any time by running PHP with the -h option :
CLI SAPI has three different ways to get the PHP code to execute:
You cannot combine these three methods when executing code. As with any shell application, not only PHP itself, but your PHP scripts also take arguments. The number of arguments passed to the script in PHP is not limited (the shell has a limit on the number of characters to be transferred). If the arguments that you want to pass to the script do not begin with a hyphen (-) character, you do not need to observe anything specifically. Passing to the script an argument starting with - will create problems, because PHP thinks it should handle them. To prevent this, use as a list argument separator - . After the argument is parsed by PHP , each subsequent argument is passed to your script unchanged / not parsed.
However, here is another way to use PHP for shell scripting. You can write a script, the first line of which begins with #! / Usr / bin / php , and then comes the normal PHP code contained between the PHP start and end tags and the file execution attributes are set accordingly. In this way, it can be executed as a normal shell script or perl:
Assuming that the file is called test and is located in the current directory, we can execute:
As you can see, nothing special needs to be done when passing parameters to the script, which begins with - . Table 24-3. Command line options
Исполняемый файл PHP может быть использован для запуска PHP-скриптов абсолютно независимо от web-сервера.
Здесь мы используем специальную первую строку для указания на то, что этот файл должен быть запущен в PHP. Здесь мы работаем с CLI-версией, поэтому не выполняется вывод HTTP-шапок/header. Имеются две переменные, которые вы можете использовать при написании РНР-приложений для командной строки: $argc и $argv . Первая - это количество аргументов плюс 1 (имя запущенного скрипта). Вторая - это массив аргументов, начиная с имени скрипта с индексом ноль ( $argv[0] ). Мы проверяем, имеется ли менее или более одного аргумента. Также, если аргумент был --help , -help , -h или -? , мы печатаем help-сообщение, выводя имя скрипта динамически. Если мы получили какой-либо другой аргумент, мы выводим его (echo). Если вы хотите выполнить вышеприведённый скрипт под Unix, вам необходимо сделать его executable и просто вызвать как script.php echothis или script.php -h . Под Windows вы можете создать batch-файл для выполнения этой задачи:
Assuming that you called the program script.php and that your php.exe is in c: \ php \ php.exe , this batch file will launch it with the options you added: script.bat echothis or script.bat -h . |
Comments
To leave a comment
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)