run c program using php

Viewed 20707

how to run c program using php exec() i have seen many results from google search it is possible by exec() function but i am unable to use it i tried in this way i wrote a program in c

**myc.c**
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("Hello, world\n");

    return 0;
}

**test.php**
<?php
exec('myc.c');
?>

can any one help me pls in this regard i executed this through wamp server by placing in www folder

4 Answers

Today's PHP ecosystem provides a couple better solutions for this now.

1. Write a PHP extension

You can use Zephir to easily build PHP extensions in a PHP-like language. They provide a mechanism called custom optimizers that cleanly binds arbitrary C libraries or custom C code to your extension.

While it requires a little more work, it could (YMMV) result in near-C performance via native PHP calls, and upgrades your PHP-fu. You also might accidentally fall in love with Phalcon.

In my personal experience, pure Zephir actually harmed the performance of pure PHP for my task, so I would recommend it only if you want to leverage the power of existing C libs, or you have heavy workloads.

This Github comment provides a brief overview of why you should use the Zephir optimizer over an inline CBLOCK and how to structure your directories/files.

2. Use FFI

As of PHP 7.4, the Foreign Function Interface comes built-in. You can also install it as an extension for older versions of PHP.

The upside? You don't have to write your own PHP extension to use C code. The downside? Right now FFI performance doesn't really compare to actual C code. You can think of it more like a crutch than a batmobile.

If you care about high performance, try option 1.

Related