Bernard Aybouts - Blog - Miltonmarketing.com

Approx. read time: 3.3 min.

Post: How to make a go-back button with PHP code?

Lesson: Creating a “Go Back” Button in PHP Without JavaScript Using HTTP_REFERER

Objective:

Learn how to create a functional “Go Back” button using PHP, relying on the HTTP_REFERER variable while ensuring its reliability through proper error handling and sanitization.

Prerequisites:

  • Basic understanding of PHP
  • Familiarity with HTML
  • Awareness of server-side HTTP request headers

Introduction to HTTP_REFERER

The HTTP_REFERER variable in PHP, stored in the $_SERVER['HTTP_REFERER'] superglobal, holds the URL from which the user came before landing on the current page. This is particularly useful for creating a “Go Back” button without JavaScript, allowing the user to return to the previous page by clicking the button.

However, the HTTP_REFERER is unreliable because:

  1. It can be modified or hidden by browsers or third-party software.
  2. It is not always passed by the browser (e.g., when navigating from a bookmark or typing a URL directly).

Because of its limitations, it is important to sanitize and check if the HTTP_REFERER is set before using it in your PHP code.

Code to Create a Go Back Button Using HTTP_REFERER

1. Basic Approach Without Error Handling:

Copy to Clipboard
  • This code attempts to display a link that directs the user to the previous page.
  • The htmlspecialchars() function is used to prevent cross-site scripting (XSS) by encoding special characters in the URL.
  • However, this code will throw an error if HTTP_REFERER is not set, which is why error handling is crucial.

2. Improved Code With Error Handling:

To avoid potential errors when HTTP_REFERER is unavailable, we can wrap the logic in a condition to check if it exists.

Copy to Clipboard
  • Explanation:
    • We first check if $_SERVER['HTTP_REFERER'] is set using isset().
    • If it is set, we sanitize the URL using htmlspecialchars() to ensure it’s safe.
    • If not, we display a fallback message (like “No previous page found”).

3. Using Ternary Operator:

Alternatively, the ternary operator can be used for more concise code:

Copy to Clipboard
    • Explanation:
      • The ternary operator checks if $_SERVER['HTTP_REFERER'] is set. If it is, it assigns the sanitized URL to $url. Otherwise, it assigns an empty string.
      • We then either print the back link if $url has a value or a fallback message.

    Why Is HTTP_REFERER Unreliable?

    1. Browser Settings: Some browsers allow users to disable or modify the referrer information. In such cases, the HTTP_REFERER may be missing or incorrect.
    2. Privacy Tools: Many privacy-focused tools or plugins (such as anti-spyware) can block the referrer information from being sent.
    3. Direct Access: If a user directly accesses a page (e.g., via a bookmark or typing the URL), there is no referring page, and thus no HTTP_REFERER.

    Error Prevention in Logs

    When logging or analyzing server traffic, you may encounter cases where HTTP_REFERER is not set. Instead of causing errors, handle these situations gracefully by checking for its presence, as shown above.

    Here’s an example of a web server log that includes HTTP_REFERER:

Copy to Clipboard

However, in cases where HTTP_REFERER is blocked or not passed, it would look like this:

Copy to Clipboard

Conclusion

Using the HTTP_REFERER variable in PHP is useful for creating navigation aids like “Go Back” buttons, but always keep in mind its unreliability. By sanitizing the data and checking if it’s set, you can ensure your PHP application handles this scenario gracefully and securely.

Key Points:

  • Always sanitize the HTTP_REFERER before using it.
  • Check if HTTP_REFERER is set to avoid errors.
  • Understand that HTTP_REFERER may be missing or altered due to user privacy settings or direct access.

Next Steps:

a. Add custom error messages or logging when HTTP_REFERER is unavailable.
b. Consider using server-side session management if navigation tracking is crucial for your application.

The Longevity Blueprint: AI-Powered Health Optimization

Current step:1AI-Human Medical Analyzer: Smarter, Personalized Health
2AI-Human Medical Analyzer: Smarter, Personalized Health

> SYS.HEALTH: AI-Human Medical Analyzer_

// Revolutionize Your Diagnostics

Experience the perfect blend of cutting-edge AI precision and expert human care. Our revolutionary analyzer turns your raw health data into personalized, actionable insights tailored just for you.

> INITIALIZING_BIOMETRIC_SCAN...

[+] DATA_INPUT

Securely upload complex health parameters, including lab bloodwork and comprehensive medical history.

[+] PROCESSING

Advanced algorithmic parsing combined with human-level oversight ensures hyper-accurate data interpretation.

[+] OUTPUT_MATRIX

Receive smarter, faster, and truly personalized care strategies to take immediate charge of your health journey.

A name/nickname is required to continue.

> TRANSLATION_MATRIX_ACTIVE...
[ LANG_EN ]
Knowledge Heals, Prevention Protects
[ LANG_HI ]
ज्ञान ठीक करता है, रोकथाम सुरक्षा करती है
[ LANG_ZH ]
知识治愈,预防保护
[ LANG_JA ]
知識は癒し、予防は守る
[ LANG_HE ]
הידע מרפא, המניעה מגנה
[ LANG_AR ]
المعرفة تُشفي، والوقاية تحمي
[ LANG_FR ]
La connaissance guérit, la prévention protège

> SYS.AUTH: Data Processing Consent_

[ AWAITING_AUTHORIZATION ] By providing consent, you allow us to process your uploaded data through our proprietary AI-Human analysis system.

  • [+] SECURE_REVIEW: This ensures your information is carefully reviewed using advanced AI technology and certified professional oversight to deliver personalized health insights.
  • [+] PRIVACY_LOCK: Your privacy is our strict priority. Your data will only be used for this specific diagnostic purpose.

> SYS.UPLOAD: Share Medical Records [OPTIONAL]_

[ USER_CONTROL_ACTIVE ] Uploading your medical records during registration is entirely optional. You can choose to bypass this step and provide data later if it suits your timeline.

You dictate the data flow: share as much or as little as you’re comfortable with, and let us guide you toward better health.

[+] FORMAT_SUPPORT

We accept all file formats, including photos, PDFs, text documents, and raw official medical data.

[+] DATA_YIELD

Increased inputs correlate with higher precision. The more info you share, the better we tailor your personalized insights.

> NEXT_STEPS: Post-Registration Protocol_

Once your registration is complete, a human specialist from our team will personally reach out to you within 3-10 business days. We will discuss your health journey and map out exactly how we can support you.

About the Author: Bernard Aybout (Virii8)

Avatar Of Bernard Aybout (Virii8)
I am a dedicated technology enthusiast with over 45 years of life experience, passionate about computers, AI, emerging technologies, and their real-world impact. As the founder of my personal blog, MiltonMarketing.com, I explore how AI, health tech, engineering, finance, and other advanced fields leverage innovation—not as a replacement for human expertise, but as a tool to enhance it. My focus is on bridging the gap between cutting-edge technology and practical applications, ensuring ethical, responsible, and transformative use across industries. MiltonMarketing.com is more than just a tech blog—it's a growing platform for expert insights. We welcome qualified writers and industry professionals from IT, AI, healthcare, engineering, HVAC, automotive, finance, and beyond to contribute their knowledge. If you have expertise to share in how AI and technology shape industries while complementing human skills, join us in driving meaningful conversations about the future of innovation. 🚀