John Davidson

php if statments to get the browser

0 comments
Message:


Im trying to call a script if the browser is firefox and its working.
But now i want to do the same if the browser is Safari and im not being able to figure it out im missing the way that php works in if statments , im new to php.


<?php
function get_browser_name($user_agent)
{
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
elseif (strpos($user_agent, 'Edge')) return 'Edge';
elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
elseif (strpos($user_agent, 'Safari')) return 'Safari';
elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';

return 'Other';
}

$browser = get_browser_name($_SERVER['HTTP_USER_AGENT']);

if($browser == "Firefox"): ?> do something here <?php endif; ?>

now i want to add an if for the Safari but im not seeing how i can do it



My Answer:
You can use the `$_SERVER['HTTP_USER_AGENT']` variable to get the user agent string of the browser and then check if it contains the string "Safari" to determine if the browser is Safari. Here's an example of how you can do this:

php
$user_agent = $_SERVER['HTTP_USER_AGENT'];

if (strpos($user_agent, 'Firefox') !== false) {
// Code to execute if the browser is Firefox
echo "This is Firefox";
} elseif (strpos($user_agent, 'Safari') !== false) {
// Code to execute if the browser is Safari
echo "This is Safari";
} else {
// Code to execute if the browser is neither Firefox nor Safari
echo "This is not Firefox or Safari";
}


In this code snippet, we first get the user agent string of the browser using `$_SERVER['HTTP_USER_AGENT']`. We then use the `strpos()` function to check if the user agent string contains the string "Firefox" or "Safari". If it does, we execute the corresponding code block. If not, we execute the code block for browsers other than Firefox or Safari.

I hope this helps! Let me know if you have any other questions.

Rate this post

3 of 5 based on 1861 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us