Good morning,
I've got such problem. I would like to store in cookies language, which user will choose. The value in local variable is still changed, but value in cookie is always the same. Even if I always delete the cookie and then I create it again the value stored in cookie is wrong and my local is good. Here's my code:
<?php
if (isset($_GET['lng'])) {
$lng = $_GET['lng'];
if (($lng != "en") && ($lng != "de")) {
$lng = "en";
}
} else {
if(!isset($_COOKIE['lang'])) {
$lng = "en";
} else {
$lng = $_COOKIE['lang'];
}
}
if(isset($_COOKIE['lang'])) {
setcookie("lang", $_COOKIE['lang'], time()-10); //here I try to remove cookie and then create another
}
setcookie("lang", $lng, time()+5);
print_r($_COOKIE);
echo $lng;
?>
print_r will allways return me the main language (en), even if in variable $lng there is de. I think, there will be just stupid problem, but I can't fix it. This removing line (which I commented) is there because of problem written on official php site:
Be careful of using the same cookie name in subdirectories. Setting a simple cookie
setcookie("region", $_GET['set_region']);
both in the root / and for instance in this case /admin/ will create 2 cookies with different paths. In reading the cookies back only the first one is read regardless of path.
And I thought I've similar problem. But this didn't fix my problem and even when the cookie after 5 second will expire to cookie is then written again the bad "en" value.
Thank for your answer
Can you try this, it works for me.
I edited the code a bit, sorry for obfuscating it with one line if-statements.
I also set the cookie time to 1 day so it won't disappear when testing the code.
And remember, you have to update the page to read the new cookie, it will be one step behind $lng.
<?php
$allowed = array('en', 'de');
$chosen = $_GET['lng'] ? $_GET['lng'] : ($_COOKIE['lang'] ? $_COOKIE['lang'] : 'en');
$lng = in_array($chosen, $allowed) ? $chosen : 'en';
setcookie("lang", $lng, time()+24*60*60, '/');
var_dump($_COOKIE['lang']);
echo $lng;
?>
Related
I am trying something strange with code i just want to know weather it is possible to perform a php code like this one
<?php
$cururl= ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$nexurlw = $cururl-1;
echo "$nexurlw";
?>
I have a problem in this code. My current page url is 30.php and i have a button on page "go to previous page" i want to change its url 29.php with the help of this function.
But this function echo 30 every time.
Try this :
$cururl = ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$intUrl = ((int) $cururl) - 1;
$nexurlw = (string) $intUrl.'.php';
echo "$nexurlw";
Even if it happens to be true in your case (because that's the default in a raw PHP installation) there's often no direct mapping between URL locations and filesystem objects (files / directories). For instance, this question's URL is
https://stackoverflow.com/questions/68504314/how-to-get-current-webpage-name-and-echo-with-some-modification but the Stack Overflow server does not have a directory called 68504314 anywhere on its disk.
You want to build a URL from another URL, thus there's no even any benefit in having the filesystem involved, you can just gather the information about current URL from $_SERVER['REQUEST_URI']. E.g.:
$previous_page_url = null;
if (preg_match('#/blah/(\d+)\.php#', $_SERVER['REQUEST_URI'], $matches)) {
$current_page_number = (int)$matches[1];
if ($current_page_number > 1) {
$previous_page_url = sprintf('/blah/%d.php', $current_page_number - 1);
}
}
I've recently been developing a multi-lingual website. I've got a slight problem though.
Every time a button is clicked the language variable needs to change. i did this using the anchor tag (i.e English ).
The problem arises when other variables besides the language are added to the URL. I would like to redirect the page without getting rid of other variables and just changing the lang variable. So if the url contains "var1=value&var2=value&lang=En", I would like to alter the lang variable and keep the rest as they are. The lang variable can have 3 values: En, Az, Ru.
The method I tried so far:
function URI_ADD_AZ(){
$URI = $_SERVER['REQUEST_URI'];
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
unset($lang);
}
$new_URI = $URI . '?lang=Az';
return $new_URI;
}
Azeri
The problem:
Everytime the button is clicked the lang variable just gets added to the url not altered:
/?lang=Az?lang=Az?lang=Az?lang=Az
How can I make sure it does not keep getting repeated and avoid redirect loops?
The URI_ADD_AZ function posted in the question does not overwrite or remove preexisting occurrences of lang=* in the Query String, therefore duplication of "langs" in the URL. Also there is no handling of the requirement for ? or & depending on location of the key=value pair in the query string.
Here, to simplify things and limit the working string and therefore potential for introducing errors, the $_SERVER var QUERY_STRING is pulled, rather than the entire REQUEST_URI, and PHP_SELF is then prepended to the HREF value.
First thing here is to remove the lang=* including the & depending on it's position. A conditional reference is used to remove the trailing & only if the match is found at the beginning of the string.
Next $lang is retrieved from the $_GET var and validated. And if there's a valid $lang it is appended to the query string taking into consideration whether & is needed or not.
Finally, if not empty, the resulting query string is prepended with ? and returned.
function URI_ADD_AZ() {
$QS = preg_replace('/((^)|&)lang=[^&]*(?(2)&)?/', '', $_SERVER['QUERY_STRING']);
$lang = ( isset($_GET['lang']) && in_array($_GET['lang'], array('En','Az','Ru')) )? 'lang=' . $_GET['lang']: '';
if ( '' != $lang ) {
if ( '' == $QS ) { $QS = $lang; }
else { $QS .= "&$lang"; }
}
if ( '' != $QS ) {
return '?' . $QS;
}
}
Azeri
Simply provide Complete URL :-
Azeri
or, if you want to do it without reloading of page, you will have to use "jquery.history.js" file.
https://github.com/browserstate/history.js
History.pushState(null, 'title of my website', "?lang=<?php URI_ADD_AZ(); ?>);
Thanks
For some reason, I can't seem to set a cookie in one of my PHP files. All of the code works fine, except it refuses to set the cookie. I've placed different versions of cookie setting with different arguments, but it doesn't seem to make a difference. On top of that, I can set a cookie using that same line of code in a separate PHP file in the same directory. I've tried placing setcookie() at different places and I still get the same result. Am I missing something?
<?php
$table_name="lfgs";
$name=$_POST['name'];
$event="[";
$level=$_POST['level'];
$comments=$_POST['comments'];
$hours=$_POST['hours']*60*60;
$minutes=$_POST['minutes']*60;
$time=$hours+$minutes+time();
setcookie("remember", $name, $time, 'www.domain.com', '/');
if(isset($_POST['event'])){
if (is_array($_POST['event'])) {
foreach($_POST['event'] as $value){
$event = $event . "\"" . $value . "\",";
}
} else {
$value = $_POST['event'];
$event = $event . "\"" . $value . "\"]";
}
} else {
$event = "";
}
if($event[strlen($event)-1] == ',') {
$event = substr_replace($event ,"]",-1);
}
$con=mysqli_connect("domain.com","username","password","database");
$req="INSERT INTO $table_name(name, event, level, comments, time) VALUES ('$name', '$event', '$level', '$comments', '$time')";
mysqli_query($con,$req);
mysqli_close($con);
foreach($_COOKIE as $c) {
echo $c . "<br />";
}
?>
Edit: This is ALL the code for the entire file.
According to the php reference, the correct way to use the setcookie function is
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Didn't you swaped the $path and $domain argument?
Try
setcookie("remember", $name, $time, '/', 'www.domain.com');
try
setcookie("remember", $name, '/', $time);
I dont't understand what you want to do, but it'll not works the way you do.
Always remember: you work with PHP on the server side.
So to set a cookie an then to test if it worked, you need always tow steps (because you are on the server side):
The first step is to set the cookie.
And then during the next request you can check if ur cookie contains in the global $_COOKIE array. if yes then ok, if not then mybe the client/user donsen't allow to set cookies.
If you need to do it in "one step", you should use JavaScript. Something like that:
On submit the form, set the cookie and then propagate the submit action (send the data to the server). JQuery support a good solution to set and read cookies.
Are you sure the php interpreter doesn't send a char before the setcookie() call for some reason? The function send a HTTP header, so it have to appear before any printing on the page.
From my experience, if you have any session active on the page it will not allow you to create PHP cookies. Start a new blank page and test it that way.
You should be able to set a cookie on the new generic page. Then go back to your other page that has a session started on it. Echo the details of that set cookie in the session page and you will get the stored value, no problem.
You can call cookies but you can't seem to create them in an active session page. At least, I can't with my current system settings/config.
How to pass an array from one file to another using include using PHP language?
I have one file with some language array(language/langen.php):
global $lang;
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
In other file I have:
include base_url().'language/lang'.$_COOKIE['lang'].'.php';
var_dump($lang);
*(My mistake by coping code - true is var_dump($lang))*
But it shows me an error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: lang
How to solve this problem and what did I do wrong?
First of all:
You should never use cookie value directly in include statement - its pretty easy to make fake cookie and mess up in your application.
I suppose you just don't have cookie with name lang or variable $lang has never been initialized before.
To check if cookie exists and is in correct format you can do like that:
// set default lang code
$langCode = 'en';
// check if cookie exists and if contains string build from 2 characters from range a-z
// check also if file exists
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
include base_url().'language/lang'.$langCode.'.php';
in included file you should check if variable $lang exists
if (!isset($lang)) $lang = array();
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
also I think using global here is pointless as from your example it looks like its the same scope.
anyway for me much cleaner solution would be:
// first_file.php
$langCode = 'en';
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
$lang = include base_url().'language/lang'.$langCode.'.php';
// langen.php
return array(
'Date' => 'Date',
'Here' => 'Here',
);
EDIT
One more thing - If base_url() is returning web URL (like http://example.com...) then it is also wrong (and also can cause problem as langen.php will contain at least Notice message when included this way) - should be included with valid file path
Shouldn't it be?
include base_url().'language/lang'.$_COOKIE['lang']['Here'].'.php';
Or else it would just return array()
First of all, I don't see the point of var-dumping variable $data, if there is no such thing in code you posted. If you have a cookie called "lang" in your browser, then you should be fine. You could always check this by
var_dump($GLOBALS['lang']);
in your code. It should print the array of values from your lang*.php file.
Can someone help me clean this up and make it more logical? I'm fried right now and can't seem to get a good line of code written :)
I'm trying to capture affiliate id from urls like ?aid=3056677. The idea is IF aff id is set in GET that takes precedence, the session and finally cookie with least. Also, we don't want to set an aff id that does not exist.
Do you know of a more tried and true method of doing this?
session_start(); // start session
// affiliate id
$g_aid = (isset($_GET['aid']) && $_GET['aid'] != '') ? trim($_GET['aid']) : false;
$s_aid = (isset($_SESSION['aid']) && $_SESSION['aid'] != '') ? trim($_SESSION['aid']) : false;
$c_aid = (isset($_COOKIE['aid']) && $_COOKIE['aid'] != '') ? trim($_COOKIE['aid']) : false;
if($g_aid !== false) // use get if set
$aid = $g_aid;
elseif($s_aid !== false) // next use session if get not set
$aid = $s_aid;
elseif($c_aid !== false) // cookie
$aid = $c_aid;
else
$aid = ''; // leave it empty
// if $aid is set is it in the $affiliates array?
//If not use the first key from that array
$aid = (isset($affiliates[$aid])) ? $aid : key($affiliates);
// save it and set it
// (maybe shouldn't be done if already stored?
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
session_start();
// checks if a field is valid
function isValid($aid) {
return (!empty($aid) && trim($aid) != '');
}
// set the affiliate ID
$aid = isValid($_GET['aid']) ? $_GET['aid'] :
isValid($_SESSION['aid']) ? $_SESSION['aid'] :
isValid($_COOKIE['aid']) ? $_COOKIE['aid'] :
'';
// use first key from array if aid not set
if (!isset($affiliates[$aid])) $aid = key($a);
// save and set
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
Why would you test for session and cookie, in case you have a valid affiliateID from the $_GET array? ==> Make it progressive so that session is only checked, if no GET was found and cookie is only checked if no session was found.
Don't repeat the validation of the affiliateID. ==> Write a validate function and reuse it, you might want to add more rules later on.
Use curly brackets to make your code more readable
$aid or $aff are BAD variable names, $affiliateID instead is a GOOD one! You don't win anything for writing short variables names but you win a lot with writing self-explanatory code.
Bad example, doesn't talk
if (validate($aff))
Good example, talks to you
if (isValid($affiliationID))
So my proposal for change of the core components:
if (isValid($_GET['aid']))
{
$affiliationID = trim($_GET['aid'];
}
else if (isValid($_SESSION['aid']))
{
$affiliationID = trim($_SESSION'aid'];
}
else if (isValid($_COOKIE['aid']))
{
$affiliationID = trim($_COOKIE['aid'];
}
else
{
throw new Exception('No affiliation ID defined');
}
function isValid($affiliationID)
{
if (empty($affiliationID))
{
return false;
}
else
{
return true;
}
}
Thanks guys this is looking better and better. One point that might clarify for you, is that IF an aff id is given in GET it MUST be a valid one that exists before we possibly wipe out someone else's aff id. Money is involved with each transaction and we want an affiliate to get credit for as long as possible.
Regarding empty it's not too useful since whitespace fools it. So unless you trim before using it, I feel it's not accurate enough. So I don't know about the empty for the GET. It's ok for the others because we've already checked them.
Here's what I have so far from your help (does the complex ternary here break when it finds true? I don't want it to keep executing the line):
session_start(); // start session
$aid = !empty($_GET['aid']) ? trim($_GET['aid']) :
!empty($_SESSION['aid']) ? $_SESSION['aid'] :
!empty($_COOKIE['aid']) ? $_COOKIE['aid'] :
'';
// use first key from array if aid not set
if(!isset($a[$aid])) $aid = key($a);
if(!isset($_SESSION['aid']) || $aid != $_SESSION['aid'])
{
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
}