Creating html pages with PHP. What is the difference between a php file and an html file What you need to know
Cameron Laird
PHP does not support processing streams. Regardless, and contrary to the opinion of most PHP developers I have spoken to, PHP applications can multitask. Let's start by finding out what "multitasking" and "threading" mean for PHP programming.
Diversity of parallelism
First, we put aside the cases that lie outside the mainstream of the main theme. PHP has a complex relationship with multitasking or concurrency. On the upper level PHP is constantly involved in multitasking - standard PHP installations on the server (like the Apache module) are used in a multitasking way. That is, multiple client applications (web browsers) can request the same PHP page at the same time, and the web server will return it to everyone more or less at the same time.
One web page does not block transmission of another, although they can interfere slightly with each other when dealing with limited resources such as server memory or network bandwidth. In this way, system requirement concurrency may well be tolerated by PHP-based solutions. In terms of implementation, PHP holds the Web server responsible for concurrency.
Client-side parallelism called Ajax has also caught the attention of developers in the past few years. While the meaning of Ajax has become somewhat obscure, one aspect of this technology is that the browser can perform computations at the same time and remain sensitive to user actions such as menu selections. It really is kind of multitasking. PHP coded Ajax does this, but without any special PHP involvement; Ajax frameworks for other languages work the same way.
A third example of concurrency that only scratches the surface of PHP is PHP / TK. PHP / TK is a PHP extension that provides portable Graphical User Interface (GUI) bindings to the PHP core. PHP / TK allows you to create desktop GUI applications written in PHP. Its event-driven aspects simulate a form of concurrency that is easy to learn and less error prone than working with threads. Again, concurrency is "inherited" from a complementary technology rather than a fundamental PHP functionality.
There have been several experiments to add threading support to PHP itself. As far as I know, none have been successful. However, the event-driven Ajax and PHP / TK frameworks show that events can even better express concurrency for PHP than threads can. PHP V5 proves it.
PHP V5 offers stream_select ()
In standard PHP V4 and earlier, all the work of a PHP application must be done sequentially. If the program needs to retrieve the price of an item from two commercial sites, for example, it asks for the first price, waits for a response, asks for the second price, and waits again.
What if a program could perform multiple tasks at the same time? It would be completed in only a fraction of the time required for consistent work.
First example
The new stream_select function, along with several of its friends, provides this capability. Consider the following example:
0) ($ s = stream_socket_client ("phaseit.net:80", $ errno, $ errstr, $ timeout, STREAM_CLIENT_ASYNC_CONNECT / STREAM_CLIENT_CONNECT); if ($ s) ($ sockets [$ id ++] = $ s; $ http_message = " GET / demonstration / delay? Delay = ". $ Delay." HTTP / 1.0 \ r \ nHost: phaseit.net \ r \ n \ r \ n "; fwrite ($ s, $ http_message);) else (echo" Stream ". $ id." failed to open correctly. ";) $ delay - = 3;) while (count ($ sockets)) ($ read = $ sockets; stream_select ($ read, $ w = null, $ e = null , $ timeout); if (count ($ read)) (/ * stream_select usually shuffles $ read, so we have to figure out which socket it is reading from. * / foreach ($ read as $ r) ($ id = array_search ($ r, $ sockets); $ data = fread ($ r, $ convenient_read_block); / * A socket can be read either because it has data to read OR because it is in an EOF state. * / if (strlen ($ data) = = 0) (echo "Stream". $ Id. "Closes at". Date ("h: i: s"). ". \ N"; fclose ($ r); unset ($ sockets [$ id]); ) else ($ result [$ id]. = $ data;))) else (/ * Ty maut means that * all * threads did not wait for a response. * / echo "Time-out! \ n"; break; ))?> |
If you run this program, you will see information similar to the following:
Program starts at 02:38:50. Stream 4 closes at 02:38:53. Stream 3 closes at 02:38:56. Stream 2 closes at 02:38:59. Stream 1 closes at 02:39:02. Stream 0 closes at 02:39:05. |
It is important to understand what is happening here. On the high level the first program makes several HTTP requests and receives pages that the Web server sends to it. While a real application would probably request several different Web servers (possibly google.com, yahoo.com, ask.com, etc.), this example passes all requests to our corporate server on Phaseit.net just for the sake of reducing complexity.
The requested Web pages return results after the variable delay shown below. If the program were to execute requests sequentially, it would take about 15 + 12 + 9 + 6 + 3 (45) seconds to complete. As shown in Listing 2, it actually takes 15 seconds to complete. Triple productivity is a great result.
This is made possible by stream_select - new function in PHP V5. Requests are initiated the usual way- opening several stream_socket_clients and writing a GET to each of them, which corresponds to http://phaseit.net/demonstration/delay?delay=$DELAY. When you request this URL in your browser, you should see:
Although the particular implementation in Listing 3 is for UNIX®, almost all of the scripts in this article apply equally well to PHP installations on Windows® (especially post-Windows 98) or UNIX. In particular, you can work with Listing 1 on any operating system. Linux® and Mac OS X are flavors of UNIX, and all of the code here will work on both systems.
Latency server requests are made in the following order:
delay = 15 delay = 12 delay = 9 delay = 6 delay = 3 |
The goal of stream_select is to get results as quickly as possible. In this case, the order of the delays is the opposite of the order in which the requests were made. After 3 seconds, the first page is ready to read. This part of the program is normal PHP code - in this case, with fread. Just like in another PHP program, reading could be done with fgets.
Processing continues in the same way. The program blocks at stream_select until the data is ready. Crucial is that it starts reading as soon as any connection has data, in any order. This is how the program implements multitasking or parallel processing of the results of multiple queries.
Note that there is no additional CPU load on the host computer. It is not uncommon for network programs to execute fread in this way soon to use 100% of the CPU. This is not the case here, since stream_select has the desired properties and responds immediately as soon as any read is possible, but it also minimally loads the CPU in standby mode between reads.
What you need to know about stream_select ()
This event-based programming is not trivial. Although Listing 1 has been reduced to the essentials, any coding based on callbacks or coordination (which is necessary in multitasking applications) will be less familiar than a simple procedural sequence. In this case, the biggest difficulty lies in the $ read array. Please note that this is a link; stream_select returns important information by modifying the contents of $ read. Just as pointers have a reputation for being a constant source of bugs in C, references seem to be the most difficult part of PHP for programmers.
This query technique can be used from any number of external Web sites, ensuring that the program receives each result as quickly as possible without waiting for other requests. In fact, this technique works correctly with any TCP / IP connection, not just the Web (port 80), that is, in principle, you can control the extraction of LDAP data, SMTP transmission, SOAP requests, etc.
But that's not all. PHP V5 handles various connections as "streams" rather than simple sockets. The PHP Client URL Library (CURL) supports HTTPS certificates, outbound FTP uploads, cookies, and more (CURL allows PHP applications to use different protocols to connect to servers). Since CURL provides a stream interface, the connection is transparent from the program's point of view. The next section explains how stream_select multiplexes even local computation.
There are a few caveats with stream_select. This function is not documented, so it is not covered even in new PHP books. Several of the code examples available on the Web just don't work or are not understandable. The second and third arguments to stream_select, which control the write and exception channels corresponding to the read channels in Listing 1, should almost always be null. With a few exceptions, the selection of these channels is a mistake. If you are not experienced enough, use only well-described options.
In addition, stream_select appears to be buggy due to at least, in PHP V5.1.2. Most significantly, the return value of a function cannot be trusted. Although I haven't debugged the implementation yet, my experience has shown that it is safe to test count ($ read) as in Listing 1, but that does not apply to the return value of stream_select itself, despite the official documentation.
PHP Local Concurrency
The example and most of the discussion above focused on how to manage multiple remote resources at the same time and get results as they appear, rather than waiting for each one to be processed in the order of the original request. This is undoubtedly an important application of PHP concurrency. Sometimes real applications can be accelerated tenfold or more.
What if the slowdown occurs closer? Is there a way to speed up getting results in PHP when processing locally? There are several. They are perhaps even less well known than the socket-oriented approach in Listing 1. There are several reasons for this, including:
- For the most part, PHP pages are fast enough. Better performance could be an advantage, but not enough to justify the investment in new code.
- Using PHP in Web pages can make partial code speedups irrelevant. Redistributing computation to get intermediate results faster is irrelevant when the only criterion is the speed of delivery of the Web page as a whole.
- Few local bottlenecks are controlled by PHP. Users may complain that retrieving information about account takes 8 seconds, but it may be limiting the processing of the database or some other resources external to PHP. Even if you reduce the PHP processing time to zero, it will still take more than 7 seconds to just search.
- Even fewer constraints lend themselves to parallel processing. Let's pretend that specific page calculates the recommended price for the listed common stock, and the calculations are complex and take many seconds. The computation can be sequential in nature. There is no obvious way to distribute it for "collaboration".
- Few PHP programmers understand PHP's potential for parallel processing. When talking about the possibility of parallelization, most of the programmers I met simply quoted the phrase "PHP does not work with threads" and returned to their established computation model.
Sometimes you can do better. Suppose a PHP page needs to compute two stock prices, perhaps compare them, and the host computer being used is multiprocessor. In this case, we can almost double the performance by assigning two separate, long-running computations to different processors.
In the world of PHP computing, such examples are rare. However, since I have not found an exact description anywhere else, I want to give an example of such acceleration here.
array ("pipe", "r"), 1 => array ("pipe", "w"), 2 => array ("file", $ error_log, "w")); $ cmd = "sleep". $ delay. "; echo" Finished with delay of ". $ delay." "."; $ handles [$ id] = proc_open ($ cmd, $ descriptorspec, $ pipes); $ streams [$ id] = $ pipes; $ all_pipes [$ id] = $ pipes; $ delay - = 2; ) while (count ($ streams)) ($ read = $ streams; stream_select ($ read, $ w = null, $ e = null, $ timeout); foreach ($ read as $ r) ($ id = array_search ($ r, $ streams); echo stream_get_contents ($ all_pipes [$ id]); if (feof ($ r)) (fclose ($ all_pipes [$ id]); fclose ($ all_pipes [$ id]); $ return_value = proc_close ($ handles [$ id]); unset ($ streams [$ id]);)))?> |
This program will display the following information:
Program starts at 10:28:41. Finished with delay of 1. Finished with delay of 3. |
The idea is that PHP started two independent subprocesses, received data from the first, and then from the second, although the latter started earlier. If the host computer is multiprocessor and operating system correctly configured, it takes care of assigning different subprograms to different processors. This is one way to take advantage of PHP's multiprocessing machines.
Summary
PHP supports multitasking. PHP does not support stream processing in the way other programming languages such as Java or C ++ do, but the examples above have shown that PHP has a higher potential for speeding up than most people realize.
So, friends, if you have reached this lesson, then you managed to either install local server, or buy a hosting that can work with PHP. Congratulations - this is a big step!
I will say briefly about PHP - this programming language is used all over the world and on it you can create sites of all levels of complexity, from business card sites to large portals. I think it is no longer a secret for many that the largest social networks facebook.com(from scratch to php) and vk.com(php engine) were written in PHP. So we draw conclusions and start work!)
How the code works
PHP Code processed on the server side... That is, there is no ready page. For example, the code instructs to collect data on how many users are registered on this moment on the site. Site visitor clicks on a link All users... He wants to get dynamic data, that is, those that are constantly changing. After the counting on the server is finished, the data will come from the server in the form of the generated HTML-code of the page with the number of users. As a result, after clicking a request on the link, the user receives the page. If you view the code of the resulting page, you can see only HTML, and the PHP code will not be available for viewing. Roughly speaking, PHP is an instruction to the server on how and from which blocks to make a page.What does PHP code look like and where to insert it?
PHP code can be embedded directly into HTML. PHP code is embedded in HTML pages using angle brackets and a question mark , however, you can limit yourself to parentheses with question marks код; ?> ... You will only need to change the file extension, for example, from .html on the .phpPHP Code(file index.php)
echo "Hello world!";
?>