How can we change the existing URL of a webpage into another one in PHP?

To change the existing URL of a webpage to another one in PHP, you typically use the header() function to send a raw HTTP header. Here's an example of how you can perform a URL redirection:

phpCopy code<?php
// Redirect to a new URL
$newURL = "https://www.example.com/new-page";
header("Location: $newURL");
exit(); // Ensure that no further code is executed after the redirect
?>

In this example:

  1. $newURL contains the target URL where you want to redirect the user.

  2. The header("Location: $newURL") line sends an HTTP header to the browser, instructing it to redirect to the specified URL.

  3. exit() is used to ensure that no further PHP code is executed after the redirect header, as it's good practice to prevent any unintended code execution.

Make sure that the header() function is called before any HTML content or whitespace in your PHP script, as headers must be sent before any actual output.

Keep in mind that URL redirection is a common technique, but it's crucial to handle it carefully to avoid unintended consequences or security vulnerabilities. Always validate and sanitize user input, and consider the implications of redirecting users, especially if the new URL is based on user-provided data.