search
HomeBackend DevelopmentPHP TutorialPHP server push technology chat room

  1. //chat.php
  2. header('cache-control: private');
  3. header('Content-Type: text/html; charset=utf-8');
  4. ?>
复制代码

保存用户提交的聊天内容 简易版本:

  1. $content = trim($_POST['content']);
  2. if ($content) {
  3. $fp = fopen('./chat.txt', 'a');
  4. fwrite($fp, $content . "n");
  5. fclose($fp);
  6. clearstatcache();
  7. }
  8. ?>
复制代码

主要的HTTP长连接部分,chat_content.php文件:

  1. header('cache-control: private');

  2. header('Content-Type: text/html; charset=utf-8');
  3. //测试设置30秒超时,一般会设置比较长时间。
  4. set_time_limit(30);
  5. //这一行是为了搞定IE这个BT
  6. echo str_repeat(' ', 256);
  7. ob_flush();

  8. flush();
  9. $fp = new SplFileObject('./chat.txt', 'r+');

  10. $line = 0;
  11. $totalLine = 0;
  12. while (!$fp->eof()) {
  13. $fp->current();
  14. $totalLine++;
  15. $fp->next();
  16. }
  17. $fp->seek($totalLine);

  18. $i = $totalLine - 1;
  19. while (true) {
  20. if (!$fp->eof()) {
  21. if ($content = trim($fp->current())) {
  22. echo '
    ';
  23. echo htmlspecialchars($content);
  24. echo "
";
  • flush();
  • $fp->next();
  • $i++;
  • }
  • } else {
  • $fp->seek($i - 1);
  • $fp->next();
  • }
  • {
  • //这里可以添加心跳检测后退出循环
  • }
  • usleep(1000);
  • }
  • ?>
  • 复制代码

    Code description: 06. Set a timeout. Since you need to maintain a long HTTP connection, this time must be longer. It may take several hours. The article mentioned above also explains that only two such long HTTP connections can be opened. Due to browsing device limitations. in addition In fact, even if you set a never timeout, the configuration file of the server part (such as Apache) may also set the maximum waiting time for HTTP requests, so the effect may not be what you think. Generally, the default may be 15 minutes. time out. if If you are interested, you can try to modify it yourself.

     09. A section of blank space is output here, mainly because the manual has explained that the IE browser will not directly output the first 256 characters, so we first output some blank space casually to allow the subsequent content to be output, and possibly other Browsers also have other For browser settings, you can check the description of the frush function in the PHP manual for details. The next 11 and 12 lines are to force these whitespace characters to be output by the browser.

     13. ~ 20. The main purpose here is to calculate the number of file lines so that the content can be read from the end of this line.

     The following while loop is an infinite loop, which is to output the file content in a loop. Each time it is judged whether it has reached the end of the file. If a user writes to the file, the current detection is definitely not the end of the file, so the line is read and output. Otherwise it will refer to The needle moves forward one line and continues to cycle, waiting 1000 microseconds each time,

     39. If a long connection is maintained, even if the client is disconnected, the server may not know that the client has been disconnected, so some heartbeat records may be needed here, such as each user keeping a heartbeat flag, each grid Update in a few seconds The last heartbeat time, when the last time detected has not been updated for a long time, this infinite loop is launched and the HTTP connection is closed.

    Demo Example 2: Traditional B/S structure applications all use "client pull" to achieve data exchange between the client and the server. This article will implement a simple idea of ​​a server-pushed PHP chat room by combining Ticks.

    PHPer, especially those who have used set_cookie, header, must have seen this prompt message: "Warning: Cannot modify header information - headers already sent by...", this is because communication is through the HTTP protocol , the data packet will contain two parts, one is Header and the other is data. Generally speaking, the Header part is started first, and the length of the Data part is specified in the Header part, and then \r\n\r\n is used to indicate the end of the header part, followed by the Data part.

    When there is any output, the Header part is sent. At this time, if you use the header function to change some domain information of the Header part, you will get the above prompt information. A simple solution is to use output_buffering. Let it cache the server's output and don't send the header part to the client too early. So, if output_buffering is not used, can it be achieved that whenever the server has output, it is immediately sent to the client? Do the following experiment:

    1. //Set output_buffering=0 in php.ini or use ob_end_flush() to turn off caching
    2. set_time_limit(0);
    3. for($i=0;$i echo "Now Index is :". $i;
    4. sleep(1);
    5. }
    6. ?>
    Copy the code

    It turns out that you still have to wait until the script is fully executed before you can see everything at once the result of. why? This is because it only solves the caching problem, but there is also a buffering problem. PHP will buffer the output of the program. Therefore, you still need to call flush() at this time to force PHP to send all program output to the client.

    1. //Set output_buffering=0 in php.ini

    2. ob_end_flush();//Turn off caching
    3. set_time_limit(0);

    4. for($i=0;$i echo "Now Index is :". $i;
    5. flush();
    6. sleep(1);
    7. }
    8. ?>> ;
    Copy code

    Have you seen that the server data is constantly being displayed?

    There are relationships between several concepts, and I’ll add them here: Using ob_start() in the code is equivalent to using output_buffering=on in php.ini, using the server cache. Using ob_end_flush() in the code is equivalent to using output_buffering = false in php.ini to turn off the server cache. 1 2 Next Page Last Page



    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

    PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

    What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

    The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

    Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

    PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

    How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

    ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

    How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

    The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

    How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

    The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

    What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

    The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

    How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

    Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.