I can’t redirect with PHP using header()

Asked

Viewed 176 times

-4

I need help, I am beginner and I made the script below where I receive data from a form, saved in a csv file, and then I release the download of a pdf, however, at the end of the script, I wanted to give a header() to the index to erase the form data, but I am not able to redirect in any way, the pdf already lowers automatically, but does not redirect.

inserir a descrição da imagem aqui

  • Welcome to Sopt, Jande. What appears on the screen? Are there any messages? It is always ideal to use only text when sending some code instead of an image with code, because sending an image makes it difficult to test here.

  • 1

    Hello jande, could post your code instead of the image?

  • Not related to the question, but if you have if(...) { faz_coisas; faz_A; } else { faz_A; }, you just need to if(...) { faz_coisas; } faz_A;

  • @tvdias adjusted the answer, I think it’s good now, where you think it’s bad exactly to justify your downvote

2 answers

8

The whole problem is that you don’t understand HTTP yet, I’ll tell you something, most say understand HTTP, think that studying a day or two dominates it, but it’s pure illusion, it’s necessary to understand what TCP is and then understand what HTTP is.

You are expecting a server behavior as if you were running on the user’s computer, but you are not, because the script is on the server, That’s not a command:

header('Location: index.php');

Nor any other header is a command in PHP, are all instructions, which will be downloaded and processed by the client-side program or by SAPI (Sobserve Topplication Programming Interface, in this case are some special instructions like the X-Send quoted by his colleague @Bacchus that only run on the server side communicating a script with a server module, but that’s another story), be they:

  • browsers
  • programs like Curl, line command
  • Web Crawlers (Spider or Bot)

Understanding a little bit of HTTP

I’ll give you a heads-up, it’s no use leaving here thinking you’ve learned, or that you’re really going to master this, most of them don’t, they just delude themselves and it takes time to understand yes, especially if you don’t understand the basics and TCP, but you can explain HTTP without getting too deep into TCP, the simplest explanation, but that will not make anyone an expert is, when you make any HTTP request the client program, as browsers will send a instruction to the server, something like:

GET /pasta/arquivo.php HTTP/1.1
Host: www.site.com
Accept: image/gif, image/jpeg, */*
Accept-Language: en-us
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
(linha em branco)

The (linha em branco) is an empty line, should go after the headers, in GET is "indifferent", usually the servers treat this, but in POST, PUT and PATCH when contain payload (information from a form by exmeplo).

So the browser sends all this purely AS TEXT, going completely up the SERVER will process and understand the instruction and will now send a download, yes a download, everything in HTTP is download, so this is being downloaded and is only processed by the front end when some parts will be being readjusted, example (just put a piece, because a PDF would be great)

HTTP/1.1 200 OK
Date: Sun, 06 Feb 2020 23:15:53 GMT
Last-Modified: Thu, 06 Feb 2020 15:24:18 GMT
Content-Length: ‭1048576‬
Connection: close
Content-Type: application/octet-stream
Content-Disposition: attachment; filename='arquivo.pdf'
Location: index.php

%PDF-1.7

4 0 obj
...

Then the browser will interpret the headers, as there is the header:

Content-Type: application/octet-stream

or the:

Content-Disposition: attachment

Makes the browser CANCEL the request (in browsers), yes it cancels and directs to the download manager, of course it depends on the engine and how it works manages the download, so the HTTP response is no longer controlled by the tab/window you requested and is now controlled by download manager, the manager is not part of the rendering engine

The download manager may come embedded in the browser and does not mean that it is part of it "completely", but of course it processes the same session that was in the tab/window and you can notice that at the moment the download starts the "manager" the HTTP request is marked as canceled in the "browser", you can see this in the console (Devtools for example) in the network tab.

To summarize how headers are handled depends on where it runs, on XmlHttpRequest the behavior/treatment of the received headers is another and depending on the client as curl (line command) this may also vary, ie each type of location can treat the headers differently, may be by order or even by priority defined by the client program.

Unable to redirect after a download

In short, is not PHP that does the redirect, who does it is who will interpret the headers and it is also not possible to direct after a download start because usually download managers need to cancel in an instance (browser) so that they can control the request

The only way to get around this would be by maybe doing via Javascript and on the front end, downloading and redirecting are different windows, a superficial example (after all I have no way of knowing exactly how your system is, just adjust your need):

//Arquivo hipotético
$arquivo = '../foo/bar.csv';
?>
<script>
  var a = document.createElement("a");
  a.style.display = "none";
  a.href = "<?php echo $arquivo ?>";
  a.setAttribute("download", fileName);

  document.body.appendChild(a);

  a.click();

  //Redireciona via JavaScript
  setTimeout(function () {
      window.location = "index.php";
  }, 10);
</script>
<?php
} else {
    header('Location: index.php');
}
  • Why the negative? Who disagreed that HTTP works like this? Or do you believe that HTTP and TCP is easy to understand?

  • @tvdias has many ways to solve in front-end, but it depends on the knowledge of the user who asks, in general I should not have given suggestion, because this is specific may be that in a specific environment can not implement so, if people cared about learning the least of what is web, and web is HTTP, then they would know how to get around every problem like this, but as people learn wrong it is necessary to explain what is HTTP and wait for the person to modify/adapt what made their own need, what was q tried to teach.

  • I just added the example to try to help, but it’s like I said it won’t work for all cases, the important part is to understand how HTTP works and then adjust and even see a better strategy, which may be the one I presented or the one you presented, or even a series of others that only by seeing his complete system could we know.

  • @tvdias yes, but then this problem, the download is forced via PHP, it could force with . htaccess+mod_headers (Apache features) and solve the whole rest on the front end in a simple way, he may have chosen FORM, but it was his decision, nor does it mean that it is the best strategy, it is more likely that he chose pq does not know the basic principles well, This is the kind of problematic question that falls under one of the off-topic closure, but I answered because I felt sorry for him not understanding HTTP... PS: What other question (this: despite being asked in another question for doing this)?

  • 1

    Congratulations on the well-crafted and enlightening reply @Guilhermenascimento!

  • @tvdias I think depends, has to analyze case by case, here the problem was precisely the flawed understanding of the author who needed to be guided and maybe in what you answered may be something else entirely, but only I see the link to be sure.

  • 1

    Yes, it always depends. TB I’m recent at Sopt and "learning" how it works. By the way, I have committed countless gaffes... I’m trying to participate a lot, exchange ideas, etc. I want to see how long I can keep up the pace!

  • @tvdias Excellent! That’s right, always look for pro-activity and always seek tips. Good luck and if you would like to exchange an idea you are welcome to chat at https://chat.stackexchange.com/rooms/11910/stackoverflow

Show 3 more comments

1

From the image, I noticed that you make use of the readfile, this method reads a file and writes its contents to the output buffer (output buffer).

As a rule, you cannot send a header after you have started streaming the content (which is what readfile is doing).

I imagine you’re trying to download a file, probably with a target='_blank' in your php, and so is trying to redirect with the header.

When you return a header application/octet-stream the browser itself will start the download, so I believe you can call your download directly from the page home, remove this header("Location: home.php"); and the behavior will be as expected.

If this is not your scenario, update your question with more details, which I complement the answer.

  • Failed to answer how to clear the form when downloading...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.