Set Cookie if Contact Form 7 was sent - php

i want to set a cookie if a specified form (Contact Form 7) was sent.
If is write the code into the init-call it works:
function process_post() {
if( isset( $_POST['kampagne'] ) ) {
setcookie('cid', get_option( 'cf7-counter', 0) + 1 , time()+3600, '/');
}
}
add_action( 'init', 'process_post' );
But that's not good, because the value of cookie is an id - stored in database, which i must get in the moment where the form will send.
So I want to set the cookie in the "wpcf7_before_send_mail" hook. But within that the cookie will not generate.
function wpcf7_do_something($WPCF7_ContactForm)
{
$submission = WPCF7_Submission :: get_instance();
if ( $submission ){
$posted_data = $submission->get_posted_data();
if ( empty( $posted_data ) ){ return; }
$changed_name = get_option( 'cf7-counter', 0) + 1;
update_option('cf7-counter', $changed_name);
$mail = $WPCF7_ContactForm->prop( 'mail' );
$new_mail = str_replace( '[cf7-counter]', '00'. $changed_name .'', $mail );
$WPCF7_ContactForm->set_properties( array( 'mail' => $new_mail ) );
return $WPCF7_ContactForm;
}
}
add_action("wpcf7_before_send_mail", "wpcf7_do_something");
I hope you can help me.
Thank you very much!
Best regards.

But that's not good, because the value of cookie is an id - stored in database, which i must get in the moment where the form will send.
So what you need is the ID that will be stored into the database when creating the cookie.
Create it
if( isset( $_POST['kampagne'] ) ) {
$cookie = 'cid';
$id = uniqid("cid:", true);
setcookie($cookie, $id, $_SERVER['REQUEST_TIME'] + HOUR_IN_SECONDS, '/', ini_get('session.cookie_domain'), (bool)ini_get('session.cookie_secure'), (bool)ini_get('session.cookie_httponly'));
$_COOKIE[$cookie] = $id;
}
; and store it
$cookie = 'cid';
$WPCF7_ContactForm->set_properties(
[
'mail' => $new_mail,
'cid' => $_COOKIE[$cookie],
]
);
.
The contact form transaction now has the id that is in the cookie.
It is independent to get_option( 'cf7-counter', 0) by binding the submission to its own identifier - like the cookie is not the cf7-counter option.
Take note on explicitly setting $_COOKIE[$cookie] = $id;, always. This is to have the ID in the request itself.
Take double note on this action, as the code does set the cookie with a new ID even if it was already set. If that is not your intention, check if the cookie is unset beforehand (later references on setting a cookie in Wordpress have it, too).
It is now more eventually consistent, up to the level of uniqueness of the uniquid() function (study it if you want to make use of it), which is an improvement over the situation where the chance of being inconsistent was much higher (that is when using the cf7-counter option).
An insecure random-unique ID normally is enough for short term transaction tagging, e.g. having it for an hour in the cookie.
Which is something you may want to put more of your attention to. And the example is less Wordpress specific, there is more to get from in Wordpress like nonces, keys, salts, cookie-paths, user-level cookies etc. pp. to adhere to that system specifically.
It requires you to study Wordpress first, which I can't take of your shoulders, and there is even more to learn first, like how cookies work. Perhaps ask the more general questions first that you have to close such gaps.
Another answer I was thinking about first is to take a more fitting action so that you have the id the moment you can do both: setting the cookie and storing to the database.
As it has been commented, such a solution would need to find the right place in time. But that is merely how cookies work.
(And not specifically Wordpress.)
As you have already seen yourself, the action you wanted to use did not work.
And even if you would find such another action, this is still Wordpress, and it would be unpredictable that it would suffice: The cookie might be set in your tests, but not when a user visits the site (or any site that is out there with Contact Form 7 which this answer should answer if it is worth it).
To set a cookie in Wordpress, there is no free choice of the action to do it in, but it first of all needs to set the cookie for which the action is invariant:
How to set a cookie in Wordpress
Setting a redirect cookie in wordpress
As the action is set in stone to set a cookie, this goes back to the answer above.
However this is not Wordpress SE, but Stackoverflow so I've put the focus more on the PHP code itself where it relates to the PHP configuration and only HOUR_IN_SECONDS is a constant from Wordpress in it. See as well my comment on it about more specific Wordpress features you may want to add to it.
It hopefully answers your question to the level you need it.

Related

PHP Active Session Warning in wordpress

I know this question is frequently asked on this forum, but none of the proposed solutions has worked for me, basically, I am a WordPress plugin developer and developing a plugin whose session starts in the init file but close when the client closes his/her browser, and it is necessary to keep the session open. In this case, how can I get rid of this warning? Maybe I should use something other than the session or what you suggest.
Till now there are different proposed solutions like Use
if ( !session_id() ) {
session_start( [
'read_and_close' => true,
] );
}
but with this technique, I can never be able to use sessions in my plugin, and the whole functionality goes on the ground.
Any help in this regard would be much appreciated.
thanks
WordPress plugin or theme developers cannot use php's session subsystem as you have discovered.
If you need to save some kind of global context for your plugin to work, use WordPress's add_option() function to save it at the end of each operation. You can retrieve your context using get_option().
If you need per-user context, use add_user_meta() to save it and get_user_meta() to retrieve it. Like this:
$id = get_current_user_id();
$myContext = get_user_meta( $id, 'my_plugins_meta_tag_name' );
...
add_user_meta( $id, 'my_plugins_meta_tag_name', $myContext);
WordPress uses a database table to store these sorts of options. Some sites put an object cache in front of the table. But these APIs are how you do what you want to do.
In your plugin's deactivation hook, please consider calling delete_option() to clean up that storage. And, if you use per-user context, please consider using delete_user_meta() to remove your user_meta item from all of them.
$users = get_users( array( 'fields' => array( 'ID' ) ) );
foreach($users as $user){
delete_user_meta ( $user->ID, 'my_plugins_meta_tag_name' );
}
As for sensitive information, WordPress offers no other place to put it. And, if you were using sessions, php would need to put it somewhere as well. By default, php puts session data in the filesystem of the server. That's why WordPress hashes user passwords before storing them.

WordPress Store Authentication token in memory

I am looking for some help concerning WordPress plugin development. My plugin queries an API which requires an Authentication Token, that token is fetched via a Token delivery APi. The token expire every 3600 seconds.
I would like to store the Token, in a persistent way (for all sessions , like server side caching) and update it only when needed. Multiple Api call could be done with the same token. The problem is, if I store the token in a global variable, it gets reset each time a user reload a page which uses my plugin.
https://wordpress.stackexchange.com/questions/89263/how-to-set-and-use-global-variables-or-why-not-to-use-them-at-all
After looking for answer I found:
-WP_CACHE , but it is not persistent.
-I know I can store the token in the Database, but a Token in Database is not a use case I found elegant
-Tool such as Redis Object Cache for PHP but I found it to be really complicated , installing etc...
Is there any good practice or easy way of doing this? I only need to keep a string for an hour and access it within the plugin in PHP.
Thank you.
https://wordpress.stackexchange.com/questions/89263/how-to-set-and-use-global-variables-or-why-not-to-use-them-at-all
In this case, I would work with WordPress transients:
https://developer.wordpress.org/reference/functions/set_transient/
https://developer.wordpress.org/reference/functions/get_transient/
To set a transient, you can use this code:
$transient = 'your_token_name';
$value = 'your_token'
$expiration = 3600
set_transient( $transient, $value, $expiration );
To receive the value of your transient again, you can use:
$token = get_transient( $transient );
Using these methods is better than update_option or get_option since WordPress manages the expiration (deletion) of transients completely, so you don't have to implement your own logic for this.
Before you pass the value to the transient method, you can encrypt and decrypt it by storing a salt/key in your wp-config.php. You can find more infos about this topic here:
http://php.net/manual/es/function.openssl-encrypt.php
http://php.net/manual/es/function.openssl-decrypt.php
To define a constant in WordPress you need to go to your wp-config.php file and add it between the "you can edit" words:
define( 'YOUR_SALT', '12345678' );
You can read it again as a normal constant in WordPress:
$salt = YOUR_SALT;

WordPress/WC session not carried to next page

Simply trying to store and retrieve unregistered customer data from page to page in a custom checkout template. I've stripped it down to the bare bones to try to pinpoint the issue.
This
<?php
$customer = WC()->customer;
$customer->set_billing_first_name("WORKING!!!");
$customer->save();
var_dump($customer->get_billing());
?>
Outputs this
array (size=2)
'country' => string 'US' (length=2)
'first_name' => string 'WORKING!!!' (length=10)
But then this
<?php
$customer = WC()->customer;
//$customer->set_billing_first_name("WORKING!!!");
//$customer->save();
var_dump($customer->get_billing());
?>
Outputs this
array (size=1)
'country' => string 'US' (length=2)
Even though I should still be firmly within the same session, and therefore should get the data stored before the comments. All I did was refresh the page after commenting out those two lines.
Am I completely wrong about these methods?
Checked
Environment is configured entirely correctly. Even had someone else double-check it for me. URLs, caches, etc.
It does appear to work when logged in, but the vast majority of users never do so that's not very helpful.
Have tried this on two different servers (one local, one remote) and have the same issue.
Started fresh with a new WP+WC install, created a blank theme, functions.php that does the above on init code. Same exact issue.
If $customer->save() doesn't persist the changes you made to the customer's data (e.g. $customer->set_billing_first_name('Test')), then it's likely because the customer is not registered to the site or not logged-in, where $customer->get_id() is 0.
And that is normal because the user's ID or the session's ID is required in order to properly save the changes and make it persistent across different pages.
So when the user is not registered/logged-in, WooCommerce doesn't start its session until the user logs in, or that he/she added a product into the cart.
But you can manually start the session, like so: (add the code to the active theme's functions.php file)
add_action( 'woocommerce_init', function(){
if ( ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
} );
And then, changes to the customer's data would then be carried on to other pages so long as cookies are enabled on the browser, because just like WordPress, WooCommerce stores its session ID (the user ID or an auto-generated ID/hash) in the cookies — and the session ID is used to set/retrieve the session data in the database — the table name is woocommerce_sessions if without any table prefix.
Try this after starting the WooCommerce session:
$customer = WC()->customer;
// Change 'Test' if necessary - e.g. 'Something unique 123'
if ( 'Test' !== $customer->get_billing_first_name() ) {
$customer->set_billing_first_name( 'Test' );
echo 'First name added to session<br>';
} else {
echo 'First name read from session<br>';
}
And this one — you should see a new date on each page load: (well, the one you've set previously)
echo WC()->session->get( 'test', 'None set' ) . '<br>';
WC()->session->set( 'test', current_time( 'mysql' ) );
echo WC()->session->get( 'test', 'It can\'t be empty' );
Are you using the Url set in Wordpress? It seems that it stores the cookie based on the url configured in the app rather than the actual one.
Hope this helps.
Source: https://en.blogpascher.com/wordpress-tutorial/How-correct-the-loss-of-session-on-wordpress

CakePhp sessions clear almost instantly, but only sometimes

I have adopted a CakePhp 2 project. We get to the project from another project, linking to the CakePhp project with a "token" and a conference ID as a parameter in the URL. Using that token, we authorize the user, and using the conference ID get the information from the database. The session value "auth" is set to true.
We have it running on 2 "platforms" locally on my system using a vagrant machine, and on a production server. Locally the session value dies really quick and at random times. On the production server not as often, but the issues we have where Ajax calls don't seem to do what are expected, we believe are being caused by a similar issue. We have many different projects, all Laravel, with zero issues where the session values clear. This issue is strictly with the CakePhp project.
All the authentication magic happens in the beforeFilter method. The code:
public function beforeFilter() {
$session = new CakeSession();
/**
*
* We will check if the current user is authorized here!
*
*/
// If the visitor is coming for the first time, there should be a parameter in
// the URL that is the auth code to check against the database.
if ( ( isset($_GET['conf']) && is_numeric($_GET['conf']) ) && isset($_GET['token']) ) {
$getConference = ClassRegistry::init('Conference')->find('first', ["conditions" => ["conference_id"=>$_GET['conf'] ]]);
$checkToken = ClassRegistry::init('User')->find('first', ["conditions" => ["remember_token"=>$_GET['token'] ]]);
if ($getConference && $checkToken) {
$checkToken['User']['remember_token'] = $this->generateToken();
if ( ClassRegistry::init('User')->save( $checkToken ) ) {
$session->write('auth', true);
$session->write('conferenceId', $_GET['conf']);
$this->redirect('/');
}
}
else {
$session->write('auth', false);
$session->write('conferenceId', null);
}
}
if (! $session->read('auth') || $session->read('conferenceId') == null ) {
echo "No permission!";
exit;
}
}
At the top of the controller:
App::uses('CakeSession', 'Model/Datasource');
When the URL parameters are present, it traps them, does the work, and redirects to the home route without the parameters.
$this->generateToken();
Creates a new token, and overwrites the old one in the database.
There are 2 main controllers. The controller with this code is the main projects controller. The only time it is really hit is the first time you go to the project, and we hit the index method. From there everything else is AJAX calls to the other controller. There is one link, a "home" type link that will hit that index method.
Sometimes these Ajax calls stop working, and clicking that home link will output "No Permission" instead of the expected html in the container the Ajax call outputs too.
Steps to troubleshoot led me to putting this beforeFilter method on the top of the second controller. Now, randomly I'll get no permission. Sometimes, when I'm on the main project that links to this CakePhp project, I click that link, I get no permission right off the bat.
I found this page: cakephp takes me to login page on multiple request and have tried to set the session details like this:
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => '300' // <- added this element
));
And I have tried:
Configure::write('Session.timeout', '300');
Additionally, I have tried cookieTimeout in both of those cases.
I've also tried
Configure::write('Security.level', 'low');
and included
Configure::write('Session.autoRegenerate', true);
In any order, any of these cause the session to bomb out immediately. I get "No permission on page load, and never get anywhere.
The code for this project is honestly crap. The developer who wrote it had mistakes and errors all over the place. On top of that, we are a Laravel shop. We are just trying to keep the project limping along until sometime in the future when we can nuke it from orbit. So we just need to get this working. Any thoughts on what could be causing this? Any other details I am forgetting to include that would help troubleshoot this issue?
Thanks
Reading & writing session data
You can read values from the session using Set::classicExtract() compatible syntax:
CakeSession::read('Config.language');
$key should be the dot separated path you wish to write $value to:
CakeSession::write('Config.language', 'eng');
When you need to delete data from the session, you can use delete:
CakeSession::delete('Config.language');
You should also see the documentation on Sessions and SessionHelper for how to access Session data in the controller and view.

Setting a cookie in WordPress plugin, cookie gets deleted automatically

I'm currently trying my hands on WordPress plugind developement for an exercise and came across some little snag.
The plugin is designed to display a simple poll in a widget on the front page. Once the visitor has voted, I use setcookie to drop a cookie containing his vote for 30 days, and some simple code to change the widget so that it shows the results and the user cannot vote again until a new poll is proposed. The problem is, voting is still possible, the results are never shown. Looking at the logs with the developer's tools, I found that the cookie is deleted the second it lands on the client browser. Does anybody know why, and how I can correct that?
Here's the code. First, the action hook:
public function __construct()
{
parent::__construct('poll_plugin', __('Polls', 'poll_plugin'), array('description' => __('Simple poll widget', 'poll_plugin')));
add_action('init', array($this, 'save_votes'));
}
Then, the actual action:
public function save_votes()
{
global $wpdb;
/*Cookie setting, 30 days expiration */
if ( isset($_POST['option']) && !isset($_COOKIE['Poll_Votes']))
{
unset($_COOKIE['Poll_Votes']);
setcookie('Poll_Votes', $choix, 30 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);
$choix = $_POST['option'];
$id_choix = $wpdb->get_var("SELECT id FROM {$wpdb->prefix}poll_options WHERE label = '$choix'");
$wpdb->query("UPDATE {$wpdb->prefix}poll_results SET total = total+1 WHERE option_id = '$id_choix'");
};
/*Testing the presence of a new poll */
$vote = $_COOKIE['Poll_Votes'];
/*If the cookie's value isn't found in the db, the poll's changed, so we reset the cookie*/
if (is_null($wpdb->get_var("SELECT * FROM {$wpdb->prefix}poll_options WHERE label = '$vote'")))
{
setcookie('Poll_Votes', '', time()-3600);
}
}
Quick note here, I already tried commenting the line designed to unset the cookie, it changed nothing.
The only other time where the cookie is mentioned is via the $_COOKIE global, in a isset().
And lastly, please forgive my english, I'm french :)

Categories