What you are trying to achieve cannot be done in the PHP Web paradigm: your script runs in the context of an HTTP request ; its execution will always be terminated the moment your visitor interrupts the request (closes the tab or browser, turns off WiFi, etc.).
In order to trigger the execution of a long background task from an HTTP request (either the click of a button, or a programmatic curl call), your server must be composed of more ingredients: typically a Message Queue (such as RabbitMQ).
The button click would only trigger a Job message: put a (string) message into the Message Queue which describes the type of execution to run, and the parameters (for instance in a PHP-serialized way, or JSON) — and then returns immediately. Your visitor receives a quick HTTP response which says "Your job has been queued successfully".
Then, in addition to the Message Queue ingredient, you must run a continuously running process (in PHP CLI with infinite time limit, or a daemon in any language of your choice). This infinitely looping script puts itself in listening mode (subscriber) against the Message Queue service, and every time a message comes in, it does whatever long processing you need.
The status of the long job may be consulted by your visitor on a dedicated page of their running jobs, where they might also obtain the outcome for download or view etc. (example: the various "Convert YouTube to Mp3" services around the Web)
This is the only robust way of handling long background tasks triggered online.
There are several alternatives to the middleware that you can use to achieve this: RabbitMQ, Redis, Kafka, are some example, depending on the specifics of your situation (according to considerations such as the number of daemon instances, the need for priority management of the pending messages in queue, or persistence of the queue in case of failure etc.)
You can find in the RabbitMQ How-To a detailed guide with PHP.