PHP与Node.js服务器间收发数据方案咨询:无需cURL或中转服务器
Hey there! I’ve got a straightforward solution that checks all your boxes—no cURL, no third-party middlemen, and client-side JS can catch Node.js events easily. Let’s dive in:
We’ll set up two key components to make this work:
- A direct communication channel between PHP and Node.js using native PHP HTTP functions (no cURL) and a Node.js HTTP server.
- A WebSocket server in Node.js to push real-time events to your client-side JavaScript.
This way, when PHP sends data or files to Node.js, Node can process the content and immediately fire an event that the client JS picks up right away.
We’ll use Node’s built-in http module for the PHP endpoint and the lightweight ws library for WebSocket functionality (if you want zero dependencies, I can share a raw WebSocket implementation too).
First, install ws if you haven’t already:
npm install ws
Here’s the Node.js server code (server.js):
const http = require('http'); const WebSocket = require('ws'); // HTTP server to accept requests from PHP const httpServer = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/php-data') { let incomingData = ''; req.on('data', chunk => { incomingData += chunk.toString(); }); req.on('end', () => { // Parse data from PHP (supports strings or file content) const parsedData = JSON.parse(incomingData); console.log('Received from PHP:', parsedData); // Broadcast event to all connected WebSocket clients wss.clients.forEach(client => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ eventType: 'php-data-received', data: parsedData })); } }); // Send success response back to PHP res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({status: 'success'})); }); } else { res.writeHead(404); res.end(); } }); // Attach WebSocket server to the same HTTP server const wss = new WebSocket.Server({ server: httpServer }); wss.on('connection', (ws) => { console.log('Client connected to WebSocket'); ws.on('close', () => { console.log('Client disconnected'); }); }); // Start server on port 3000 httpServer.listen(3000, () => { console.log('Node.js server running at http://localhost:3000'); });
We’ll use PHP’s native stream_context_create and file_get_contents to send HTTP requests—no cURL required.
Sending a String Message:
<?php $nodeEndpoint = 'http://localhost:3000/php-data'; // Prepare data to send $messageData = [ 'type' => 'text', 'content' => 'Hey Node.js, this is PHP talking!' ]; // Create HTTP context for POST request $httpContext = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode($messageData) ] ]); // Send request to Node.js $response = file_get_contents($nodeEndpoint, false, $httpContext); $responseData = json_decode($response, true); echo $responseData['status'] === 'success' ? 'Message sent to Node.js!' : 'Failed to send message.'; ?>
Sending a File:
We’ll encode the file content as base64 to include it in the JSON payload:
<?php $nodeEndpoint = 'http://localhost:3000/php-data'; $targetFile = './sample-image.jpg'; // Read file content and prepare data $fileContent = file_get_contents($targetFile); $fileData = [ 'type' => 'file', 'fileName' => basename($targetFile), 'content' => base64_encode($fileContent) ]; // Create HTTP context $httpContext = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode($fileData) ] ]); // Send file data to Node.js $response = file_get_contents($nodeEndpoint, false, $httpContext); $responseData = json_decode($response, true); echo $responseData['status'] === 'success' ? 'File sent successfully!' : 'File upload failed.'; ?>
Connect to the WebSocket server and listen for incoming events. Here’s a simple HTML file (client.html):
<!DOCTYPE html> <html> <body> <h2>Real-Time Event Log</h2> <div id="event-container"></div> <script> // Connect to Node.js WebSocket server const socket = new WebSocket('ws://localhost:3000'); socket.onopen = () => { console.log('Connected to Node.js WebSocket'); }; // Listen for events from Node.js socket.onmessage = (event) => { const eventData = JSON.parse(event.data); const logContainer = document.getElementById('event-container'); if (eventData.eventType === 'php-data-received') { const logItem = document.createElement('div'); logItem.style.padding = '8px'; logItem.style.borderBottom = '1px solid #eee'; if (eventData.data.type === 'text') { logItem.textContent = `Text Message: ${eventData.data.content}`; } else if (eventData.data.type === 'file') { logItem.textContent = `File Received: ${eventData.data.fileName} (size: ${atob(eventData.data.content).length} bytes)`; } logContainer.appendChild(logItem); } }; socket.onclose = () => { console.log('Disconnected from WebSocket'); }; </script> </body> </html>
- Start the Node.js server:
node server.js - Open
client.htmlin a browser—it will connect to the WebSocket automatically. - Run either PHP script (string or file) via your PHP server.
- Watch the client page: it will instantly display the event sent from Node.js after receiving data from PHP.
- If you want to avoid the
wslibrary, you can implement WebSocket manually using Node’shttpmodule by handling theUpgradeheader—just let me know if you need that code! - For very large files, consider using chunked transfer instead of base64, but this approach works for most common use cases.
- Ensure
allow_url_fopenis enabled in your php.ini (it’s usually enabled by default) to let PHP send outgoing HTTP requests.
内容的提问来源于stack exchange,提问作者Gen

