php help на русском
Предисловие
Это руководство состоит, главным образом, из справочника функций, а также содержит справочник языка, комментарии к наиболее важным из отличительных особенностей PHP, и другие дополнительные сведения.
Это руководство доступно в нескольких форматах по адресу » https://www.php.net/download-docs.php. Более подробную информацию о том, как ведётся работа над руководством, вы сможете получить обратившись к приложению Об этом руководстве. Если вам интересна история PHP, обратитесь к соответствующему приложению.
Авторы и Участники
Мы публикуем имена самых активных на данный момент участников разработки документации на первой странице, но есть ещё множество людей, которые помогают нам в процессе разработки или оказали неоценимую помощь в прошлом. Также, есть огромное количество людей, помогающих нам с помощью системы пользовательских замечаний, которые постоянно включаются в основную документацию. Все списки ниже отсортированы в алфавитном порядке.
Авторы и Редакторы
Следующие участники внесли значительный вклад в наполнение документации в прошлом: Bill Abt, Jouni Ahto, Alexander Aulbach, Stig Bakken, George Peter Banyard, Christoph M. Becker, Daniel Beckham, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Philip Olson, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yoshinari Takaoka, Yannick Torres, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar и Andrei Zmievski.
Следующие участники внесли значительный вклад в редактирование и корректирование документации в прошлом: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe, Philip Olson и Egon Schmid.
Редакторы пользовательских замечаний
Текущие наиболее активные редакторы: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda и Maciek Sokolewicz.
Эти люди внесли свой вклад в управление пользовательскими замечаниями в прошлом: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles и Jeroen van Wolffelaar.
Другие переводчики
Наиболее активные переводчики присылавшие патчи: Spbima, Тигрович, Иван Ремень, Serg, Wolg, Degit, Nooneon, StelZek, Grul, Alexandr Fedotov, Marina Lagun, Mike, HaJIuBauKa, Sunny, dba, Александр Тушин.
Мы публикуем имена самых активных на данный момент переводчиков документации, но есть ещё множество людей, которые помогают нам. И каждый их перевод, поправка или совет ценен и важен.
Переводчики, ранее принимавшие участие в переводе руководства на русский язык (в алфавитном порядке): Alexander Voytsekhovskyy, Alexey Asemov, Andrey Demenev, Antony Dovgal, Boris Bezrukov, Evgeniy Syuzev, Irina Goble, Ivan Kovalenko, Jigkayev Kazbek, Kirill Barashkin, Olishuk Andrey, Veniamin Zolotukhin.
А также неизвестные переводчики со следующими никами: freespace, santiago, shafff, sveta.
Возможности PHP
PHP доступен для большинства операционных систем, включая Linux, многие модификации Unix (такие как HP-UX, Solaris и OpenBSD), Microsoft Windows, macOS, RISC OS и многие другие. Также в PHP включена поддержка большинства современных веб-серверов, таких как Apache, IIS и многих других. В принципе, подойдёт любой веб-сервер, способный использовать бинарный файл FastCGI PHP, например, lighttpd или nginx. PHP может работать в качестве модуля или функционировать в качестве процессора CGI.
Таким образом, выбирая PHP, вы получаете свободу выбора операционной системы и веб-сервера. Более того, у вас появляется выбор между использованием процедурного или объектно-ориентированного программирования (ООП) или же их сочетания.
PHP способен генерировать не только HTML. Доступно формирование изображений, файлов PDF и даже роликов Flash (с использованием libswf и Ming), создаваемых «на лету». PHP также способен генерировать любые текстовые данные, такие, как XHTML и другие XML-файлы. PHP может осуществлять автоматическую генерацию таких файлов и сохранять их в файловой системе вашего сервера вместо того, чтобы отдавать клиенту, организуя, таким образом, серверный кеш для вашего динамического контента.
PHP также поддерживает взаимодействие с другими сервисами через такие протоколы, как LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (на платформах Windows) и многих других. Кроме того, вы получаете возможность работать с сетевыми сокетами напрямую. PHP поддерживает стандарт обмена сложными структурами данных WDDX практически между всеми языками веб-программирования. Обращая внимание на взаимодействие между различными языками, следует упомянуть о поддержке объектов Java и возможности их использования в качестве объектов PHP.
PHP имеет много возможностей по обработке текста, включая регулярные выражения Perl (PCRE) и много других модулей и инструментов для обработки и доступа к XML-документам. В PHP обработка XML-документов стандартизирована и происходит на базе мощной библиотеки libxml2, расширив возможности обработки XML добавлением новых модулей SimpleXML, XMLReader и XMLWriter.
Есть ещё много других интересных модулей, которые можно просмотреть как в алфавитном порядке, так и по категориям. Есть ещё много дополнительных модулей PECL, которые также могут (а могут и нет) быть документированы в данном руководстве, такие как » XDebug.
Как вы видите, этой страницы не хватит для того, чтобы перечислить все, что может предложить вам PHP. Читайте следующую главу, Установка PHP и обратитесь к главе Справочник по функциям за более подробными сведениями о перечисленных выше модулях.
PHP и HTML
PHP и HTML тесно взаимодействуют: PHP может генерировать HTML, а HTML может передавать информацию PHP. Перед чтением вопросов в этом разделе важно чтобы вы понимали как получать переменные извне PHP. Страницы руководства по этой теме содержат много примеров.
Интерпретация HTML. Для того, чтобы задать произвольную строку, вы должны заключить её в двойные кавычки и использовать htmlspecialchars() для кодирования.
Пример #1 Скрытый элемент HTML-формы
Пример #2 Данные, редактируемые пользователем
Замечание: Данные показываются браузером как предполагается, потому что браузер будет интерпретировать экранированные HTML-символы. При отправке через GET или POST данные будут закодированы (urlencoded) браузером для передачи и декодированы (urldecoded) PHP. Поэтому вам не надо выполнять какое-либо кодирование/декодирование url самостоятельно, всё обрабатываются автоматически.
Пример #3 В URL
Замечание: На самом деле вы подделываете HTML GET-запросом, поэтому необходимо вручную закодировать ( urlencode() ) данные.
При отправке формы, вместо стандартной кнопки отправки возможно использовать изображение с тэгом как:
Пробелы в именах переменных запроса преобразуются в подчёркивания.
Определять ключи массивов в HTML необязательно. Если вы не установите ключи, массив заполняется в порядке появления элементов в форме. Наш первый пример будет содержать ключи 0, 1, 2 и 3.
Как получить все результаты из HTML-тега select с атрибутом multiple?
HTML-тег select с указанным multiple позволяет пользователю выбрать несколько элементов из списка. Эти элементы затем передаются обработчику формы. Проблема в том, что они все переданы с одним и тем же именем. Например:
Заметьте, что если вы используете JavaScript, то [] в имени элемента могут вызвать проблемы, если вы пытаетесь обращаться к элементу по имени. Вместо этого используйте числовой идентификатор элемента формы или заключите имя переменной в одинарные кавычки и используйте его как индекс массива элементов, например:
Как я могу передать переменную из JavaScript в PHP?
Пример #4 Генерирование JavaScript из PHP
User Contributed Notes 7 notes
1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.
But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)
The value of the variable is now the same as the original value.
*) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.
WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.
P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.
I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.
Do not enjoy my possibly stupid solution, if you have a better idea
Php help на русском
Класс может содержать собственные константы, переменные (называемые свойствами) и функции (называемые методами).
Пример #1 Простое определение класса
Результат выполнения данного примера в PHP 7:
Результат выполнения данного примера в PHP 8:
Если с директивой new используется строка ( string ), содержащая имя класса, то будет создан новый экземпляр этого класса. Если имя находится в пространстве имён, то оно должно быть задано полностью.
В случае отсутствия аргументов в конструктор класса, круглые скобки после названия класса можно опустить.
Пример #3 Создание экземпляра класса
Когда происходит присвоение уже существующего экземпляра класса новой переменной, то эта переменная будет указывать на этот же экземпляр класса. То же самое происходит и при передаче экземпляра класса в функцию. Копию уже созданного объекта можно создать через её клонирование.
Пример #4 Присваивание объекта
Результат выполнения данного примера:
Создавать экземпляры объекта можно двумя способами:
Пример #5 Создание новых объектов
class Test
<
static public function getNew ()
<
return new static;
>
>
class Child extends Test
<>
Результат выполнения данного примера:
Обратиться к свойству или методу только что созданного объекта можно с помощью одного выражения:
Пример #6 Доступ к свойствам/методам только что созданного объекта
Результатом выполнения данного примера будет что-то подобное:
Замечание: До PHP 7.1 аргументы не имели значения, если не определена функция конструктора.
Свойства и методы
Пример #7 Доступ к свойству vs. вызов метода
public function bar () <
return ‘метод’ ;
>
>
Результат выполнения данного примера:
Это означает, что вызвать анонимную функцию, присвоенную переменной, напрямую не получится. Вместо этого свойство должно быть назначено, например, переменной. Можно вызвать такое свойство напрямую, заключив его в скобки.
Пример #8 Вызов анонимной функции, содержащейся в свойстве
Результат выполнения данного примера:
extends
Класс может наследовать константы, методы и свойства другого класса используя ключевое слово extends в его объявлении. Невозможно наследовать несколько классов, один класс может наследовать только один базовый класс.
Наследуемые константы, методы и свойства могут быть переопределены (за исключением случаев, когда метод класса объявлен как final) путём объявления их с теми же именами, как и в родительском классе. Существует возможность доступа к переопределённым методам или статическим свойствам путём обращения к ним через parent::
Пример #9 Простое наследование классов
class ExtendClass extends SimpleClass
<
// Переопределение метода родителя
function displayVar ()
<
echo «Расширенный класс\n» ;
parent :: displayVar ();
>
>
Результат выполнения данного примера:
Правила совместимости сигнатуры
Пример #10 Совместимость дочерних методов
Результат выполнения данного примера:
Следующие примеры демонстрируют, что дочерний метод, который удаляет параметр или делает необязательный параметр обязательным, несовместим с родительским методом.
Пример #11 Фатальная ошибка, когда дочерний метод удаляет параметр
class Extend extends Base
<
function foo ()
<
parent :: foo ( 1 );
>
>
Результат выполнения данного примера в PHP 8 аналогичен:
Пример #12 Фатальная ошибка, когда дочерний метод делает необязательный параметр обязательным.
Результат выполнения данного примера в PHP 8 аналогичен:
Переименование параметра метода в дочернем классе не является несовместимостью сигнатуры. Однако это не рекомендуется, так как приведёт к Error во время выполнения, если используются именованные аргументы.
Пример #13 Ошибка при использовании именованных аргументов и параметров, переименованных в дочернем классе
Результатом выполнения данного примера будет что-то подобное:
::class
Пример #14 Разрешение имени класса
namespace NS <
class ClassName <
>
Результат выполнения данного примера:
Разрешение имён класса с использованием ::class происходит на этапе компиляции. Это означает, что на момент создания строки с именем класса автозагрузки класса не происходит. Как следствие, имена классов раскрываются, даже если класс не существует. Ошибка в этом случае не выдаётся.
Пример #15 Отсутствует разрешение имени класса
Результат выполнения данного примера:
Начиная с PHP 8.0.0, константа ::class также может использоваться для объектов. Это разрешение происходит во время выполнения, а не во время компиляции. То же самое, что и при вызове get_class() для объекта.
Пример #16 Разрешение имени объекта
Результат выполнения данного примера:
Методы и свойства Nullsafe
Пример #17 Оператор Nullsafe
Оператор nullsafe лучше всего использовать, когда null считается допустимым и ожидаемым значением для возвращаемого свойства или метода. Для индикации ошибки предпочтительнее выбрасывать исключение.
User Contributed Notes 11 notes
I was confused at first about object assignment, because it’s not quite the same as normal assignment or assignment by reference. But I think I’ve figured out what’s going on.
First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.
Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object’s «handle» goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.
What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.
Функции запуска программ
Примечания
Открытые файлы с блокировкой (особенно открытые сессии) должны быть закрыты до выполнения программы в фоне.
Смотрите также
Эти функции также тесно связаны с оператором обратные кавычки («).
Содержание
User Contributed Notes 46 notes
exec(«php script.php parameters 2>dev/null >&- /dev/null &»);
Where.
— php is the path to your php script executer (php has to be specifically complied to be to do this)
— script.php is the script
— parameters are none or more parameters
— 2>dev/null redirects the stderr to a file
— &- switches off the stdout
— >dev/null redirects all other output to the file dev/null
— & direct script to run in background
What I found odd is that the script I was execing would run fine in the bg when executed from the command line, but not from the browser until I closed the stdin and stdout.
at LAST! tenacity pays off, days trying every little thing!
I didn’t want batch files. I’m trying to use PHP to get rid of batch files.
I didn’t want to call a file to parse the parameters to call a shell to call a file. I’ve got «systems» right now with batches tiered three and five deep.
I just wanted to run stuff.
CALL, tested on WinXP, will be testing on more OSes right away, in PHP4 and 5, with exec, system, works with popen, and passthru.
here is my lame sample function.
// all of the below are working in Win XP Pro
passthru ($shellcommand);
exec ($shellcommand);
system ($shellcommand);
shell_exec ($shellcommand);
$proc= popen ($shellcommand, «r»); //$proc contains output
LONG PATH NAMES WITH SPACES IN THEM ON WINDOWS!
all in a big long concatenated command line with multiple quoted-filename parameters
shell scripting bliss!
The only syntax I found to work for the command portion of an an exec() call on a Win2K devel platform is:
$cmd = «\»path-to-exe\» args file-name»;
where ‘path-to-exe’ has escaped double quotes, args are in the standard format, and ‘file-name’ has any backslashes escaped.
Note that the backslashes are escaped in the uploaded_file name, but not in the path to call the Winzip executable. Go figure!
To clarify even more about what has been said in the last few posts:
«exec», «backticks», «system» and so on will fail on Windows 2003 by default.
You must modify the security on cmd.exe to give the user account IUSR-computername the necessary permissions which are at least read & execute.
The note is about usage of exec() under windows.
Here is where i’m at right now (also TRYING to use exec() and passthru() on windows XP sp2):
$cmd = ‘»C:\my path with spaces\targetapp.exe» C:\mypathnospaces\targetfile.xxx’;
exec($cmd);
The above works.
________
Or, you can put your script into your directory C:\my path with spaces\, and work with php directly from there:
$cmd = ‘targetapp.exe «C:\my other path with spaces\targetfile.xxx»‘;
exec($cmd);
The above also works, provided of course your script has the correct working directory.
________
But. In your cmd.exe, you can issue:
«C:\my path with spaces\targetapp.exe» «C:\my other path with spaces\targetfile.xxx»
Although the above works perfectly in the cmd, the following php script does NOT work on my system:
$cmd = ‘»C:\my path with spaces\targetapp.exe» «C:\my other path with spaces\targetfile.xxx»‘;
exec($cmd,&$content);
As far as my few tryings go, the root of the problem lies in the fact that the command to execute has two passages enclosed inside double quotes. Another command which I’ve had working in the cmd but NOT with php is:
Maybe someone has a solution; I don’t (other than using chdir).
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use cacls command-line utility to do this.
cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F
gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
To fork a process I use the following code
( STDOUT ); //Close all output or it WON’T work
fclose ( STDIN );
fclose ( STDERR );
if( pcntl_fork ()) <
exit; //Return to the caller
>
//Code to run in the background
AFICT, the standard Unix Apache configuration causes an rare problem when running a job in the background. The MaxRequestsPerChild directive causes the child to terminate after 1000 requests, any background processes associated with the child will die with the child unless they are started with the «nohup» command. Thus, the proper way to start a job in the background is to use:
exec(‘nohup my-command > /dev/null 2>&1 &’)
Just a simple note to help people get rid of some headaches.
Make sure you use «\ » ( \ space) for the Linux\unix path and just » » space for fopen. These are both very basic things that you wouldn’t normally think to cause a problem, but when you try to pass slashes to fopen it either breaks or even better works incorrectly =D. And vise versa for any programs that use «\ » for spaces in file paths/names.
*Note this is alot of sudo code, and there are faster more effecient ways of doing the same operations, but I thought this might help those who were going crazy over filepaths =D.
Well, I had this issue when I wanted to start an indefinitely running PERL script from PHP. Somehow I could not make the PHP script to return after executing the PERL script. So finally I came to following solution:
PHP file
——————-
( «perl /home/chatserver.pl > /dev/null» );
?>
——————-
This script will be run over HTTP.
Hopefully it helps someone 🙂
Margus
If you plan to start programs on the server that show message boxes (things that require OK from the server-side), or remain (like notepad.exe), and the exec-command seems to go into an deadly loop, then MAYBE your program has started, but you can’t see it. Because the web server runs as an system process, and it isn’t allowed to interact with the desktop.
To solve a part of the problem (to see the programs you execute), in the control panel in Windows, goto Administration->Services, right-click the server-service, goto Properties and on the second tab (login?) and check the box about allowing the service to interact with the desktop. Click OK. Restart the webserver, and MAKE SURE it is restarted for real (i.e. look in the task manager so the service goes _down_), otherwise the desktop-option won’t take.
Next phase would be to stop PHP from waiting for the processes to complete (this is what makes PHP «loop»). I solved this by creating a small Delphi-application that took the path to the file I wanted to execute and executed it by the WinExec API, which just starts the childprogram but doesn’t wait for it to complete = the program completes and the PHP.exe completes the script. Problem solved!
Delphi-snippet:
WinExec(PChar( ),SW_SHOW); // replace with the program path.
I was stuck for about an hour and a half last night trying to get Perl to pass back values to my PHP script after running an exec() command.
Of course, this wasn’t working and I finally figured it out with the help of a friend (Shawn = superstar): you need to echo the exec() command in order to get the values back into PHP.
In case you ever had to chain from php to another program (e.g. with a cgi php that only gives part of the output, or with php-gtk), here is a little C program that kills his parent (php, for instance), then launches a program given in argument.
Just following up my previous post, in reply to lancelot—du-lac at hotmail dot fr:
The behaviour described was fixed in PHP 5.3 in the following commit:
To replicate the fix in your own code, so it also runs on PHP 5.2, instead of:
= «. any shell command, maybe with multiple quotes. » ;
Within Linux, when calling the php interpreter directly from popen, or other program execution function to execute a script, it appears as though the script perpetually fails and re-executes.
[One solution is] to ensure the executing script has a valid shebang, and execute permissions. This allows you to execute the script directly
I found this comment on this page:
Instead of nslookup I believe this would apply to most programs from the \system32\ directory.
. but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory «c:\php\safedir\» is set in the php.ini setting
safe_mode_exec_dir = «c:\php\safedir\»
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!
Hope this helps somebody saving some time and headaches.
[end of quote]
This is just to complicated. Only two things are needed:
1. Specific permissions for the IUSR account for read & execute to the cmd.exe in C:\Windows\System32 directory
2. Specific permissions for the IUSR account for read & execute to the command that’s needed (example: nslookup.exe in C:\Widnows\System23 directory)
With just this two conditions the exec works fine
(This is for an IIS server running on a windows platform)