TKK_E32230273/run_background.php

60 lines
1.8 KiB
PHP

<?php
/**
* Helper to run a PHP script in the background.
* Works on both Windows (Laragon) and Linux servers.
*
* Usage: include 'run_background.php';
* runBackground(__DIR__ . '/auto_delete.php', [$chatId, $msgId, $token, 'pin', $text]);
*/
function runBackground($scriptPath, $args = []) {
// Find the real PHP CLI binary
$phpBin = findPhpCli();
// Build the argument string
$argStr = '';
foreach ($args as $arg) {
$argStr .= ' ' . escapeshellarg((string)$arg);
}
$isWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
if ($isWindows) {
// Windows: use start /B to run in background
$cmd = 'start /B "" "' . $phpBin . '" "' . $scriptPath . '"' . $argStr . ' > NUL 2>&1';
pclose(popen($cmd, 'r'));
} else {
// Linux/Mac: use & to run in background
$cmd = '"' . $phpBin . '" "' . $scriptPath . '"' . $argStr . ' > /dev/null 2>&1 &';
exec($cmd);
}
}
function findPhpCli() {
// Method 1: Use PHP_BINDIR (always points to PHP's bin directory)
$isWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
$ext = $isWindows ? '.exe' : '';
$phpExe = PHP_BINDIR . DIRECTORY_SEPARATOR . 'php' . $ext;
if (file_exists($phpExe)) {
return $phpExe;
}
// Method 2: Use php.ini directory (same folder as php.exe in Laragon)
$iniPath = php_ini_loaded_file();
if ($iniPath) {
$phpExe = dirname($iniPath) . DIRECTORY_SEPARATOR . 'php' . $ext;
if (file_exists($phpExe)) {
return $phpExe;
}
}
// Method 3: PHP_BINARY (works for CLI, might be httpd.exe for mod_php)
$bin = PHP_BINARY;
if (stripos(basename($bin), 'php') === 0) {
return $bin;
}
// Method 4: Fallback to 'php' in PATH
return 'php';
}