phpshell-exec

shell_exec to run a large data processing


I was trying to run a php file on the background using shell_exec. But upon, adding that code on a php file it just keeps loading until the process is completed. This is my sample code below:

I have a button that will redirect to sync_to_products.php and inside that code is my shell_exec.

This is my code in sync_to_product.php and this is just keeps loading until it is completed.

include_once('../conn.php');

session_start();

$product_sku = isset($_GET['product_sku']) ? $_GET['product_sku'] : "";
$feed = isset($_GET['feed']) ? $_GET['feed'] : "";
$current_domain = $_SERVER['HTTP_HOST'];
$products_session = isset($_SESSION['products']) ? $_SESSION['products'] : '';

if(empty($product_sku)){
    $selected_products = "";
    if(!empty($products_session)){
        $product_ids = array_keys($products_session);
        $product_ids = implode(",", $product_ids);
        $selected_products = "selected_products:\"".$product_ids."\"";
    }
    shell_exec("cd ".ROOT_DIRECTORY." && php functions.php current_domain:\"".$current_domain."\" $selected_products >/dev/null 2>/dev/null &");
    session_destroy();
    header("Location: my-page.php");
}

I also tried adding >/dev/null 2>/dev/null & after the command but still it just keeps loading..

The data is about around 20k products that needs to process.


Solution

  • This is because you're using &&, so both return values have to be evaluated. Use ; instead.

    shell_exec("cd ".ROOT_DIRECTORY." ; php functions.php current_domain:\"".$current_domain."\" $selected_products >/dev/null 2>/dev/null &");
    

    should be working just fine in the background.