开发者

Error redirection in PHP

开发者 https://www.devze.com 2023-03-17 09:55 出处:网络
I\'m new to PHP and am wondering how to handle redirection in case of error. I have a s开发者_如何学JAVAcript which calls a function:

I'm new to PHP and am wondering how to handle redirection in case of error.

I have a s开发者_如何学JAVAcript which calls a function:

  $cart_object->Go2Server();
  $echo 'error';

Now, if all goes well the script will redirect the user to another url. However, if something goes wrong the page refreshes and i see the error message. Ie, the function returns.

What I'm not sure of is how to redirect the user somewhere else if the function returns. If i have the following, the redirect_to_error is sometimes called when there is no error.

$cart_object->Go2Server();
redirect_to_error();

EDIT - sorry I should add, if the script dies after the redirect, how can it return a value?


The header function can take care of this http://php.net/manual/en/function.header.php

Example :

header("Location: http://www.google.com");
exit;

You'll need to return a bool value from the function and check the value with an if statement in order to redirect to a specific page.


In your Go2Server function, consider having it return a boolean variable that indicates whether or not the headers have been set correctly to redirect the user. That is, if Go2Server works, return true, otherwise return false.

Then, run your redirect_to_error function if the boolean is false. To redirect someone, use the header function. e.g.

header('Location: www.example.com');


Is the redirect taken place in the $cart_object->Go2Server(); function?

If so is there an exit() or die() after the redirect?

The script continues when doing a redirect that's why you always need to end the script execution after redirect.


It would have been helpful if you'd shown the HTTP headers for successful and failed operations.

It sounds like you may be trying to issue a HTTP redirect (i.e. a 302 response code) after the page output has started (at which point the headers cannot be changed). If you've got your error reporting set up correctly you should see lots of 'headers sent' in your logs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号