Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
990 views
in Technique[技术] by (71.8m points)

php - Header location not working properly

I have a php script that renders an image (with imagick) and saves it to some directory "SITE_ROOT.$filePath", then does a header('Location: ' . SITE_ROOT.$filePath), the file it redirects to is a png image.

If I go to the path directly, like just type it in the URL bar I can save the image and everything works fine, however when I rely on the script to redirect me and I try to right click and save the image it doesn't recognise that I'm actually trying to save an image, it thinks I'm trying to save it as a non-typed file called 'Driver' which is the name of the script page.

I have no idea what's wrong here, surely the header location should just take me to the image and have no record of the 'Driver' file after it has redirected?

The same thing happens with redirect() too btw.

Thanks in advance for any help!

Edit: This problem was solved by placing a die() after the header command.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using file paths which is not working with header location. You are supposed to use urls.

It's best practice to use absolute urls in header location. PHP documentation says:

HTTP/1.1 requires an absolute URI as argument to ? Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. (Source)

Also always exit the script afterwards because otherwise in my experience in certain circumstances code that comes after the redirect might still be executed. So a good example would look like this:

header("location:http://www.mysite.com/path/to/myfile.php");
exit;

Often you would use a server variable for this case:

$url = $_SERVER["HTTP_HOST"]."/path/to/myfile.php";
header("location:".$url);
exit;

Cheers!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...