I need to write some custom code for a Wordpress function, and I need to be able to delete any cookies that start with wp-postpass_. I know this can be done with jQuery but I'm unsure of how to approach it in PHP.
I have tried Googling and searching on here but I haven't been able to find anything that matches what I'm trying to do.
Thank you in advance,
Andy
EDIT:
Sorry, I should have mentioned that Wordpress appends a random string onto the end of wp-postpass_ hence why I need to find any cookies that start with wp-postpass_. Apologies, early morning.
So iterate through all cookies and check if there contain wp_postpass_ and then remove the cookie.
foreach($_COOKIE as $cookieKey => $cookieValue) {
if(strpos($cookieKey,'wp-postpass_') === 0) {
// remove the cookie
setcookie($cookieKey, null, -1);
unset($_COOKIE[$cookieKey]);
}
}
If you have access to the $_COOKIE superglobal just do
$past = time() - 86400;
foreach($_COOKIE as $name => $value) {
if(strpos($name, 'wp-postpass_') === 0) {
setcookie($name, '', $past);
unset($_COOKIE[$name]);
}
}
Related
I am now using this code for facebook. "https" is active and wordpress site.
<?php
$ref = $_SERVER['HTTP_REFERER'];
if (strpos($ref, 'facebook.com') != false) {
?>
DON'T SHOW ADS
<?php } else { ?>
SHOW ADS
<?php } ?>
This code works for facebook. I wanted to add twitter, but when I add twitter it doesn't work at all. I tried this.
if (strpos($ref, 'facebook.com', 'twitter.com', 't.co') != false) {
It didn't work that way. If else query or "false" is correct? How can I do it in the simplest way? If the visitor comes from Facebook, Twitter, I don't want to show ads. thanks
strpos() does not check multiple "needles" to look for. You can store them in an array
and iterate over each one individually though:
<?php
$ref = $_SERVER['HTTP_REFERER'];
$sitesWithAdsHidden = [
'facebook.com',
'twitter.com',
't.co',
];
$isHiddenSite = false;
foreach ($sitesWithAdsHidden as $site) {
if (strpos($ref, $site) !== false) {
$isHiddenSite = true;
break;
}
}
if ($isHiddenSite) {
?>
DON'T SHOW ADS
<?php } else { ?>
SHOW ADS
<?php } ?>
Note that I also changed the strpos comparison to !== because a non-strict check could lead to evaluating to false if the position is actually 0 (the start of the string).
First and foremost, directly from Wikipedia:
"The referrer field is an optional part of the HTTP request sent by the web browser to the web server."
Therefore, you should always check that the Http Referer exists in the request. You can achieve this by using !empty() or isset(), however, for future maintainability, you can also use array_diff and array_keys.
You can then also achieve this without having to iterate over an array using preg_match.
if(!array_diff(['HTTP_REFERER'], array_keys($_SERVER)))
if(preg_match('/facebook|twitter/', $_SERVER['HTTP_REFERER']))
// todo: disable adverts
You could also use the null cascading operator to reduce this to one line. Do this if you have no further checks to make from the $_SERVER global variable.
if(preg_match('/facebook|twitter/', $_SERVER['HTTP_REFERER'] ?? ''))
// todo: disable adverts
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;
?>
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.
I know there was a TONS of similar quesitons here, but I've tried already all suggestions posted in other questions, and nothing helped.
This is my function:
function makecookie($s, $d) {
if(empty($_COOKIE[#COOKIE_PATH . "[{$s}]"])) {
setcookie(#COOKIE_PATH . "[{$s}]", $d);
}
return true;
}
At the top of the document I got: ob_start(); and at the end of the document I got ob_end_flush();.
When I try:
echo setcookie(#COOKIE_PATH . "[{$s}]", $d);
exit;
It returns 1 what means 'true'. And cookie has been not set.
So why does it happen?
Once the cookie is set, you can retrieve it on next page load with $_COOKIE["name of cookie"]
#COOKIE_PATH doesn't look like valid/sensible PHP. Are you sure that isn't some sort of typo for (say) $COOKIE_PATH?
I want to do a loop, normally it is done with while do for etc but when the process is big I came up with a solution to refresh the page by echoing a javascript to refresh the page for the next loop.
for example:
The page is http://localhost/index.php --> this preforms the first iteration with $i=1;
at the end of the script it will be redirected to http://localhost/index.php?i=$i++
if (!$_GET['i']){
$i = 1;
}else{
$i = $_GET['i'];
}
if ($i<500){
// proceed with $i = $_GET['i']
//then redirect to http://localhost/index.php?i=$i++
}else{
echo "done";
}
Now, consider a situation that the imput parameters come from a FORM to this script. (i.e. $parameter1 , $parameter2, $parameter3)
Then I have to pass them every time to new url (next iteration).
At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url?
At normal work I can pass them as GET variable to new url but how can I pass them if I don't want the user be able to see the value of parameters in url?
You can not with the bare redirect, but if you're talking about a specific user, you can do so by assigning those parameters as session variables Docs and then passing the session id as an additional parameter (or trust the user has cookies enabled).
function do_redirect($i, Array $parameters)
{
$i = (int) $i;
$parameters['i'] = $i; // save to session as well
$_SESSION['parameters'] = $parameters;
// redirect to http://localhost/index.php?i=$i&SID
}
if (is_form_request())
{
$parameters = get_form_parameters();
do_redirect(1, $parameters);
}
elseif (is_redirect_loop_request())
{
$parameters = $_SESSION['parameters'];
$i = $parameters['i'];
if ($i < 500)
{
do_redirect($i++, $parameters);
} else {
echo "done.";
}
}
Not to be rude, but both answers above are quite prone to security issues (but the session solution is the best one). As for the 'encryption' solution of #itamar: that's not exactly encryption... This is called 'Caesar cypher' (http://en.wikipedia.org/wiki/Caesar_cipher), which is indeed as safe as a paper nuclear bunker...
It can be much easier and safe as can be; do not save the iteration in the session, but in the database. For the next request, the only thing you have to do is get the iterator from the database and go on with whatever you want to do. Sessions can be stolen, meaning someone could let you iterate from, say, $i=10 a thousand times. It cannot be done when the iterator is stored in a secure database.