如何在redirect语句中嵌入变量?能否实现双重重定向?
Hey there! Let's work through your questions step by step, and fix up that code snippet you shared.
Your original redirect line has a PHP syntax error—you can’t use echo directly inside the string like that. There are two straightforward ways to include variables in your redirect URL:
- String concatenation with
.: Join the static part of the URL and your variable using the dot operator:redirect('http://A.com/' . $nom); - Double-quoted string parsing: Wrap the entire URL in double quotes, and PHP will automatically parse the variable inside:
redirect("http://A.com/$nom");
Both methods will correctly insert the value of $nom (which you set to status) into the URL, so your redirect will point to the right place.
Since you’ve already defined $nom = 'status';, using either of the corrected redirect methods above will directly send the user to http://A.com/status—that’s exactly what you need here.
First, a quick note: HTTP only allows one redirect response per request, so you can’t make the server send two separate redirect commands to the browser at once.
But looking at your code, it seems like what you actually want is to run your order update logic (the simpanupdateorder call) first, then redirect the user to http://A.com/status. That’s totally doable without any "dual redirect" trickery—you just need to fix the syntax error in your redirect line. Here’s the corrected full method:
public function update_order(){ $nom = 'status'; $data= array( 'status' => 'confirmed' ); // Run your order update logic first $this->data->simpanupdateorder($nom,$data); // Now redirect to the external URL redirect('http://A.com/' . $nom); }
If you really need the browser to hit both your update_order method and A.com/status (like opening two separate pages), you’d have to handle this with frontend JavaScript. For example, you could use AJAX to call your update_order endpoint first, then redirect the user once that’s done:
// Call your update_order controller method via AJAX fetch('/update_order', { method: 'POST' }) .then(response => { // Once the update is done, redirect to A.com/status window.location.href = 'http://A.com/status'; }) .catch(error => { console.error('Failed to update order:', error); });
Just make sure your update_order method is set up to handle AJAX requests, and don’t forget to add security measures like CSRF protection!
内容的提问来源于stack exchange,提问作者Tri Bagus Soleman

