I need a way to detect if the 'foreach' is unsuccessful. If it is unsuccessful, then repeat the same error message that is in the current 'else'.
<?php
if(file_exists('redirects.xml')) {
$xml = simplexml_load_file('redirects.xml');
if(isset($_GET['r']) && $_GET['r'] != '' && !is_array($_GET['r'])) {
foreach($xml->short as $shorts) {
if($shorts->name == $_GET['r']) {
header('Location: '.$shorts->url);
break;
}
}
}
else {
header("refresh:2;url=http://www.wlatw.co/");
echo '<div align="center" style="font-weight: bolder; font-size: 24px;">Malformed URL</div><div align="center" style="font-weight: bolder; font-size: 16px;">Redirecting...</div>';
}
}
?>
You'll need to add a variable to keep track of the loop's status.
<?php
if(file_exists('redirects.xml')) {
$xml = simplexml_load_file('redirects.xml');
if(isset($_GET['r']) && $_GET['r'] != '' && !is_array($_GET['r'])) {
$url_is_malformed = false;
foreach($xml->short as $shorts) {
if($shorts->name == $_GET['r']) {
header('Location: '.$shorts->url);
break;
}
}
$url_is_malformed = true;
}
else {
$file_doesnt_exist = true;
}
if( $file_doesnt_exist || $url_is_malformed )
{
header("refresh:2;url=http://www.wlatw.co/");
echo '<div align="center" style="font-weight: bolder; font-size: 24px;">Malformed URL</div><div align="center" style="font-weight: bolder; font-size: 16px;">Redirecting...</div>';
}
}
?>
Create a flag before starting the loop; Set it to unsuccesful when it fails.
<?php
if(file_exists('redirects.xml')) {
$xml = simplexml_load_file('redirects.xml');
if(isset($_GET['r']) && $_GET['r'] != '' && !is_array($_GET['r'])) {
$success = false; // set the flag
foreach($xml->short as $shorts) {
if($shorts->name == $_GET['r']) {
header('Location: '.$shorts->url);
$success = true;
break;
}
}
if ($success) { // do what you want when not success ful.
header("refresh:2;url=http://www.wlatw.co/");
echo '<div align="center" style="font-weight: bolder; font-size: 24px;">Malformed URL</div><div align="center" style="font-weight: bolder; font-size: 16px;">Redirecting...</div>';
}
}
else {
header("refresh:2;url=http://www.wlatw.co/");
echo '<div align="center" style="font-weight: bolder; font-size: 24px;">Malformed URL</div><div align="center" style="font-weight: bolder; font-size: 16px;">Redirecting...</div>';
}
}
?>
But looking at your code, you can just exit after setting the header:
foreach($xml->short as $shorts) {
if($shorts->name == $_GET['r']) {
header('Location: '.$shorts->url);
exit;
break;
}
}
Note: As @Sverri M. Olsen said, you should always stop your script after setting the Location header, either with die, exit or any other mechanism you have.