We help IT Professionals succeed at work.

Run a php file in the background by clicking button

impressionexpress
on
I need to run a php file in the background by clicking a input type button
without navigating away from the page that the button is placed

The php file have the following headers (basically it will prompt a file generated download)
I have no information to post.

I also would like to know in the php file which prompts the download of the file, if I can save a copy of the file on the server at the same time? how would I do this ?
	// output headers so that the file is downloaded rather than displayed
	header('Content-type: text/csv');
	header('Content-Disposition: attachment; filename="demo.csv"');

	// do not cache the file
	header('Pragma: no-cache');
	header('Expires: 0');

Open in new window

Comment
Watch Question

David FavorFractional CTO
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
If you run a PHP file in background (true background), then you'll never receive any headers.

Maybe you mean run a PHP file in foreground, which will allow your PHP process to emit headers or other output which can be used in your rendering.

If this is the case you can use...

shell_exec()

Open in new window


To generate headers. Usually best for your PHP process to return headers on STDOUT, then have your parent process manage all rendering output.
David FavorFractional CTO
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:

Author

Commented:
I tried to do an ajax call put the csv file created was pout in the console. not exactly what I was looking for...

Im trying to trigger all with a simple input type button and have jquery or javascript access the file and run it if possible
Daniel PineaultPresident / Owner CARDA Consultants Inc.
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:

In your PHP you can save the file to a host folder.  Then use Ajax to make the call, use your function to return a JSON array containing the status, if successful then you can access the file in your further JS code.

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
Hi there,

Depending on your needs, you may be over thinking this. If your PHP file has the headers you've suggested, then you don't need to do anything in the background - just call the URL. Your browser will recognise that it needs to download the file so it won't navigate away from your currrent page - it will just prompt the user to download the file. You can do this with a standard <a> tag or a basic <form> submit.

<a href="download.php?var1=somedata">Download the file</a>

It's then entirely up to you what you dow inside the download.php before generating the headers (update a DB / save a file to the server etc).

Author

Commented:
was indeed over-thinking this !

answer was too easy to be true. but works exactly like I want it.

Thanks