Language redirect not working - php

I am struggling with code that redirects a user to other pages based on language detection. I found this code which looks promising as so far I have not had any luck from other posts on this website. My only question is related to the first line of code. What do I put in the "" part on first line?
<?php
$lc = ""; // Initialize the language code variable
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
// Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
header("location: index_french.php");
exit();
} else if($lc == "de"){
header("location: index_german.php");
exit();
}
?>
<h2>Hello Default Language User</h2>
<h3><?php echo "Your 2-letter Code is: ".$lc; ?></h3>
When I run this code I get an error message:
Warning: Cannot modify header information - headers already sent by (output started at /home/m3418630/public_html/sumoresources/index.php:3) in /home/m3418630/public_html/sumoresources/index.php on line 12
Can anyone explain why this happens?
thanks

In your code snippet, you have to set a default language to the variable $lc. It will be overwritten if the server sends a language code from the current request.

This snippet can detect language from user's browser
$locale = null;
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($languages as $lang) {
$lang = str_replace('-', '_', trim($lang));
if (false === strpos($lang, '_')) {
$locale = strtoupper($lang);
} else {
$lang = explode('_', $lang);
if (count($lang) == 3) {
$locale = strtolower($lang[0]) . ucfirst($lang[1]) . strtoupper($lang[2]);
} else {
$locale = strtolower($lang[0]) . strtoupper($lang[1]);
}
}
}
}
echo $locale;
see http://codepad.viper-7.com/F1XfU5

You don't put anything there, it's just initiating the variable as it says in the comment.
If you're getting a headers already sent error, that means your outputting information to the page before sending header(), you can't do this without buffering using ob_start(), ob_end_flush().

Related

Check in header if 'thank you' page - Opencart 2

In OpenCart 2, I am editing the appearance/php of the header only in the "success"/"thank you" page (catalog/view/theme/*/template/common/success.tpl).
So, in catalog/view/theme/*/template/common/header.tpl I want to do something like:
if( $is_thank_you_page ){
echo "stuff";
// bonus: I wanted to get the order email but maybe it should be a different post
}
But how can I check in the header.tpl if it is the "success"/"thank you" page?
I tried setting a variable in success.tpl before printing the header with no results.
You could try something like this (go about it based on your URL):
<?php
$parameters = explode('/', $_SERVER['REQUEST_URI']);
if(end($parameters) === 'success.tpl'){
//the condition with $parameters depends on the exact look of your URL
//you could also access an index directly
}
Basically, it takes the REQUEST_URI (part after the domain), splits it around the / symbols and then checks if it ends with success.tpl
You could also make a switch for the end($parameters) instead of the if.
I don't know opencart structure, but if this value never change you can try with strpos/stripos, something like:
if(stripos($var_with_page_title, 'thank you') !== false) {
do_something();
}
If you want you detect checkout/success page in you header, do following:
open catalog/controller/common/header.php
find
// Menu
$this->load->model('catalog/category');
Add before
// success page checking
$data['success'] = '';
if (isset($this->request->get['route']) && $this->request->get['route'] == 'checkout/success') {
$data['success'] = true;
}
// looking for email from the order
$data['success_email'] = '';
if ($this->customer->isLogged()) {
$data['success_email'] = $customer_info['email'];
} elseif (isset(this->session->data['guest']['email'])) {
$data['success_email'] = $this->session->data['guest']['email'];
}
Now in catalog/view/theme/YOUR_THEME/template/common/header.tpl
add anywhere you like
<?php if ($success) { ?>
//do something
<?php if ($success_email) { ?><?php echo $success_email; ?><?php } ?>
<?php } ?>
With bonus email

PHP Array to string conversion with preg_match

I have this error while I'm using this my script:
$pages = array('/about.php', '/');
//...............function text here................//
$ua = $_SERVER['HTTP_USER_AGENT'];
$mobiles = '/iphone|ipad|android|symbian|BlackBerry|HTC|iPod|IEMobile|Opera Mini|Opera Mobi|WinPhone7|Nokia|samsung|LG/i';
if (preg_match($mobiles, $ua)) {
$thispage = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
if ($thispage == $_SERVER["HTTP_HOST"].$pages) {
ob_start("text");
}
}
This script changes certain pages style depending on user's useragent. I need this script in such way. But I don't know how to make it in PHP properly. Maybe I need some "foreach ($pages as $i)"? But it didn't work in a way I made it.
You are trying to check if the "requested resource" $_SERVER["REQUEST_URI"] is in predefined list of resource paths.
Change your condition as shown below(using in_array function):
...
if (in_array($_SERVER["REQUEST_URI"], $pages)) {
ob_start("text");
}

PHP Harmful URL protection

I've made this script, but the 4th line isn't right and I have really no clue how to solve this. I really appriciate if someone helps me. This is my code:
<?php
$url = $_GET["url"];
$badsite = array("http://check.com", "http://hotmail.com");
if($url == $badsite) {
echo "This URL is harmful.";
} else {
echo "Not harmful";
header("Location: " . $_GET["url"]);
}
?>
So the thing which doesn't work is the following line
if($url == $badsite) {
How can I make it so it checks if the GET contains a $badsite?
You don't want to check if the value equals the array, you want to check if it's in the array. Perhaps something like this:
if (in_array($url, $badsite)) {
// ...
}
Side note, you don't need (or want, really) this echo statement:
echo "Not harmful";
header("Location: " . $_GET["url"]);
You might get an error by emitting output before sending a header. But even if you buffer output or in some other way suppress that error, there's no reason to emit output when returning a redirect response. The browser would display it for only an instant, if at all. A redirect by itself is a complete HTTP response, no output is required.
In this case you can use the function in_array:
http://php.net/manual/en/function.in-array.php
<?php
$url = $_GET["url"];
$badsite = array("http://check.com", "http://hotmail.com");
if(in_array($url, $basite)) {
echo "This URL is harmful.";
} else {
echo "Not harmful";
header("Location: " . $_GET["url"]);
}
?>

PHP notice - Undefined index on index.php

I'm running into a server notice that doesn't seem to effect the loading of my pages but nonetheless creates a new entry in the error log every time a page is loaded... That error is:
PHP Notice: Undefined index: thing in C:\File Location\htdocs\index.php on line 1
I'm not sure whether the problem is actually on the first line or on a subsequent line, so I included a modified version of the whole file. The weird thing for me is that there's an identical line of code on several other files and it doesn't raise an issue in them. Also, the value is correctly extracted and all is well, I just don't know what to change in order to avoid the notice.
$thingvalue = $_REQUEST['thing'];
include("mdetect.php");
$iphoneTierHomePage = 'mobilemain.php';
$iphoneTierMobilePage = 'mobilepage.php?thing=' . $thingvalue;
$genericMobileDeviceHomePage = 'mobilemain.php';
$genericMobileDeviceMobilePage = 'mobilepage.php?thing=' . $thingvalue;
$line1 = define('WP_USE_THEMES', true);
$line2 = require('./wp-blog-header.php');
$desktopPage == $line1 + $line2;
$uagent_obj = new uagent_info();
function AutoRedirectToProperHomePage()
{
global $thingvalue, $uagent_obj, $iphoneTierHomePage, $genericMobileDeviceHomePage, $iphoneTierMobilePage, $genericMobileDeviceMobilePage, $desktopPage;
if ($thingvalue == ''){
if ($uagent_obj->isTierIphone == $uagent_obj->true)
header ('Location: '.$iphoneTierHomePage);
else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true)
header ('Location: '.$genericMobileDeviceHomePage);
else
header ('Location: '.$desktopHomePage);
}
if ($thingvalue != ''){
if ($uagent_obj->isTierIphone == $uagent_obj->true)
header ('Location: '.$iphoneTierMobilePage);
else if ($uagent_obj->DetectMobileQuick() == $uagent_obj->true)
header ('Location: '.$genericMobileDeviceMobilePage);
else
header ('Location: '.$desktopPage);
}
}
AutoRedirectToProperHomePage();
It's referring to the array index for the first line in index.php:
Try this:
$thingvalue = empty($_REQUEST['thing']) ? '' : $_REQUEST['thing'];
It is trying to reference the index thing inside the $_REQUEST superglobal. If someone is viewing that page directly and was not posted via a form or directed with a ?thing=foobar in the query string, PHP will show that notice. I'd recommend not using $_REQUEST as it checks both $_GET and $_POST which is not very secure/practical - then check if it is set, and if not, taking some failsave action:
try
{
if(!isset($_POST['thing']))
{
throw new Exception('No direct access. Please use our Contact form');
}
else
{
$thingvalue = $_POST['thing'];
}
}
catch(Exception $e)
{
echo $e->getMessage();
exit();
}
The issue is that you are trying to get the value of thing here
$thingvalue = $_REQUEST['thing']; before checking if the value exists first.
try this first
if( !isset( $_REQUEST['thing']) )
{
do something because its missing
}

[PHP]: Why page is not redirecting?

In the following code, the "header:" line is giving problem.
$q = mysql_query($a) or die(mysql_error());
$row = mysql_fetch_array($q);
$ValidationResponse = "false";
if ($_COOKIE['user_name'] != "")
{
while ($row) {
if ($_COOKIE['user_name'] = $row['username'])
{
$ValidationResponse = "true";
break;
}
}
if ($ValidationResponse == "true")
{
ob_start();
header("location:personal_view.php");
ob_clean();
}
else
echo "<script>alert('Invalid Login. Try Again.');</script>";
}
$_COOKIE['user_name'] = "";
Three useful functions I tend to have:
function redirect($url) {
while (ob_end_clean()) ; // do nothing
header("Location: " + $url);
exit;
}
function reload() {
redirect($_SERVER['REQUEST_URI']);
}
function reloadQS() {
redirect($_SERVER['REQUEST_URI'] + '?' + $_SERVER['QUERY_STRING']);
}
The above correctly handles what might be nested output buffers already but will fail if content has already been sent to the user, which you can't do anything about. I'd suggest using the above otherwise you'll litter your code with loops to clean buffers and there's no point in that.
You're using output buffering incorrectly, which is why it's failing. Change:
ob_start();
header("location:personal_view.php");
ob_clean();
to:
ob_end_clean();
header("Location: personal_view.php");
exit;
You should put the ob_start at the very beginning of the script
Also, i'm not sure about this, but i always seen the location header written in this way
header("Location: location.php");
Location with capital L an a space after the colon ": "
This might sound stupid, but are you sure you are not outputting anything before the header() function call? Apache won't redirect even if it finds a newline character before the starting tag <?php in a script.

Categories