{"id":4921,"date":"2025-04-18T03:33:06","date_gmt":"2025-04-18T02:33:06","guid":{"rendered":"https:\/\/ibex.tech\/cloud\/?p=4921"},"modified":"2025-09-26T19:28:07","modified_gmt":"2025-09-26T18:28:07","slug":"execute-a-php-file-in-the-background","status":"publish","type":"post","link":"https:\/\/ibex.tech\/cloud\/php\/threads\/execute-a-php-file-in-the-background","title":{"rendered":"Execute a php file in the background"},"content":{"rendered":"\n<p>To run any background process from PHP you can simply use the exec() or shell_exec() functions. Adding a &#8216;&amp;&#8217; at the end causes the process can run in the background.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Create the php file to be executed<\/h5>\n\n\n\n<p>Put the php code you want to run in the background in a file called, for example, &#8216;my_background_task.php&#8217;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Execute it in the background<\/h4>\n\n\n\n<p>You&#8217;ll need the path to your php binary &#8211; <a href=\"\/cloud\/php\/files\/path-to-php\">see here<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  $PathToFile = plugin_dir_path( __DIR__ ) . 'includes-functions\/my-php-file-script-to-be-run.php';\n  \/\/echo \"&#91;$PathToFile]&lt;br&gt;\";\n  if (is_file($PathToFile))\n  {\n    \/\/Get the path to the PHP binary\n    $PathToPhp = '\/usr\/bin\/php';  \n\n    \/\/&gt;&gt;&gt;&gt;&gt;\n    \/\/Execute the file and capture the output (not in the background - useful for debugging)\n    \/\/$Output = shell_exec(\"$PathToPhp $PathToFile 2&gt;&amp;1\");      \/\/\"2&gt;&amp;1\" means that STDERR is redirected into STDOUT (we get standard output or error output)\n    \/\/echo \"&lt;pre&gt;shell_exec() output:\\n$Output&lt;\/pre&gt;\";\n    \/\/&lt;&lt;&lt;&lt;&lt;\n\n    \/\/Execute the file in the background\n    $ProcessId = shell_exec(\"$PathToPhp $PathToFile &gt; \/dev\/null 2&gt;&amp;1 &amp; echo $!\");     \/\/\"2&gt;&amp;1\" means that STDERR is redirected into STDOUT (we get standard output or error output),\n                                                                                      \/\/The \" &gt; \/dev\/null\" is there because the output must be directed somewhere, \/dev\/null means it won't output it to a file\n                                                                                      \/\/The final \"&amp;\" makes it execute in the background.\n                                                                                      \/\/The \"echo $!\" is there to get the process ID of the background process that was started.\n    echo \"File run, ProcessId: $ProcessId&lt;br&gt;\";\n  }\n  else\n  {\n    echo \"File not found&lt;br&gt;\";\n  }<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">Example &#8216;my-php-file-script-to-be-run.php&#8217;<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env php\n&lt;?php\n\n\n  echo \"Some output\\n\";\n  echo \"Some more output\\n\";\n\n\n?&gt;<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">Running a .php file with WordPress environment functionality<\/h5>\n\n\n\n<p>Say you want to run a wordpress task in the background, you can call a php file with it and use this to load the wordpress environment<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#!\/usr\/bin\/env php\n&lt;?php\n\n\/\/namespace MyNameSpaceName;     \/\/Optional, if you need to use the namespace in this file, otherwise remove \n\n\/\/----- LOAD WORDPRESS ENVIRONMENT -----\n\/\/We need the path to '\/wp-load.php' which is before the '\/wp-content' directory. \n\/\/__DIR__ will provide thepath to this directory, so adjust it to remove the extra\n$Path = preg_replace( '\/wp-content.*$\/', '', __DIR__ );   \nrequire_once $Path . '\/wp-load.php';\n\n\/\/----- FILES WE NEED TO INCLUDE -----\nrequire_once $Path . 'wp-content\/plugins\/my-plugin-name\/some-file-i-need.php';\n\n\n\/\/----- DO THE TASKS WE WANT TO RUN -----\n\/\/Simple test you have wordpress functionality:\necho(home_url() . \"\\n\");\n\n\/\/Simple test you have wordpress database functionality\n\/*\nglobal $wpdb;\n\n\/\/Example usage of $wpdb\n$results = $wpdb-&gt;get_results(\"SELECT ID, post_title FROM {$wpdb-&gt;posts} WHERE post_status = 'publish' LIMIT 5\");\n\necho \"Top 5 Published Posts:\\n\";\nforeach ($results as $post) {\n    echo \"- ID: {$post-&gt;ID}, Title: {$post-&gt;post_title}\\n\";\n}\n*\/\n\n?&gt;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Passing arguments to the PHP file<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Executing it in the background<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>  \/\/----- SETUP THE ARGUMENTS WE'RE PASSING -----\n  $Arguments = ''\n    . 'my_field1=' . escapeshellarg($my_field1) . ' '\n    . 'my_field2=' . escapeshellarg($my_field2) . ' '\n    . 'my_field3=' . escapeshellarg($my_field3) . ' '\n    . 'my_field4=' . escapeshellarg($my_field4) . ' ';\n\n  \/\/WHEN YOU EXECUTE THE SCRIPT, USE THIS\n  $ProcessId = shell_exec(\"$PathToPhp $PathToPhpFile $Arguments > \/dev\/null 2>&amp;1 &amp; echo $!\");<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">In your &#8216;my-php-file-script-to-be-run.php&#8217;<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>  \/\/----- PARSE THE COMMAND LINE ARGUMENTS -----\n  \/\/Remove script name\n  array_shift($argv);\n\n  $my_field1 = 0;\n  $my_field2 = '';\n  $my_field3 = '';\n  $my_field4 = '';\n\n  \/\/Loop through CLI arguments\n  foreach ($argv as $Arg)\n  {\n    if (str_starts_with($Arg, 'metadata='))\n    {\n      $Raw = substr($Arg, strlen('metadata='));\n      \/\/ Match single \"key\":\"value\"\n      if (preg_match('\/\"(&#91;^\"]+)\":\"(&#91;^\"]+)\"\/', $Raw, $Match))\n      {\n          $metadata&#91;$Match&#91;1]] = $Match&#91;2];\n      }\n    }\n    else if (str_contains($Arg, '='))\n    {\n      list($Key, $Value) = explode('=', $Arg, 2);\n\n      switch ($Key)\n      {\n        case 'my_field1':\n          $my_field1 = intval($Value);\n          break;\n        case 'my_field2':\n          $my_field2 = $Value;\n          break;\n        case 'my_field3':\n          $my_field3 = $Value;\n          break;\n        case 'my_field4':\n          $my_field4 = $Value;\n          break;\n        }\n    }\n  }<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>To run any background process from PHP you can simply use the exec() or shell_exec() functions. Adding a &#8216;&amp;&#8217; at the end causes the process can run in the background. Create the php file to be executed Put the php code you want to run in the background in a file called, for example, &#8216;my_background_task.php&#8217; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[375,225],"tags":[],"class_list":["post-4921","post","type-post","status-publish","format-standard","hentry","category-threads-wordpress","category-threads"],"_links":{"self":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts\/4921","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/comments?post=4921"}],"version-history":[{"count":9,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts\/4921\/revisions"}],"predecessor-version":[{"id":5139,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/posts\/4921\/revisions\/5139"}],"wp:attachment":[{"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/media?parent=4921"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/categories?post=4921"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ibex.tech\/cloud\/wp-json\/wp\/v2\/tags?post=4921"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}