starting a websockets server in php on shared hosting

怎甘沉沦 提交于 2019-12-03 15:44:19

Not having SSH access to your shared hosting is pretty flaky. That said...

You can use exec to run something on the command line from a triggered script. For instance, if you have a controller action that you call from a URL like http://mysite.com/server/start, you could embed the line:

$lastLine = exec("php server.php");

Of course, this command will not return until the command finishes, so you will never get a response from this script (unless it fails). So I would use popen, which will fork the process and return right away, allowing your controller to return a response.

$handle = popen("php server.php", "r");

At some point, you are probably going to want to stop this server. You can use passthru and posix_kill with a little unix CLI magic to get this done, maybe in another controller action that you call from a URL like http://mysite.com/server/stop, you could embed:

$output = passthru('ps ax | grep server\.php');
$ar = preg_split('/ /', $output);
if (in_array('/usr/bin/php', $ar)) {
    $pid = (int) $ar[0];
    posix_kill($pid, SIGKILL);

Actually there's lots of ways to get a daemon running without shell access, but the hosting companies will have blocked shell access because they don't want you running daemons !

You have to make it on shell accessed server. I mean, you must have VPS for your application, and shared hosting not useful for you.

Use shell_exec to run the command from a script that can be triggered. The code shoulld be like this:

shell_exec("php -q server.php");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!