Php exec node js

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.

Execute PHP function within NodeJS application

License

iqbalfn/exec-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

Execute PHP function within NodeJS application

let execPhp = require('exec-php'); execPhp('path/to/file.php', '/usr/bin/php', (err, php, out) =>  // the `php` argument is now contains all php defined functions php.my_func(arg1, arg2, (err, res, out, print) =>  // `res` argument is now hold the returned value of `my_func` php function // `print` hold anything that get printed during calling the `my_func` function >) >)
  1. phpfile::string Path to user php file.
  2. phpbin::string Path to engine php binary file.
  3. callback::function A function to call after populating the php functions.

The callback function will be called with below arguments:

  1. error::mixed The error message.
  2. php::object The php object that hold all php defined functions.
  3. printed::string All printed string while populating php functions.

All user defined function on php engine will be appended to php argument of the caller. The function will be lower case. You can now call the function normally with additional last argument is the callback function to get response of the php functions call with below arguments:

  1. error::mixed Error message
  2. result::mixed Returned content of user php function
  3. output::string Printed string on requiring the php file.
  4. printed::string Printed string on calling user php function.
// file.php  echo "One"; function my_function($arg1, $arg2)< echo "Two"; return $arg1 + $arg2; >
// app.js let execPhp = require('exec-php'); execPhp('file.php', (err, php, out) =>  // outprint is now `One'. php.my_function(1, 2, (err, result, output, printed) =>  // result is now `3' // output is now `One'. // printed is now `Two'. >) >)

All uppercase function name on PHP will be converted to lowercase on exec-php .

// file.php  function MyFunction($a, $b)< return $a + $b; >
// app.js let execPhp = require('exec-php') execPhp('file.php', (err, php, out) =>  php.myfunction(1, 2, function(error, result) // result is now 3 >) >)
  1. 0.0.3
    1. Handle PHP throw error exception
    1. Upgrade tmp module to suppress opsolete functions ( GuilhermeReda )
    2. Add noop function to support the new node callback standard
    1. Close temp file pointer on removing the file ( MHDMAM )
    1. Remove deprecated module.parent ( Jakub Zasański )
    2. Upgrade deprecated dependencies

    About

    Execute PHP function within NodeJS application

    Источник

    Запуск node.js из PHP c параметрами

    В процессе разработки иногда возникает необходимость из PHP запустить скрипт на node.js и передать параметры, а в node.js получить эти параметры и использовать их. А также вернуть результат обработки назад в PHP. Запуск из PHP будет произведен при помощи команды shell_exec — это будет равносильно тому, что мы бы запустили скрипт (node index.js 1 2) из командной строки. Ниже пример кода, как это сделать. Код PHP файла:

    $param1 = '1'; $param2 = '2'; $buf = shell_exec('node index.js $param1 $param2'); echo $buf;
    for(let arg of process.argv) < console.log(`Массив входящих аргументов->: $`); >
    Массив входящих аргументов-> : /usr/bin/node Массив входящих аргументов-> : /var/www/user/data/www/ae-nekrasov.ru/testoflern/index.js Массив входящих аргументов-> : 1 Массив входящих аргументов-> : 2

    Аргументы передаются отделенные пробелами. Входящие аргументы находятся в process.argv, но при этом в первых двух ячейках будут служебные данные, это следует учитывать, при обращении к ним из node.js. В данном примере они просто выводятся в цикле for, в реальном скрипте их можно использовать для передачи каких-то необходимых данных, для работы скрипта. В примере использован вывод в ` ` — так как это позволяет подставлять значения в строку, без конкатенации.

    Также можно передавать массив из PHP в node.js, для этого необходимо использовать функцию преобразования массива в json и уже эти данные отправлять. Также необходимо массив упаковать в два вида кавычек одинарные, а уже название ключей и значения в двойные, для построения правильной строки, чтобы на стороне node.js сработала функция JSON.parse для преобразования строки в объект. Пример PHP кода:

    $param1 = array('"name"' => '"John"','"lastname"' => '"Smith"','"age"' => '"24"','"city"' => '"Moscow"'); $param2 = '2'; $paramjson = json_encode($param1); $buf = shell_exec('node index444.js $paramjson $param2'); echo $buf;

    Теперь на стороне node.js преобразуем строку в объект, пример:

    var stingtoobj = JSON.parse(process.argv[2]); console.log(`Вывод данных : $`);

    В итоге мы получили объект из строки, которая пришла от PHP и выводим имя, результат будет такой: Вывод данных : John

    Источник

    Как запустить nodejs скрипт через PHP exec?

    Итак, имеется nodejs скрипт, который, используя selenium webdriver, запускает браузерный тест. Он нормально запускается из консоли. Но когда я пытаюсь запустить его из контроллера через exec или shell_exec, то получаю кучу ошибок, природу которых не совсем понимаю, так как упомянул уже ранее, что через терминал всё работает хорошо.

    "use strict"; require('chromedriver'); const webdriver = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); var browser = new webdriver.Builder().forBrowser('chrome') .setChromeOptions(new chrome.Options() .addArguments('--no-sandbox') .addArguments('--headless') .addArguments('--disable-dev-shm-usage') ) .build(); browser.get('https://some_url.com');

    Так запускаю скрипт в контроллере:
    exec(‘/usr/bin/node ../../admin-test/test.js’);

    И сама ошибка, которая возникает при запуске:

    Array ( [0] => /var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/lib/promise.js:2626 [1] => throw error; [2] => ^ [3] => [4] => WebDriverError: unknown error: Chrome failed to start: exited abnormally [5] => (unknown error: DevToolsActivePort file doesn't exist) [6] => (The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) [7] => (Driver info: chromedriver=77.0.3865.40 (f484704e052e0b556f8030b65b953dce96503217-refs/branch-heads/3865@),platform=Linux 4.19.36-1-MANJARO x86_64) [8] => at Object.checkLegacyResponse (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/lib/error.js:546:15) [9] => at parseHttpResponse (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/lib/http.js:509:13) [10] => at doSend.then.response (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/lib/http.js:441:30) [11] => at processTicksAndRejections (internal/process/task_queues.js:86:5) [12] => From: Task: WebDriver.createSession() [13] => at Function.createSession (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/lib/webdriver.js:769:24) [14] => at Function.createSession (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/chrome.js:761:15) [15] => at createDriver (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/index.js:170:33) [16] => at Builder.build (/var/www/xxe.loc/admin-test/node_modules/selenium-webdriver/index.js:642:16) [17] => at Object. (/var/www/xxe.loc/admin-test/test_lab.js:13:14) [18] => at Module._compile (internal/modules/cjs/loader.js:816:30) [19] => at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10) [20] => at Module.load (internal/modules/cjs/loader.js:685:32) [21] => at Function.Module._load (internal/modules/cjs/loader.js:620:12) [22] => at Function.Module.runMain (internal/modules/cjs/loader.js:877:12) )

    Средний 10 комментариев

    Источник

    Run PHP Scripts from Node JS

    Due to the asynchronous only design of ImageMagick within Node JS, I ran into a nightmare trying trying to code a recent web application. You can not run ImageMagick synchronously in NodeJS, I wasn’t able to get callbacks to work correctly, the npm async series method wasn’t working, and the nesting of ImageMagick functions wasn’t favorable. Much of my code was using ImageMagick to check the properties of the image and do conditional functions based on the results.

    All that complaining said, the bigger frustration is that I already had most of this script written in PHP. In PHP the script uses an object oriented approach which does allow for a synchronous flow and conditional checks. So could I use this PHP script along side of my Node JS application?

    How to call PHP from Node JS

    A bit of digging and all of the solutions I was able to find suggested running Apache along side of Node JS, which would then allow you to call PHP via Apache. But seriously, this makes no sense. Calling a web server from a web server on the same machine? Even worse, I wanted my Node JS web app to be called on port 80, so installing Apache will create a port conflict, etc.

    I want to give credit to scriptol.com for being the only reference I could find on how to beautifully blend Node JS with the synchronous methods of ImageMagick in PHP.

    Источник

    Running locally a PHP program from the browser with Node.js

    Node.js is the link that connects the browser to executable files on a local machine.

    The diagram below shows how the system works:

      We start node with the server script :

    PHP, HTML and Node.js

    To start the program, you type the program name in the URL bar:

    And you can also pass variables to the program, in this form:

    localhost:1000/dirlist.php?x=test 

    The JavaScript code is derived from the server code that was already used to create a HTML file server with Node.js. But this time, instead of displaying the content, we use the module child_process to run the program, and it is then the program output that will be displayed.
    It works on a local machine, or on a remote host.

    1) As always we first create a server

    var server = http.createServer(php); server.listen(1000); console.log("PHP ready to run script given on port 1000.");

    And we assign a communication port.

    2) The existence of the script in the file system is checked

    function php(request, response) < var urlpath = url.parse(request.url).pathname; var param = url.parse(request.url).query; var localpath = path.join(process.cwd(), urlpath); fs.exists(localpath, function(result) < runScript(result, localpath, param, response)>); >

    The file name is extracted from the URL with the parse method of the url module.
    And also is extracted the parameter string with the query method. It is transmitted as is to the PHP script.

    function runScript(exists, file, param, response) < if(!exists) return sendError(404, 'File not found', response); runner.exec("php " + file + " " + param, function(err, stdout, stderr) < sendData(err, stdout, stderr, response); >); >

    The exec method of child_process has for first parameter all that is typed in the command line, so the name of the PHP interpreter, the script name and parameter list.

    4) Everything displayed by the script will be displayed in the browser

    function sendData(err, stdout, stderr, response) < if (err) return sendError(500, stderr, response); response.writeHead(200,); response.write(stdout); response.end(); >

    It is the role of the sendData function called in callback by the exec method.

    This PHP demo script reads files in the directory and lists them. Everything it displays appears in the browser.

    The parameters are found in the $argv array. The first parameter (the only one in this example) in $argv[1]. It is the task of the programmer to split the string and use its contents.

    6) The full JavaScript code source

    var http = require("http"), fs = require("fs"), path = require("path"), url = require("url"), runner = require("child_process"); function sendError(errCode, errString, response) < response.writeHead(errCode, ); response.write(errString + "\n"); response.end(); return false; > function sendData(err, stdout, stderr, response) < if (err) return sendError(500, stderr, response); response.writeHead(200,); response.write(stdout); response.end(); > function runScript(exists, file, param, response) < if(!exists) return sendError(404, 'File not found', response); runner.exec("php " + file + " " + param, function(err, stdout, stderr) < sendData(err, stdout, stderr, response); >); > function php(request, response) < var urlpath = url.parse(request.url).pathname; var param = url.parse(request.url).query; var localpath = path.join(process.cwd(), urlpath); fs.exists(localpath, function(result) < runScript(result, localpath, param, response)>); > var server = http.createServer(php); server.listen(1000); console.log("PHP ready to run script given on port 1000.");

    In fact we have with this program the basis for a rudimentary local application server: by changing the script name in the URL bar, you throw different tools.
    To automate the running you can put each in bookmark, and even possibly use bookmarklets to pass parameters.
    This local server can also be started itself by placing the above command in a batch file that will run at session startup.

    Источник

    Читайте также:  Scroll To Top Button
Оцените статью