Node js php fpm

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Node.js interfacing with PHP-FPM through FastCGI

License

davidcoallier/node-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Inline PHP Server Running on Node.js

Be worried, be very worried. The name NodePHP takes its name from the fact that we are effectively turning a nice Node.js server into a FastCGI interface that interacts with PHP-FPM.

This is omega-alpha-super-beta-proof-of-concept but it already runs a few simple scripts. Mostly done for my talks on Node.js for PHP Developers this turns out to be quite an interesting project that we are most likely be going to use with Orchestra when we decide to release our Inline PHP server that allows people to run PHP without Apache, Nginx or any webserver.

Yes this goes against all ideas and concepts of Node.js but the idea is to be able to create a web-server directly from any working directory to allow developers to get going even faster than it was before. No need to create vhosts or server blocks ore modify your /etc/hosts anymore.

This node.js module is made for the sole purpose of my conference talk but also to allow developers to get started with PHP even faster than the usual. After installing this node-module, developers need to make sure they have PHP-FPM running somewhere on their system. If it is, they will be able to go to any of their web-directory (that the FPM user has access to) and simply type node php and from there they will see a nice little output that looks like this:

bash$~ PHP Server is now running on port 9001 Incoming Request: GET /test.php --> Request Response Status Code: "200" 

This is going to be running in the browser allowing you to develop and test your applications faster. Hopefully you will end up forking the project and helping out because I do not have enough time to do all I would want to do with this thing.

It allows you to go into a directory, type «node-php» and have a running webserver that serves PHP. Happy.

Well this is a bit tricky, there are a few things you will need in order to get this thang running:

  • You need a running PHP-FPM server.
  • You need to have Node.js installed with NPM
  • Install node-fastcgi-parser ( https://github.com/billywhizz/node-fastcgi-parser )
  • Then you git clone git://github.com/davidcoallier/node-php.git , then you git submodule init , then you git submodule update , and npm install

For this beta version, we assume that you are running FPM off localhost on port 9000 . If you are running through a socket you may want to make your own script that looks like this:

var php = require('nodephp'); php.nodephp(< fcgi: < port: '/tmp/php-fpm.sock', host: null, >, server: < port: 9998 >>); 

Please note that the sock connection has not been tested yet. All that has been tested is connecting to a different FastCGI port and starting the server on a different port like such:

var php = require('nodephp'); php.nodephp(< fcgi: < port: 9001, host: 'localhost', >, server: < port: 9111 >>); 

You will realise rapidly enough that only running this is quite useless as it does not serve static files and such. This is why the node-php code has the abiliyt to define blocks — albeit simple blocks. They are defined in the second argument of the nodephp call:

var php = require('nodephp'); php.nodephp(< fcgi: < port: 9001, host: 'localhost', >, server: < port: 9111 >>, < "\.(js|css|png|jpg|jpeg|gif|txt|less)$": php.NODEPHP_TYPE_STATIC, "\.php$": php.NODEPHP_TYPE_FCGI, "index": "index.php" >); 
NODEPHP_TYPE_STATIC: Static files that do not need to go through the fastcgi handler (`fastcgi_pass`) NODEPHP_TYPE_FCGI: Files you do send through the FCGI handler. 

If you want more simple using the default localhost:9000 for the FCGI handler:

var php = require('nodephp'); php.nodephp(<>, < "\.(js|css|png|jpg|jpeg|gif|txt|less)$": php.NODEPHP_TYPE_STATIC, "\.php$": php.NODEPHP_TYPE_FCGI, "index": "index.php" >); 

There are a few very important issues right now:

  • There is no POST handling. I’m not that far in the FCGI specs yet — need to find how to send data (post data)
  • There is no base url. If you include ../../../../poop it will try to load it and most likely will fail.
  • If you try to load a file that the PHP-FPM worker does not have access to, it will fail silently and you will swear. A lot. By silently I mean, it will give you a 404 even though the files do exist.

This is an ugly prototype and if you run this in production you are most likely mentally challenged (Not that it’s a bad thing..) but I take no responsibility for what you do with this. Moreover, this goes against everything Node.js stands for. So realise that.

Released under the New BSD License.

Copyright (c) 2011 David Coallier

About

Node.js interfacing with PHP-FPM through FastCGI

Источник

Как настроить совместную работу PHP-FPM и Node.JS через Nginx?

Сайт на Angular состоит из пары страниц с php-кодом для того чтобы была авторизация. Остальная информация должна загружаться через socket.io. Socket.io должен обращаться к 4 разным портам на которых висит 4 скрипта node.js. При загрузке страницы все пути с socket.io загружаются с ошибкой 404.
Так же используется CDN Cloudflare.

upstream php-fpm < server unix:/var/run/php5-fpm.sock; >server < listen 80; root /var/www/example.com/public_html; index index.php index.html index.htm; server_name example.com sofast.example.com *.example.com; rewrite ^([^.]*[^/])$ $1/ permanent; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; gzip on; gzip_disable "msie6"; gzip_comp_level 6; gzip_min_length 1100; gzip_buffers 16 8k; gzip_proxied any; gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/javascript application/json application/xml+rss; location / < index index.php index.html index.htm; try_files $uri $uri/ =404; fastcgi_pass php-fpm; include fastcgi_params; fastcgi_split_path_info ^(.+?\.php)(/.*)?$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name; set $path_info $fastcgi_path_info; fastcgi_param PATH_INFO $path_info; fastcgi_param SERVER_SIGNATURE nginx/$nginx_version; fastcgi_index index.php; >location ~* .(html|js|css|htm|jpg|jpg|gif|png|woff|woff2|ttf|mp3|svg|xml|ico|conf|eot|json|log|yml|txt|steamd|otf)$ < root /var/www/example.com/public_html; error_page 404 = 404; ># 4 порта для Node.js location /node8303 < proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8303; proxy_redirect off; >location /node8304 < proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8304; proxy_redirect off; >location /node8305 < proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8305; proxy_redirect off; >location /node8306 < proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:8306; proxy_redirect off; >location ~* "/\.(htaccess|htpasswd)$" < deny all; return 404; >>

customtema

Я сделал разные виртхосты, и все заработало.

server < root /home/user/path/www; index index.html index.php; error_log /home/user/path/error.log; charset utf8; source_charset utf8; server_name site.ru www.site.ru; location / < # First attempt to serve request as file, then # as directory, then fall back to index.html try_files $uri $uri/ /index.html /index.php; >#error_page 404 /404.html; # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ < fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /home/user/path/www$fastcgi_script_name; include fastcgi_params; ># deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht < deny all; >>

Источник

Node js php fpm

node.js run php scripts via phpfpm

NPM

var PHPFPM = require('node-phpfpm');
var phpfpm = new PHPFPM(
host: '127.0.0.1',
port: 9000,
documentRoot: __dirname
>);
phpfpm.run('test.php', function(err, output, phpErrors)
if (err == 99) console.error('PHPFPM server error');
console.log(output);
if (phpErrors) console.error(phpErrors);
>);
var phpfpm = new PHPFPM(configObject);

configObject may have the following keys:

  • documentRoot optional [string] the document root folder of PHP scripts. must ends with /
  • host optional [string] the ip or host name of php-fpm server (default: 127.0.0.1)
  • port optional [int] the port of php-fpm server ( default: 9000 )
  • sockFile optional [string] use the unix sock file instead of 127.0.0.1:9000 to connect php-fpm server

available keys in options object

  • uri [string] path to your phpfile
  • url [string] alias of uri
  • method optional [string] GET or POST (default: GET)
  • form optional [object] form_data that will be send with content-type: application/x-www-form-urlencoded
  • json optional [object] json data that will be send with content-type: application/json
  • body optional [string] raw post body data
  • contentType optional [string] the content-type header
  • contentLength optional [string] the content-length header

if you send a string as options , it will be converted to:

uri: "the string value", method: 'GET' >
function(err, output, phpErrors)
// if err === 99, means php-fpm error
// it may be lost php-fpm connection or too many connections
// otherwise it will always equal to false
// output is the stdout of php scripts
// phpErrors is the php errors detail string
// php will output some errors, but that does not mean the request fails
// if you turn on display_errors in your php.ini, the phpErrors content will also be found in the output string
console.log(err, output, phpErrors);
>

Simple php request with no parameters

phpfpm.run('test1.php', function(err, output, phpErrors)
console.log(err, output, phpErrors);
>);
print_r($_GET);
// Array
// (
// [a] => b
// [c] => d
// [e] => Array
// (
// [0] => 1
// [1] => 2
// )
// )
?>

Send form data via POST method

phpfpm.run(
uri: 'test.php',
form:
a:'a',
b:'b'
>
>, function(err, output, phpErrors)
console.log(err, output, phpErrors);
>);
print_r($_POST);
// Array
// (
// [a] => a
// [b] => b
// )
?>

Send json data with POST method

phpfpm.run(
uri: 'test.php',
json:
a:'a',
b:'b'
>
>, function(err, output, phpErrors)
console.log(err, output, phpErrors);
>);
echo file_get_contents('php://input');
//
?>

Send form data with GET method

phpfpm.run(
uri: 'test2.php',
method: 'GET',
form:
a:'a',
b:'b'
>
>, function(err, output, phpErrors)
console.log(err, output, phpErrors);
>);
print_r($_GET);
// Array
// (
// [a] => a
// [b] => b
// )
?>

Send form data and query string with GET method

phpfpm.run(
uri: 'test2.php?c=cc',
method: 'GET',
form:
a:'a',
b:'b'
>
>, function(err, output, phpErrors)
console.log(err, output, phpErrors);
>);
print_r($_GET);
// Array
// (
// [c] => cc
// [a] => a
// [b] => b
// )
?>

Send raw body data with POST method

phpfpm.run(
uri: 'test5.php',
body: 'abc123'
>, function(err, output, phpErrors)
console.log(err, output, phpErrors);
>);
echo file_get_contents('php://input');
// abc123
?>

This project is based on the great work of node-fastcgi-client written by LastLeaf. LastLeaf/node-fastcgi-client

Источник

Node js php fpm

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

const http = require('http')
const phpFpm = require('php-fpm')
const serveStatic = require('serve-static')
const php = phpFpm() // Optional: parameters for fastcgi-client
const serve = serveStatic(__dirname)
const server = http.createServer(function (req, res)
if (req.url.match(/\.php(\?.*)?$/))
php(req, res)
> else
serve(req, res)
>
>)
server.listen(8080)
const express = require('express')
const phpFpm = require('php-fpm')
const app = express()
app.use(phpFpm())
app.listen(8080)

The available parameters for php-fpm are:

phpFpm(
userOptions =
// Parameters for fastcgi-client
host: '127.0.0.1',
port: 9000,
documentRoot: __dirname,
skipCheckServer: true
>,
customParams =
// Headers for php-fpm (automatically set)
uri, // REQUEST_URI
document, // DOCUMENT_URI
query, // QUERY_STRING
script // SCRIPT_FILENAME
>
)

Parameters for fastcgi-client are available here.

There is an implementation of the rewrite module to handle routes the traditional nginx/Apache way.

const phpFpm = require('php-fpm')
// Route rewrite for Phalcon framework
const php = phpFpm(
rewrite: [
rule: /.*/, // Default rule, can be omitted
replace: '/index.php?_url=$0'
>
]
>)

Источник

Читайте также:  PHP MySQL connection example
Оцените статью