wordpress wp_signon function not working - wordpress

I am using wp_signon() function to login the user. I am doing this like
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
i want to send user to home page after login.
But i Am facing following error:
Warning: Cannot modify header information - headers already sent by (output started at E:\xampp\htdocs\wpmoodle\wp-content\themes\twentyten\header.php:12) in E:\xampp\htdocs\wpmoodle\wp-includes\pluggable.php on line 690.
Thanks in advance.

wp_signon() needs to run before you've sent any of your actual page to the browser.
This is because part of what wp_signon() does is to set your authentication cookies. It does this by outputting a "Set-Cookie: ..." header -- if you look at line 690 of pluggable.php, where your error comes from, you'll see that that line sets a cookie.
So, because wp_signon() outputs headers, you can't already have sent any content -- because headers must always be output before content.
However, the error indicates that you've already sent some output -- on line 12 of header.php, presumably some of the first HTML of the standard WordPress theme.
This basically indicates that you need to move your wp_signon() call to somewhere earlier in the WordPress processing, so it has a chance to output its headers before any page content is sent.

If someone needs it, here is my solution:
function custom_login() {
if (isset($_POST['submit'])) {
$login_data = array();
$login_data['user_login'] = sanitize_user($_POST['username']);
$login_data['user_password'] = esc_attr($_POST['password']);
$user = wp_signon( $login_data, false );
if ( is_wp_error($user) ) {
echo $user->get_error_message();
} else {
wp_clear_auth_cookie();
do_action('wp_login', $user->ID);
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID, true);
$redirect_to = $_SERVER['REQUEST_URI'];
wp_safe_redirect($redirect_to);
exit;
}
}
}
add_action( 'after_setup_theme', 'custom_login' );

Related

Redirect after login in custom login page WP

first sorry for my english
i have a problem of redirect an user when he is connected , i make that on a custom login page (modal)
when i put to submit
i call this code in connexion.php
<?php
define('WP_USE_THEMES', false);
require_once('../../../../wp-load.php');
global $qode_options_theme16;
global $wp_query;
global $wpdb;
// using ldap bind
$ldaprdn = "cn=gazano,dc=cerpweb,dc=local"; // ldap rdn or dn
$ldappass = "test"; // associated password
// connect to ldap server
$ldapconn = ldap_connect("192.168.209.7","389")
or die("Could not connect to LDAP server.");
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
$mdp = wp_hash_password('cerpcerp');
$wpdb->query("INSERT INTO wp_users (user_login,user_pass, user_nicename, user_email, user_url, user_activation_key, user_status,display_name) VALUES ('hjhjh', '$mdp','e51511','dsfdsf#live.be','15d15','ertre','0','jhjh')");
$user=wp_authenticate('hjhjh', 'cerpcerp');
$ie=wp_redirect(home_url());
my_login_redirect( $ie,' ', '1' );
} else {
echo "LDAP bind failed...";
}
}
?>
my Ldap works correctly , my insert Works as well and my wp_authenticate('hjhjh', 'cerpcerp'); works also,
but the problem is in my_login_redirect( $ie,' ', '1' )
the redirect in home works correctly but without connexion ...
and in my header.php a put this one
global $current_user;
$current_user = wp_get_current_user();
someone can help me
thank in advance
As far as I remember you need to exit() right after wp_redirect.
You have also some filter to do it
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

Symfony2 PHPWord response

I am trying to generate a docx document on Symfony2, using the PHPWord bundle.
In my controller, I succeed in returning a docx file, but it is empty, I think it comes from my faulty response format.
public function indexAction($id)
{
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
return new Response($objWriter->save('helloWorld.docx'), 200, array('Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
}
Try this class
<?php
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;
use Symfony\Component\HttpFoundation\Response;
class WordResponse extends Response
{
/**
* WordResponse constructor.
* #param string $name The name of the word file
* #param PhpWord $word
*/
public function __construct($name, &$word)
{
parent::__construct();
// Set default zip library.
if( !class_exists('ZipArchive')){
Settings::setZipClass(Settings::PCLZIP);
}
$writer = IOFactory::createWriter($word, 'Word2007');
//Set headers.
$this->headers->set("Content-Disposition", 'attachment; filename="' . $name . '"');
$this->headers->set("Content-Type", 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$this->headers->set("Content-Transfer-Encoding", 'binary');
$this->headers->set("Cache-Control", 'must-revalidate, post-check=0, pre-check=0');
$this->headers->set("Expires", '0');
$this->sendHeaders();
$writer->save('php://output');
}
}
Then in your controller do:
return new WordResponse($phpWord, "filename.docx");
Thanks a lot for your answer.
I achieve using the 2nd method, which is in my opinion the best.
I just have to return a response, otherwise the file was generated, but stuck in the web directory.
Using this response, everything was fine and a download prompt appeared, with the "full" file.
Here's my code :
$PHPWord = new PHPWord();
$section = $PHPWord->addSection();
$section->addText(htmlspecialchars(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
));
// Saving the document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($PHPWord, 'Word2007');
$filename="MyAwesomeFile.docx";
$objWriter->save($filename, 'Word2007', true);
$path = $this->get('kernel')->getRootDir(). "/../web/" . $filename;
$content = file_get_contents($path);
$response = new Response();
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
$response->setContent($content);
return $response;
PHPWord->save() returns a true value so that would be why your file is not being downloaded. With your return new Response() you are setting the content of your response to true (the result of your save call) which is why your response is empty.
You have 2 (and probably more that I haven't thought of) options to generate and download this file..
1. Save your file to a temp folder and server from there
$filename = sprintf(
'%s%sDoc-Storage%s%s.%s',
sys_get_temp_dir(),
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
uniqid(),
'docx'
);
$objWriter->save($filename);
$response = new BinaryFileResponse($filename);
For more info on the BinaryFileResponse see the docs.
2. Ignore Symfony and serve directly via the PHPWord action
$objWriter->save($filename, 'Word2007', true);
exit();
The ->save method provides all of the actions to download the generated file internally (see the code) so all you need to do is set the format and the third parameter to true and it will handle all of the headers for you. Granted it won't be returning a Symfony response but you will be exiting out before you get to that exception.

User authentication through wp_signon(); help needed

I use form to send POST request to a page and to login user with wp_signon() in order to authenticate user to my wordpress installation as described in WP documentation:
$creds = array();
$creds['user_login'] = $_POST["user-login"];
$creds['user_password'] = $_POST["user-password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
After this little piece of code I'm checking if user was logged in:
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }
But I got FAIL! all the time. Then after sniffing around I found this little trick:
wp_set_current_user( $user );
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }
I've got SUCCESS on this one but when I leave this page I got FAIL again and again.
Can anyone explain me how to login user with wp_signon() without logging her out after page is changed or reloaded or whatever.
I've got desirable result when I go to /wp_admin and login with WP's default login form. I can navigate through every page of my WP site remaining logged-in all the time. But when I try to do this outside the default form with wp_signon(); I FAIL!.
Maybe I use it wrong? Guide me! PLEASE!
It was my mistake. I used the whole structure on my localhost server which for some reason didn't allow wordpress to work correctly. After I've uploaded the template into an external server I've got this working.
Sorry for bothering! It won't happen again ...

Adding a wordpress user to Salesforce Contact

I'm trying to do a relatively simple task by hooking into the Wordpress registration and adding the user that's being registered to a Salesforce db. When I run the Salesforce db code outside of Wordpress it works flawlessly, but when I test this by registering on my wordpress website, I get an error stating: INVALID_LOGIN: Invalid username, password, security token; or user locked out.
Additionally, I receive this error from Wordpress "Cannot modify header information - headers already sent" which doesn't allow me to view the entire object data that's being sent to Salesforce.
This is my code:
$SF_USERNAME = 'test';
$SF_PASSWORD = 'test';
define( 'CD_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
require_once (CD_PLUGIN_PATH . 'Toolkit/soapclient/SforceEnterpriseClient.php');
require_once (CD_PLUGIN_PATH . 'Toolkit/soapclient/SforceHeaderOptions.php');
function add_user_to_SF($user_id) {
$user = get_userdata($user_id);
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(CD_PLUGIN_PATH . 'Toolkit/soapclient/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($SF_USERNAME, $SF_PASSWORD);
print '<pre>';
print_r($mylogin);
print '</pre>';
print '<br/><br/>';
$sObject = new stdclass();
$sObject->FirstName = $user->first_name;
$sObject->LastName = $user->last_name;
$sObject->Email = $user->user_email;
//echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create(array($sObject), 'Contact');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
$errors->add( 'demo_error', __(print_r($_POST),'mydomain') );
$errors->add( 'demo_error', __($mySforceConnection->getLastRequest(),'mydomain') );
$errors->add( 'demo_error', __($e->faultstring,'mydomain') );
return $errors;
}
}
add_filter( 'registration_errors', 'add_user_to_SF', 10, 3 );
This is a php scope issue.
Adding:
global $SF_USERNAME;
global $SF_PASSWORD;
inside the function fixed the problem.
It looks like you might be missing the security token. It's appended to the end of the password.
This link explains how to generate the token
https://login.salesforce.com/help/doc/en/user_security_token.htm
You need to add your salesforce account security token with password
eg. Password - "testing"
Security Token - "2321njjn32j32"
You need to pass as - "testing2321njjn32j32"
This will work properly.

Wordpress redirect issue, headers already sent

I am wondering, based on the code bellow, where I would want to put my wp_redirect function because where it currently is does nothing but spazzes out and sais:
Warning: Cannot modify header information - headers already sent by (output started at /***/***/WordPress/WordPressDev/wp-includes/script-loader.php:664) in /***/***/WordPress/WordPressDev/wp-includes/pluggable.php on line 881
Which I get because the page has already loaded. but I am un sure where to call this function.
I have replace my web site and any "personal data" with stars and example.com. How ever this code does work, it just wont redirect me.
thoughts?
function get_latest_version_zip(){
global $wp_filesystem;
if(current_user_can('update_themes')){
$aisis_file_system_structure = WP_Filesystem();
$aisis_cred_url = 'admin.php?page=aisis-core-update';
if($aisis_file_system_structure == false){
request_filesystem_credentials($aisis_cred_url);
$this->credential_check = true;
}
$aisis_temp_file_download = download_url( 'http://example.com/aisis/aisis_update/Aisis2.zip' );
if(is_wp_error($aisis_temp_file_download)){
$error = $aisis_temp_file_download->get_error_code();
if($error == 'http_no_url') {
add_action( 'admin_notices', 'aisis_framework_download_update_erors' );
}
}
$aisis_unzip_to = $wp_filesystem->wp_content_dir() . "/themes/" . get_option('template');
$this->delete_contents_check(); //Check if we need to delete the aisis core folder.
$aisis_do_unzip = unzip_file($aisis_temp_file_download, $aisis_unzip_to);
unlink($aisis_temp_file_download); //delete temp jazz
if(is_wp_error($aisis_do_unzip)){
$error = $aisis_do_unzip->get_error_code();
if($error == 'incompatible_archive') {
$this->aisis_incompatible_archive_errors();
}
if($error == 'empty_archive') {
$this->aisis_empty_archive_errors();
}
if($error == 'mkdir_failed') {
$this->aisis_mkdir_failed_errors();
}
if($error == 'copy_failed') {
$this->aisis_copy_failed_errors();
}
return;
}
//throwing errors
wp_redirect(admin_url('admin.php?page=aisis-core-options'));
exit;
}
}
in my functions.php file I placed the following code:
function callback($buffer){
return $buffer;
}
function add_ob_start(){
ob_start("callback");
}
function flush_ob_end(){
ob_end_flush();
}
add_action('wp_head', 'add_ob_start');
add_action('wp_footer', 'flush_ob_end');
with this I still get the error, I think I misunderstanding something....
Just replace the following line
add_action('wp_head', 'add_ob_start');
with
add_action('init', 'add_ob_start');
Output buffering should start before anything sent/echoed to the browser and wp_head hook occurs a bit later than init hook and till then headers already sent and also Keep/place it at the top of your functions.php before anything echoed/sent to the browser.
The problem is that somewhere in wordpress the header() function has been called and some output was already sent to the client while output buffering is off.
Headers have to be sent before any output, otherwise you get the error you described.
wp_redirect(admin_url('admin.php?page=aisis-core-options'));
The above line sets a header like this: header('Location: admin.php......');
Turning on output buffering via php.ini, at the index.php of wordpress or simply before anything is echo'ed to the client should take care of the error.
Details/Documentation can be found here: http://php.net/manual/en/book.outcontrol.php
simplest way i can think of is make your wordpress index.php look like this:
ob_start();
// content of your index.php here
ob_flush();
Another possibility would be adding a priotity:
add_action('wp_head', 'add_ob_start', 1);
The third param is $priority.
Also, if you're hooking in more than one function, it gives you complete control of the execution chain.

Resources