PHP redirect without header () or meta

I am trying to create a page that performs some actions with a database, and then redirects the user back to the page from which they came. The problem is that I use the require() function to connect to the database, so the headers are already sent. The meta tag is out of the question, because I want it to look as if all the processes are running from the page from which they came. Any tips? Is there a way to use require() and header() , or should I drop it? Is there an alternative to header() ?

+4
source share
6 answers

As Artefacto noted, connecting to a database does not require any output. Correct everything that you include (e.g. database_connect.php) so as not to output. See this search for sent headers, which may help you find hidden output.

+3
source

If you cannot send header() before sending some content, use output buffering by placing ob_start(); at the beginning of your script before anything is sent. Thus, any content will be stored in the buffer and will not be sent until the end of the script or when manually sending the contents of the buffer.

In another note, just require another file will not generate headers / content unless it included a script. The most common β€œhidden” reason for this is inconspicuous spaces before or after the <?php ?> Tags.

+7
source
 ob_start(); // start output buffering echo "<html......"; // You can even output some content, it will still work. . . . . . header("Location: mypage.php"); ob_flush(); //flush the buffer 

In this case, the entire output is buffered. This means that the headers are processed first, then the output is played ...

+2
source

You cannot send headers after any content has already been submitted. Move the header() call before the require() call.

+1
source

You cannot send headers after sending any data to the client.

However, using require does not mean that you are issuing something. If I understand your right, you can include your database files, run your queries, and then redirect the user. This is absolutely true.

If you need to send some kind of result (why, if you need to do a redirect?), Another option is to use output buffering. Using output buffering, you do not send data to the browser when echoing, but you save it in the buffer. Data will be sent when ob_end_flush is called, or you will reach the end of the script. After ob_end_flush, you will not be able to send new headers. You start buffering output with ob_start .

0
source

When using output buffering, you can use header() with require() . This means that the entire script is buffered and sent first when the script comes to an end.

I did it by doing it

 ob_start("ob_gzhandler"); //begin buffering the output require_once('/classes/mysql.php'); // Some code where I access the database. header('/somepage.php'); exit; ob_flush(); //output the data in the buffer 
0
source

Source: https://habr.com/ru/post/1336603/


All Articles