I am trying to create a C program compiler + executer using PHP.
My PHP code is
<?php
$cwd='/path/to/pwd';
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/path/to/log/file", "a") );
$process = proc_open("./a.out", $descriptorspec, $pipes, $cwd);
fwrite($pipes[0], 123);
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
My C file is
#include <stdio.h>
int main() {
int a;
printf("Enter a number");
scanf("%d", &a);
printf("The value is: %d", a);
return 0;
}
Now when I run this, I am getting the output
Enter a numberThe value is: 123
Is there anyway to do it like a terminal execution? So it should wait for the input after showing Enter a number. Then once I enter the number it will execute further and show the output.
It will be like a web site with a terminal.
Will it be possible with proc_open and PHP? Is it possible to achieve by using Web socket in some way?
Please help. Thanks in advance.
asked Feb 7, 2022 at 12:19
Arun
3,7519 gold badges52 silver badges91 bronze badges
-
Interesting question! Effectively, you won't be able to stop the PHP so that the user can input the data like in a console. You'll very certainly have to deal with some JavaScript and web sockets might be a path towards the solution. I just don't know if you can have PHP processes that are running for a long time (without a timeout). Some console emulations such as phpbash just send a command via Ajax, execute it and return it to the browser, but it's not what you are trying to do as your command is "blocking" for input/output.Patrick Janser– Patrick Janser2022年02月07日 12:35:24 +00:00Commented Feb 7, 2022 at 12:35
-
@PatrickJanser, Thanks for spending time on this. By blocking I mean to wait for an input. So I can create kind of a terminal like UI experience. But I am not getting how to wait for input. It should go to the second input prompt when I enter the first input.Arun– Arun2022年02月07日 12:39:12 +00:00Commented Feb 7, 2022 at 12:39
-
As Patrick is saying, HTTP in general, which is what PHP, the backing server and the web browser are all talking over, is request and response, both of which terminate as soon as possible. To "resume" or "continue" a conversation, you need to introduce state of some form, such as an ID cookie on the client side, and a cursor on the server side. And for you C code, you’d want to detach that process somehow, but what out for dangling processes.Chris Haas– Chris Haas2022年02月07日 13:27:27 +00:00Commented Feb 7, 2022 at 13:27
-
Perhaps you could dig with some asynchronous PHP libraries and tools and in Symfony's process component. But I don't think it will be easy :-/Patrick Janser– Patrick Janser2022年02月07日 13:46:09 +00:00Commented Feb 7, 2022 at 13:46
lang-php