0
0

サーバーをまたいでPHPからnode.jsを動かすサンプルコード

Posted at

備忘録メモとして

レンタルサーバーに設置したフロントエンドから、別サーバー(VSP)に置いてあるNode.jsを動かしてデータを返すサンプルコード

テスト環境:XAMPP

ファイル構成

サーバー1(レンタルサーバー)
C:\xampp\htdocs\test1
call_run_node.php
index.php

サーバー2(VPSサーバー)
C:\xampp\htdocs\test2
run_node.php
script.js

サンプルでは特に外部モジュールを使用していませんが、必要なモジュールがあればサーバー2側にインストールします。

サーバー1

index.php:フロントエンド表示部分と実行ボタン

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>サーバー2のNode.jsを実行</title>
</head>
<body>
    <h1>サーバー2のNode.jsを実行</h1>
    <button id="runNode">Node.jsを実行</button>

    <div id="result"></div>

    <script>
        document.getElementById('runNode').addEventListener('click', function() {
            fetch('call_run_node.php')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        document.getElementById('result').innerHTML = 'Node.jsの実行結果: ' + data.message;
                    } else {
                        document.getElementById('result').innerHTML = 'エラー: ' + data.message;
                    }
                })
                .catch(error => console.error('エラー:', error));
        });
    </script>
</body>
</html>

call_run_node.php:サーバー2のNode.jsを呼び出す

<?php
$data = array('message' => 'Hello from server 1');
$json_data = json_encode($data);

// サーバー2のPHPファイル
$ch = curl_init('http://localhost/test2/run_node.php');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode(array('status' => 'error', 'message' => 'cURLエラー: ' . curl_error($ch)));
} else {
    echo $response;
}

curl_close($ch);
?>

サーバー2

run_node.php:サーバー1との中継・命令を受け取りNode.jsを実行させサーバー1にデータを返す

<?php
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);

if (isset($data['message'])) {
    // Node.jsスクリプトを実行
    $output = shell_exec('node C:/xampp/htdocs/test2/script.js');

    // 実行結果を返す
    echo json_encode(array('status' => 'success', 'message' => $output));
} else {
    echo json_encode(array('status' => 'error', 'message' => '無効なデータが送信されました'));
}
?>

script.js

console.log('Node.jsが正しく実行されました!');

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0