Table of Contents
1. Description of the problem
2. Solution
Home Backend Development PHP Tutorial PHP service nginx cannot use file_get_contents solution

PHP service nginx cannot use file_get_contents solution

Sep 07, 2018 pm 02:35 PM
fastcgi nginx php php-fpm windows

I built a local development service environment in a Windows environment and used Nginx as a service. However, an error occurred when using file_get_contents() to obtain the local link. The following article will introduce to you the solution to this problem.

1. Description of the problem

I built a local development service environment in a Windows environment and used Nginx as a service, but when using file_get_contents() to obtain the local link http://127.0. 0.1/index.php, such an error occurred:

file_get_contents(http://127.0.0.1/index.php) [<a href=&#39;function.file-get-contents&#39;>function.file-get-contents</a>]: failed to open stream: HTTP request failed!
Copy after login

The local computer PHP environment is: nginx php mysql; so I found this article and took a note, record it!

In the past two days, I have been working on the file_get_contents request of nginx fastcgi under windows. I think many students have encountered no pressure when file_get_contents requests http/https php files on the external network, such as echo file_get_contents(‘http://www.baidu.com’), which will display Baidu’s page. But when you request the PHP service on the localhost/127.0.0.1 local network, it always shows a timeout. No matter how long you set the request time and the script running time, you cannot return data, such as file_get_contents('http://localhost/phpinfo.php' ). However, there is no problem at all when you try to request static files such as html. What is the reason? !

First of all, we know that when file_get_contents/curl/fopen opens an http request based on tcp/ip, the request data is sent to nginx, and nginx entrusts php-cgi (fastcgi) to process the php file. In general, fastcgi After processing a PHP request, the end signal will be released immediately, waiting for the next processing request (of course, there are also cases where the program freezes and keeps occupying resources). Open nginx.conf, we see the following line:

location ~ .php {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  d:/www/htdocs$fastcgi_script_name;
        include        fastcgi_params;
}
Copy after login

It has been clearly seen above that all files ending with php are processed by fastcgi, and there is also a sentence in the php.ini configuration file:

cgi.force_redirect = 1
Copy after login

indicates that all PHP programs can safely force redirection to CGI for processing.

But in windows, how does local 127.0.0.1:9000 contact php-cgi? ! The answer is to add a php-cgi process and use it to listen on 127.0.0.1:9000. Through the controller command:

RunHiddenConsole.exe D:/www/php/php-cgi.exe  -b 127.0.0.1:9000 -c C:/WINDOWS/php.ini
Copy after login

we can start a php-cgi.exe process to listen for requests from 127.0.0.1:9000 when starting windows. Open netstat -a under the dos command and you can see that port 9000 under the local computer is in the listening state (that is, empty, if no request is sent).

Okay, let’s talk about why the results cannot be returned when using the file_get_contents(), curl(), and fopen() functions in PHP to access localhost. Let's try adding the file_get_contents('http://127.0.0.1/phpinfo.php') statement to index.php to send a request to phpinfo.php. At this time, the status indicator in the browser keeps spinning, indicating that it has been At work. Open the netstat command in Dos, and you can see that the status of the local 9000 port is: ESTABLISHED, indicating that the process is being processed online. In fact, here we have sent two http-based php requests to nginx at the same time, one is to parse index.php, and the other is phpinfo.php, so the contradiction comes out, because our windows system only loads one http process, therefore, it cannot process two php requests at the same time. It can only process the first request (index.php) first, while index.php is waiting for the processing result of phpinfo.php, and no one is helping it process phpinfo.php. request, because it has been waiting for index.php to release the end signal, thus causing the program to block and fall into an infinite loop. So we see the browser's status indicator spinning all the time. The reason for Curl() and fopen function is the same.

2. Solution

Once we find the reason, we also have a solution.

First, add an http request to the system. When another request is loaded in a php-cig, it can allocate other http to handle the additional php request. At this time, you need to assign a different port to another http server, such as 8080. The case of nginx is as follows:

http {  
    server {  
        listen          80;  
        server_name     127.0.0.1;  
        location / {  
            index index.php;  
            root  /web/www/htdocs;  
        }  
    }  
    server {  
        listen          8080;  
        server_name     127.0.0.1;  
        location / {  
            index index.html;  
            root  /web/www/htdocs;  
        }  
    }  
    include    /opt/nginx/conf/vhosts/php.conf;  
}
Copy after login

In this way, ports 80 and 8080 can handle different programs respectively, such as:
test.php

 echo file_get_contents('http://localhost:8080/phpinfo.php');
Copy after login

Of course, there are more choices under *unix , such as fork.

As a reminder, some people on the Internet said that by removing the http:// protocol mark in the address and using relative addresses, function checks can be circumvented. Is this actually the case? ! When using file_get_contents('phpinfo.php'); in index.php, we can see that the function outputs the source code of phpinfo.php, which is equivalent to file_get_contents('file:c:wwwphpinfo.php');, which actually The above just reads your text content, because the file_get_contents() function first processes the file protocol, and curl directly reports an error and cannot be parsed. Therefore these people are simply unlearned liars.

Some people also proposed to modify the hosts file and add the localhost www.xxx.com alluding relationship. The function accesses the local PHP through www.xxx.com. This is actually a folk remedy that does not cure the root cause, because it only facilitates the computer’s DNS resolution. , finally www.xxx.com is handed over to 127.0.0.1, and the latter is handed over to the only http, which is still blocked.

Related recommendations:

Solution to the problem that the file_get_contents function cannot be used

How to connect Nginx server with PHP and parse Nginx log

The above is the detailed content of PHP service nginx cannot use file_get_contents solution. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP and the Web: Exploring its Long-Term Impact PHP and the Web: Exploring its Long-Term Impact Apr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

See all articles