I randomly choose a dominant color when the visitor arrive on the website, then I want to store this color in a cookie during 1 hour.
And I'm working on wordpress.
For the moment I've got this on my function.php
add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
$colourRange = array('#965c5d', '#5f797a', '#bc8b6a', '#7fc3a2', '#89383a', '#f28c5d');
$colourTheOnlyOne = $colourRange[array_rand($colourRange, 1)];
$cookieColor = 'cookieColor';
$cookieValue = $colourTheOnlyOne;
setcookie( $cookieColor, $cookieValue, 60 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
}
The problem is every time I refresh the page a new color is set… don't understand why !
You need to check the cookie value to see if it there to avoid resetting it. You are essentially overwriting your cookie every time you reload the page.
add_action( 'init', 'setting_my_first_cookie' );
function setting_my_first_cookie() {
$cookieColor = 'cookieColor';
if (!isset($_COOKIE[$cookieColor])) {
$colourRange = array('#965c5d', '#5f797a', '#bc8b6a', '#7fc3a2', '#89383a', '#f28c5d');
$cookieValue = $colourRange[array_rand($colourRange, 1)];
setcookie( $cookieColor, $cookieValue, 60 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
}
}
This checks for the cookie 'cookieColor' and if it is found, does not write the cookie.
So I finally solve my problem with that and after in the template I check if a cookie is available, if not I display the
$colorRange = array('#965c5d', '#5f797a', '#bc8b6a', '#7fc3a2', '#89383a', '#f28c5d');
$cookieValue = $colorRange[array_rand($colorRange, 1)];
global $cookieValue;
add_action( 'init', 'setting_cookie' );
function setting_cookie() {
global $cookieValue;
$cookieTheValue = $cookieValue;
$cookieColor = 'cookieColor';
if (!isset($_COOKIE[$cookieColor])) {
setcookie( $cookieColor, $cookieTheValue, time()+60, COOKIEPATH, COOKIE_DOMAIN );
}
}
Related
if(isset($_POST["cartDelete"])){
$item_ID = $_POST["hidden_id"];
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
unset($cart_data[$item_ID]);
$item_data = json_encode($cart_data);
setcookie('shopping_cart', $item_data, time() + (86400 * 30));
header("Location: cart");
print_r($cart_data);
}
if(isset($_POST["QTYedited"])){
$item_ID = $_POST["hidden_id"];
$item_QTY = $_POST["QTYedited"];
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
$cart_data[$item_ID]["item_QTY"] = $item_QTY;
$item_data = json_encode($cart_data);
setcookie('shopping_cart', $item_data, time() + (86400 * 30));
header("Location: cart");
}
I'm writing an webshop in php, but in this part the cookie somehow won't be saved. The whole fun is, with one item in the cart everything is working. The problem beginning with at least two items.
I've tried everything I knew. You can test the page with webshop.abrisx.nhely.hu
First, make sure that the cookie is enabled in your browser and note that some illegal characters will cause the cookie not to be stored,
Try calling urlencode() on your string before sending it to the cookie.
ex:
setcookie('shopping_cart', urlencode($item_data), time() + (86400 * 30), '/');
I think this will solve your problem.
In a webshop product page, i am sending the product id with ajax to this php file:
<?php
include_once("connect.php");
if(isset($_POST['product_id']))
{
$product_id = mysqli_real_escape_string($kapcs, $_POST['product_id']);
$cookie_name = "kedvenc_termek";
$cookie_value = $product_id;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
echo 'Saved to the favorit products.';
}
?>
My problem is, that when i have id-s in the kedvenc_termek cookie, and i want to add another product id as favorit product, the new cookie value will overwrite the value in the cookie.
For example, if i have 179 stored in the cookie, and i add the 180 product id to it, the cookie value will be 180, and not 179,180.
You're overwriting the value every time. So you need to append the value, not overwrite it
$cookie_name = "kedvenc_termek";
$cookie_value = '';
if(isset($_COOKIE[$cookie_name])) {
$cookie_value = $_COOKIE[$cookie_name] . ',';
}
$cookie_value .= $product_id;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
You need to use an array to save the data. You can use PHP's serialize() method to save array data as a string, and use unserialize() to read the data. Try this:
<?php
include_once("connect.php");
if(isset($_POST['product_id']) && is_int($_POST['product_id'])) {
$product_id = $_POST['product_id'];
$cookie_name = "kedvenc_termek";
$data = unserialize($_COOKIE[$cookie_name]);
if(!in_array($product_id, $data)) {
$data[] = $product_id;
}
setcookie($cookie_name, serialize($data), time() + (86400 * 30), "/");
echo 'Saved to the favorite products.';
}
?>
I have added a post in my wordpress site using php including the code below. I deleted the post from my wordpress admin and tried to add it again using the same code but post_exists returns true instead of false.
What is wrong? Any help appreciated.
<?php
require_once( '../chinesegreekoffers/wp-load.php' );
require_once( ABSPATH . 'wp-admin/includes/post.php' );
/*******************************************************
** POST VARIABLES
*******************************************************/
$postType = 'post'; // set to post or page
$userID = 1; // set to user id
$categoryID = '21'; // set to category id.
$postStatus = 'publish'; // set to future, draft, or publish
$leadTitle = 'Adding titlenew : '.date("n/d/Y");
$leadContent = '<h1>Vacations</h1><p>Vacations are the best thing in this life.</p>';
$leadContent .= ' <!--more--> <p>Expensive they are, but they are totally worth it.</p>';
/*******************************************************
** TIME VARIABLES / CALCULATIONS
*******************************************************/
// VARIABLES
$timeStamp = $minuteCounter = 0; // set all timers to 0;
$iCounter = 1; // number use to multiply by minute increment;
$minuteIncrement = 1; // increment which to increase each post time for future schedule
$adjustClockMinutes = 0; // add 1 hour or 60 minutes - daylight savings
// CALCULATIONS
$minuteCounter = $iCounter * $minuteIncrement; // setting how far out in time to post if future.
$minuteCounter = $minuteCounter + $adjustClockMinutes; // adjusting for server timezone
$timeStamp = date('Y-m-d H:i:s', strtotime("+$minuteCounter min")); // format needed for WordPress
/*******************************************************
** WordPress Array and Variables for posting
*******************************************************/
$new_post = array(
'post_title' => $leadTitle,
'post_content' => $leadContent,
'post_status' => $postStatus,
'post_date' => $timeStamp,
'post_author' => $userID,
'post_type' => $postType,
'post_category' => array($categoryID)
);
/*******************************************************
** WordPress Post Function
*******************************************************/
$finaltext = '';
$post_id = post_exists( $leadTitle );
if (!$post_id) {
// code here
$finaltext .= ' - Post title does not exists i am going to add it<br>';
$post_id = wp_insert_post($new_post);
/*******************************************************
** SIMPLE ERROR CHECKING
*******************************************************/
if($post_id){
$finaltext .= 'Yay, I made a new post.<br>';
echo "finaltext success: ".$finaltext."<br><br>";
} else{
$finaltext .= 'Something went wrong and I didn\'t insert a new post.<br>';
echo "finaltext error: ".$finaltext."<br><br>";
}
}
else {
$finaltext .= ' - Post title already exists i dont need to add it again<br>';
}
echo $finaltext;
?>
The result of $finaltext is : - Post title already exists i dont need to add it again
I have found the solution. After you trash the post the file is not immediately deleted. You need to go to the trash select the post you want to permantly delete and select delete permantly from the drop down menu and hit apply. This nearly drive me crazy!
I'm looking for a way to limit the attempts an user can make to login. I saw this plugin but it hasn't been updated in over 2 years.. and if available I always prefer a way that doesn't involve plugins. :)
Is there a variable that can be set in wp-config.php?
Otherwise, is there a way to achive this via webserver config? I have nginx 1.7.4.
I founded this class.
<?php
/**
* CLASS LIMIT LOGIN ATTEMPTS
* Prevent Mass WordPress Login Attacks by setting locking the system when login fail.
* To be added in functions.php or as an external file.
*/
if ( ! class_exists( 'Limit_Login_Attempts' ) ) {
class Limit_Login_Attempts {
var $failed_login_limit = 3; //Giris Denemesi
var $lockout_duration = 1800; //Sureyi sn cinsinden giriniz. 30 dakika: 60*30 = 1800
var $transient_name = 'attempted_login'; //Transient used
public function __construct() {
add_filter( 'authenticate', array( $this, 'check_attempted_login' ), 30, 3 );
add_action( 'wp_login_failed', array( $this, 'login_failed' ), 10, 1 );
}
/**
* Lock login attempts of failed login limit is reached
*/
public function check_attempted_login( $user, $username, $password ) {
if ( get_transient( $this->transient_name ) ) {
$datas = get_transient( $this->transient_name );
if ( $datas['tried'] >= $this->failed_login_limit ) {
$until = get_option( '_transient_timeout_' . $this->transient_name );
$time = $this->when( $until );
//Display error message to the user when limit is reached
return new WP_Error( 'too_many_tried', sprintf( __( '<strong>HATA</strong>: Kimlik dogrulama sinirina ulastiniz, %1$s sonra lutfen tekrar deneyiniz.' ) , $time ) );
}
}
return $user;
}
/**
* Add transient
*/
public function login_failed( $username ) {
if ( get_transient( $this->transient_name ) ) {
$datas = get_transient( $this->transient_name );
$datas['tried']++;
if ( $datas['tried'] <= $this->failed_login_limit )
set_transient( $this->transient_name, $datas , $this->lockout_duration );
} else {
$datas = array(
'tried' => 1
);
set_transient( $this->transient_name, $datas , $this->lockout_duration );
}
}
/**
* Return difference between 2 given dates
* #param int $time Date as Unix timestamp
* #return string Return string
*/
private function when( $time ) {
if ( ! $time )
return;
$right_now = time();
$diff = abs( $right_now - $time );
$second = 1;
$minute = $second * 60;
$hour = $minute * 60;
$day = $hour * 24;
if ( $diff < $minute )
return floor( $diff / $second ) . ' saniye';
if ( $diff < $minute * 2 )
return "yaklasik 1 dakika once";
if ( $diff < $hour )
return floor( $diff / $minute ) . ' dakika';
if ( $diff < $hour * 2 )
return 'yaklasik 1 saat once';
return floor( $diff / $hour ) . ' saat';
}
}
}
//Enable it:
new Limit_Login_Attempts();
Altough the post is quite old I will provide my findings because I couldn't find the answer myself until today.
Looked in the codex and whatnot, but everywhere I got ordered to use a plugin - which I do not want.
So to answer your question:
Is there a variable that can be set in wp-config.php?
No, there is not a variable you can set in wp-config.
Otherwise, is there a way to achive this via webserver config? I have nginx 1.7.4.
I am no webserver magician but I guess not.
But! - From this blog post by Etienne Tremel I got that there is a filter:
add_filter( 'authenticate', (...)
and function hook:
add_action( 'wp_login_failed', (...)
you can use to tap into the login-process. With that information I was able to anticipate on login-attempts with my own custom code.
In his blog-article you'll find a copy paste piece of code to dump in your functions.php file.
Protecting this kind of functionality is indeed best done outside this application and even it's programming language.
Denying connections is typically the task of a firewall and this also protects the webserver.
Put these two together you quickly arrive at fail2ban or sshguard. A hosting company I work with has done exactly that, so I know it's possible to do that. They use a four strikes and you're out policy. I'm not sure if their code is public, but it shouldn't be to hard to come up with a recipe, both have excellent documentation.
The best place to start would be downloading and looking under the hood of a plugin that already does this. Studying what methods can be employed will help you in your implementation regardless if the plugin is up to date or not.
I am new to cookies. I created a user login php class that uses a cookie to store a unique MD5 key to remember a user that has logged in. However, the cookie is not being reset when the user logs out. I created a function from code I found on stack overflow to clear the cookies on logout.
static public function clearCookies()
{
$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
$value = '';
setcookie( $key, $value, $past );
setcookie( $key, $value, $past, '/' );
}
}
However, the cookie is still not being cleared.
This is the line of code that sets the cookie
setcookie("auth_key", $authKey, time() + 60 * 60 * 24 * 7);
Thanks ahead of time
Try to add
static public function clearCookies()
{
$past = time() - 3600;
foreach ( $_COOKIE as $key => $value )
{
$value = '';
setcookie( $key, $value, $past );
setcookie( $key, $value, $past, '/' );
unset($_COOKIE[$key]);
}
}
You have to note that changed cookies are readable AFTER sending them to client (if you do not set them manually via $_COOKIE), so the next refresh.
Here is the solution that worked.
I changed
setcookie("auth_key", $authKey, time() + 60 * 60 * 24 * 7);
to
setcookie("auth_key", $authKey, time() + 60 * 60 * 24 * 7, '/');
It seems that the cookie was not being reset because the url it was being reset from was different than the url it was set in. After adding '/' it could be reset from the new url.