Using node js with php

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.

Run node.js apps from PHP even on a shared hosting!

niutech/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

Ever wanted to deploy a node.js web app but didn’t have money for a dedicated node.js hosting or didn’t have time to set up a cloud PaaS? Have an existing PHP shared hosting based on the LAMP stack? Now you can run node.js on top of it!

Node.php originates from my ealier answer on Stack Overflow.

The node.php script installs an official node.js package, starts a hidden server on localhost:49999 with provided JS file and proxies all requests to it.

Warning! This is an alpha version, it may be insecure, run it at your own risk!

A PHP web hosting based on Linux with safe mode off and the following functions enabled: curl_exec , exec , passthru .

  1. Put the node.php file in your public_html (or similar) folder, then install node.js by browsing to: http://example.org/node.php?install .
  2. When succeeded, install your node.js app by uploading its folder or using npm: http://example.org/node.php?npm=install jt-js-sample .
  3. When everything goes fine, start your node.js instance by going to: http://example.org/node.php?start=node_modules/jt-js-sample/index.js .
  4. Now you can request your app by browsing to: http://example.org/node.php?path=optional/request/path . This will return a response from the running node.js app at http://127.0.0.1:49999/optional/request/path .
  5. Finally, stop your node.js server by loading: http://example.org/node.php?stop .

node.php[?path=some/path] — serves an already running node.js app with an optional request path (no leading slash)

The following commands require the ADMIN_MODE set to true (line 13 of node.php ):

node.php?install — downloads and extracts node.js into the node folder.

node.php?uninstall — removes the node folder

node.php?start=node_modules/jt-js-sample/index.js — starts a node.js server running the provided index.js file

node.php?stop — stops a running node.js server

node.php?npm=install jt-js-sample — runs npm install jt-js-sample (may be dangerous!)

Here is a live demo on a dirt cheap PHP shared hosting.

In order to troubleshoot any problems with running node.php, connect to your host using SSH and run exact node.php commands manually:

  1. Go to your document root directory (often ~/public_html/ ) and check if node directory exists there.
  2. If yes, go to step 3, otherwise download node for your architecture:
wget http://nodejs.org/dist/node-v5.7.0-linux-x86.tar.gz tar -xzf node-v5.7.0-linux-x86.tar.gz mv node-v5.7.0-linux-x86/ node/ rm -f node-v5.7.0-linux-x86.tar.gz 

Node.js is developed by Joyent et al. under the MIT License.

Node.php is developed by Jerzy Głowacki under the MIT License.

About

Run node.js apps from PHP even on a shared hosting!

Источник

Как связать Node.js и PHP?

Допустим есть сайт на php, необходимо на ноде запустить websocket который будет реагировать на события на клиенте и передавать информацию на сервер php и обратно, как это можно реализовать?

Оценить 1 комментарий

gzhegow

var ipaddress = '127.0.0.1'; var port = 9000; function testWebSocketServerAndNotification() < var WebSocketServer = require('ws').Server; var path = require('path'); var notifier = require('node-notifier'); var message = 'Hello from Node.js'; var path2Image = 'e:\\MyWork\\NodeWorkBench\\TestApp\\image\\infoBalloon.png'; var wss = new WebSocketServer(); wss.broadcast = function(data) < for (var i in this.clients) < this.clients[i].send(data); >>; wss.on('connection', function(ws) < ws.on('message', function(message) < wss.broadcast(message); notifier.notify (< title: 'My notification', message: `Message: '$'`, sound: true, time: 5000, wait: true, icon: path.join(__dirname, 'image', 'notificationIcon.png'), contentImage: path2Image, >); >); >); console.log('Слушаем адрес ' + ipaddress + ' на порте: ' + port + ' . '); >
 if ($socketio->send("127.0.0.1", 9000, iconv("CP866", "UTF-8", trim($input)))) < echo iconv("UTF-8", "CP866", "Сообщение отправлено. Можете продолжать:\n"); >else < echo iconv("UTF-8", "CP866", "Какой-то сбой :(\n"); >> exit("Jobe done"); ?>

bingo347

MarcusAurelius

Проще всего этим приложениям обмениваться HTTP запросами на localhost, но при большой интенсивности таких запросов, или при необходимости оптимизировать время отклика — это становится не эффективно. Тогда есть куча других средств IPC, сокеты, мьютексы и семафоры, файловая система, файлы отображаемые в память (или разделяемая память), через базу данных, через шину событий и очередь сообщений MQ системы (ZeroMQ, ActiveMQ, RabbitMQ, Redis, AMQP и т.д.). Но все эти способы не сильно улучшат ситуацию по сравнению с HTTP, потому, что PHP приложение все время завершается и стартует заново, в общем — долго не живет. При каждом запуске оно опять будет устанавливать соединение или с шиной событий или с базой или сокеты открывать к постоянно находящемуся в памяти Node.js приложению, которое живет в памяти долго. Все перечисленные способы хороши для взаимодействия двух долгоживущих приложений, которые могут установить соединение и использовать его долго, и собственную память держать долго, а через соединение просто синхронизировать состояние нескольких процессов. А в случае с PHP, обычных HTTP запросов хватит с головой, высоконагруженную системы Вы все равно не построите на связке PHP+Node.js, а вот времени сэкономите, если сделаете как можно проще.

Источник

Using PHP with Node.js in Windows

PHP and Node.js are two coding standards made for Web purposes. Node.js is not a language by itself and is a new implementation of Javascript and a different filosophy in programming.
PHP adopted some features of Node like the package manager NPM on Composer and the assincronicity make the bulk of some frameworks like Laravel
. Node.js with the help of libraries can do almost the same complete languages like Python. The new Electron.JS for desktop applications uses Node behind the scenes. It’s the base for some applications like VS Code or the Spotify desktop client. PHP is not for the desktop, and it remains closed in the same purposes since it was created in 1995 by Rasmus Lerdorf. Using the node standalone server provided by the http module and the FastCGI PHP client it’s possible to serve PHP files from within node. Let me show how. PHP 5.4 introduced the new standalone builtin web server in PHP, its possible to make the node server proxify the requests and responses of PHP, but it’s not the way we are doing the things here. The FastCGI was introduced to add flexibility and standardization to what was a plethora of ways that common binary runtimes like bash could serve webpages. Before PHP arrived, languages like Perl were used to generate dynamic web content. For some web servers that do not come with access through a shared library, PHP-CGI (on Linux, PHP-FPM, from FastCGI PHP Manager) is the way to do it. The front web server receives a request for a PHP script and makes a request to the PHP CGI client, including details like web script name, the string query, and an eventual request body. The CGI client answers with HTML or other format outputted from PHP. Nginx and Lighttpd use this way to server PHP web content, NodeJS can also interface with FastCGI through the node php-fpm module. The code is:

const phpFpm = require ('php-fpm'); const php = phpFpm(< host: '127.0.0.1', port: 9123, documentRoot: __dirname + '\\www', >); 

The PHP CGI client must be already listening at the port 9123 and was started with the args: php-cgi -b 127.0.0.1:9123 . On Linux it’s php-fpm and the args should be the same, but I haven’t tried it. Here my document root is under a subdir in the project root. I do this because I’m using configuration files in the root and conf dirs. Web visitors doesn’t may have access to these. Name the file server.js , launch the node web server with node server.js , in the root dir at www/ you can have the following PHP code:

 echo "

Hello, today's date is " . date("Y-m-d") . " and more!

"
;

PHP CGI Output in Node

Name this file index.php , save it to the www , and if you navigate to http://localhost:3000/index.php you should see something like: The complete code of server.js is below:

const http = require ('http'); const fs = require ('fs'); const phpFpm = require ('php-fpm'); const php = phpFpm( host: '127.0.0.1', port: 9123, documentRoot: __dirname + '\\www', debug: false >); const server = http.createServer((req, res) =>  let url = req.url; let method = req.method; console.log('Serving request: ' + method + ' ' + url ); if (url == '/')  readAndServe('index.html', res); > else if (url.endsWith('.php'))  php(req,res); > else  readAndServe(url, res); > >).listen(3000, '127.0.0.1',function()  let address, port> = server.address(); console.log('Server started at '+ address+ ':'+ port); >); // Helper function function readAndServe(path, res)  fs.readFile('www/' + path, function (err, data)  if (err)  console.error(err); res.writeHead(404,  'Content-Type': 'text/plain' >); data = '404 Not Found\n'; > res.end(data); >); > 

Источник

moeiscool / README.md

You must be root to follow the steps in this guide.

sudo apt-get install mariadb-server mariadb-client 
sudo systemctl stop mariadb.service sudo systemctl start mariadb.service sudo systemctl enable mariadb.service 
sudo mysql_secure_installation 

The choices you should choose are as follows:

- Enter current password for root (enter for none): Just press the Enter - Set root password? [Y/n]: Y - New password: Enter password - Re-enter new password: Repeat password - Remove anonymous users? [Y/n]: Y - Disallow root login remotely? [Y/n]: Y - Remove test database and access to it? [Y/n]: Y - Reload privilege tables now? [Y/n]: Y 
sudo systemctl restart mariadb.service 
CREATE USER 'mysqlConnectionUserName'@'localhost' IDENTIFIED BY 'new_password_here'; GRANT ALL ON * TO 'mysqlConnectionUserName'@'localhost' IDENTIFIED BY 'user_password_here' WITH GRANT OPTION; FLUSH PRIVILEGES; 
  1. At this point you may want to import your SQL database for any websites you want to use. While still in the MariaDB client you can run the following to import .sql files.

Installing a PHP Website using Node.js Express Web Server

You must be root to follow the steps in this guide.

curl -sL https://deb.nodesource.com/setup_9.x | sudo -E bash - sudo apt-get install -y nodejs php sudo apt install php-fpm php-common php-mbstring php-xmlrpc php-soap php-gd php-xml php-intl php-mysql php-cli php-mcrypt php-ldap php-zip php-curl php-cgi 
mkdir /home/wordpress cd /home/wordpress 
wget https://gist.githubusercontent.com/moeiscool/876e64a9725fa07ac9e6852e1001f1d5/raw/e4a8c72721e48c13a22a6894a56e766481fa5eed/runPhpSite.js -O runPhpSite.js 
  1. Put the PHP website inside a folder called public . The full path should be /home/wordpress/public . Your folder structure should be similar to the following.
- home | - wordpress | |- runPhpSite.js | |- public 

Источник

Читайте также:  Как питоны едят курицу
Оцените статью