I made a website using WordPress, and on one page I've included my own script to guide users through a series of steps to calculate an outcome. The scripts are included in this order
Main page -> includes my Wizard.php -> Wizard.php include's Wizard_Step_xx.php
The Wizard reload's new steps every time from Step_01 until Step_10.php, this is done by a jQuery script.
Now my problem is that whenever a user finishis this "Wizard" he gets the option to log in and get redirected to his own page. Now when a user clicks the link to get to the "Wizard" I want to show the users personal page instead of showing him the first step of the wizard which would normally happen.
I've made this simple script that sets a $_SESSION variable when the user logs in :
//Validate Log In
if(isset($_POST['Validate'])) //submit login button
{
$inlog_naam = ( $_POST['inlognaam'] );
$wachtwoord = ( $_POST['wachtwoord'] );
$try = mysql_query("SELECT * FROM xxxx WHERE username = '$inlog_naam' AND password = '$wachtwoord'") or die (mysql_error() );
$result = mysql_num_rows($try);
if($result == 0)
{
$page = ( 8 );
$_SESSION['Invalid_Login_1'] = ( "true" );
}
else
{
$_SESSION['Invalid_Login_1'] = ( "false" );
$user_info = mysql_query("SELECT * FROM xxxxx WHERE username = '$inlog_naam' AND password = '$wachtwoord'") or die ( mysql_error() );
$user_info_result = mysql_fetch_array($user_info, MYSQLI_BOTH);
$user_lastname = ( $user_info_result['contact_Achternaam'] );
$user_id = ( $user_info_result['user_id'] );
$_SESSION['user_id_1'] = ( $user_id );
$_SESSION['user_name'] = ( $inlog_naam );
$_SESSION['user_lastname'] = ( $user_lastname );
$session_id = ( session_id() );
mysql_query("UPDATE xxxxx SET user_id = '$user_id', user_username = '$inlog_naam', user_lastname = '$user_lastname' WHERE session_id = '$session_id'") or die (mysql_error() );
$page = ( 9 );
$_SESSION['user_login'] = ( "true" );
$_SESSION['user_main_screen'] = ( "true" );
}
Now this part of the script works perferct, and the $_SESSION variables gets set.
But when I click on the link to go to the Wizard again I got this script in the Wizard.php file to show the users personal page instead of Wizard_Step_01.php which would normally happen.
if(isset($_SESSION['user_login']) && $_SESSION['user_login'] == 'true')
{
$page = 9;
}
else
{
echo $_SESSION['user_login'];
}
This script doesn't seem to see the $_SESSION variable, though when I click next on this page to go to Wizard_Step_02.php it DOES recognize it.
I've also noticed that for some reason, my site is running 2 PHPSESSID's , I thought I would prevent this by doing this :
<?php if(!isset( $_SESSION )) { session_start(); } ?>
but for some reason it still creates a second PHPSESSID.
If anyone has any idea on how to disable/delete/unset 1 of the 2 PHPSESSID's if this is where the problem lies, or any idea why this is happening....
To be clear: I want to know why my page doesn't find the setted $_SESSION['user_login'] when I load the page. Also any suggestions or any form of help is appreciated.
Thanks for reading.
Related
After doing my SQL Schema (Different types of users redirected to same page (index.php) with different content), I'm starting to make my login system.
I now have this:
function login($email,$password){
$mysqli = $this ->dbConnect();
if($mysqli){
$strQuery = "SELECT USERS.ID, USERS.EMAIL, TYPES.NAME FROM `USERS` LEFT JOIN `TYPES` ON USERS.TYPEID = TYPES.ID WHERE `EMAIL` = '$email' AND `PASSWORD` = '$password'";
$recordSet = $mysqli->query($strQuery);
$row = $recordset->fetch_assoc();
if($recordset->num_rows>0){
$_SESSION['auth'] = $row['ID'];
$_SESSION['username'] = $row['EMAIL'];
$_SESSION['type'] = $row['NAME'];
header ("location:"index.php");
return true;
}
//....
}
}
Does this look good? Is the query right? Any suggestions for improvement?
UPDATE
I have my login working now. And it's redirecting to index.php. But in index php I don't have acess to the $_SESSIONS variables i have stored on my function login. Is there any problem with the attribuitions? Placing the header inside the function not good?
Thanks :)
I summarized the previous comments.
1. Issue: you didn't used the same variables
function login($email,$password){ and $strQuery = " ... WHERE EMAIL = '$email' AND PASSWORD = '$password'";
2. Recomendation: use the same namming convention
On your SQL request you used two way to use fields: USERS.EMAIL and EMAIL = (with ` arround).
Use the same. This will be easier for later & debugging.
i.e.: of course, you should not use table.field each time. Not mandatory for example if you have only one table OR if the fields are not shared between them. For my perosnnal usage, I always use this table.field. This will prevent any future issue :)
3. Protect your data from any injection
Example:
$post_email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : null;
Alter call
$this->login($post_email, ...)
And finally use something like this to protect your data:
$email = $mysqli->real_escape_string($email);
and you are ready for your request:
" SELECT [..] FROM users as u [...] WHERE u.email = '$email' "
4. Or use specific functions
Example (real_escape_string not needed anymore):
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->bind_param('s', $email);
$stmt->bind_param('s', $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
http://php.net/manual/fr/class.mysqli.php
5. Sessions
If you want to activate sessions on a spacific page, the first code (at the first line) should be session_start().
Calling this method will activate the sessions and load the $_SESSION variable with content.
<?php // index.php
session_start(); // first line
// ... code
var_dump($_SESSION);
?>
&
<?php // page.php
session_start(); // first line
// ... code
$_SESSION['test'] = time();
Header('Location: index.php');
?>
Visit index.php -> nothing on the debug
Visit page.php -> you will be redirected on index.php
On index.php -> you will have data
Enjoy session :p
6. Handle specific data
To begin with, you should coose a way to store the credential access (ACL) for each user. For example, store on the database some values as 100001, and each number is a yes/no access for a specific action (binary access mode) ; another system is to store the level '1,2,3,4,5' ... or 'member,customer,admin, ...'. So many ways :)
I will choose the USER.ACCESS = member|customer|admin solution
On the login page
// is user successfully logged
$_SESSION['access'] = $row['access']; // member|customer|admin
// Header('Location: index.php');
On any page of your site:
if( in_array($_SESSION['access'], ['member', 'admin']) ) {
echo 'You are a member, you can see this part';
}
if( in_array($_SESSION['access'], ['customer', 'admin']) ) {
echo 'You are a customer, you can see this part';
}
Or
if( checkAccess() ) {
echo 'Welcome user !';
if( checkAccess(['member', 'customer']) ) {
echo 'This is a section for member, customer or admin :)';
}
if( checkAccess('member') ) {
echo 'You are a member, you can see this part';
}
if( checkAccess('customer') ) {
echo 'You are a customer, you can see this part';
}
}
function checkAccess($types = null) {
if( !isset($_SESSION['access']) )
return false; // not logged
if( is_null($types) )
retun true; // if empty, provide info about loggin.
// admin has always access to all sections of the website
$hasAccess = in_array($_SESSION['access'], ((array) $types) + ['admin']);
return $hasAccess; // user is logged + has accessor not ?
}
Of course, you can also use includes
if( checkAccess('member') ) {
include 'secret_page_for_member.php';
}
Or, at the begening of the included page:
<?php
if( !checkAccess('admin') ) {
return '403 - Not authorized';
// die('403');
// throw new Exception('403');
}
// your code
?>
I set up a custom registration page to my http server (apache) which hosts a number of services, including a wiki.
The intended goal is to have the user sign-up at once to all these services including the wiki of course.
For the wiki I'm trying to rearrange the "CreateAndPromote" maintenance script and fit it into my page. By now I came up with this snippet
$path = "/wiki";
putenv("MW_INSTALL_PATH={$path}");
require_once ("/wiki/includes/WebStart.php");
chdir("wiki");
$mediaWiki = new MediaWiki();
$name = $_POST['username'];
$pass = $_POST['password'];
$user = User::newFromName( $name );
if ( !is_object( $user ) ) {
die("Invalid user!\n");
}
$exists = ( 0 !== $user->idForName() );
if ( !$exists ) {
$user->addToDatabase();
}
try {
$user->setPassword( $pass );
} catch ( PasswordError $pwe ) {
die("password error:" . $pwe->getText()."");
}
$user->addGroup("editor");
$user->saveSettings();
$ssu = new SiteStatsUpdate( 0, 0, 0, 0, 1 );
$ssu->doUpdate();
But i get
Error: LightnCandy class not defined
MediaWiki 1.25.2
PHP 5.6.12 (apache2handler)
The problem was simple as that:
declaring the MW_INSTALL_PATH like that apparently did not work
$path = "/wiki";
putenv("MW_INSTALL_PATH={$path}");
require_once ("/wiki/includes/WebStart.php");
so I had to change dir to the wiki BEFORE requiring the webstart.php
chdir("wiki");
require_once ("/includes/WebStart.php");
In wordpress, after a user registers, I am using the function below to create two pages of two different custom post types, and I then need to store a custom meta value in their user data to assist with redirects later. I've found that if I specify custom meta values during registration (on registration form), I can retrieve these values later with :
global $current_user;
get_currentuserinfo();
$theirRedirectKey = $current_user->rpr_redirect_key;
However, in the following functions.php snippet, I can't the meta value to save for retrieval later.
function after_registration($user_id){
// Get the Newly Created User ID
$the_user = get_userdata($user_id);
// Get the Newly Created User Name
$new_user_name = $the_user->user_login;
// Create a unique Tour Code Prefix from User ID
$tourPrefix = $the_user->ID;
// Check for Tour Code Key if entered into registration form
$enteredKey = $the_user->rpr_redirect_key;
if($enteredKey == ''){
//Create the first Tour Builder Page
$tourBuilder = array();
$tourBuilder['post_title'] = $new_user_name . '| Custom Educational Tour';
// Next line may not be important after hubpages are set up.
$tourBuilder['post_name'] = 'builder-' . $tourPrefix;
$tourBuilder['post_type'] = 'builder';
$tourBuilder['post_content'] = 'This is the content!';
$tourBuilder['post_author'] = $user_id;
$tourBuilder['post_status'] = 'publish';
$tour_id = wp_insert_post( $tourBuilder );
// Build hubpage
$hubpage = array();
$hubpage['post_title'] = $new_user_name . '\'s Hubpage';
// URL must be unique
$hubpage['post_name'] = $new_user_name;
$hubpage['post_type'] = 'hubpages';
$hubpage['post_author'] = $user_id;
$hubpage['post_status'] = 'publish';
$hub_id = wp_insert_post( $hubpage );
//Update User with proper redirect keys for some reason this line doesn't work.
add_user_meta($the_user, 'rpr_redirect_key', '/hubpage/' . $new_user_name, true);
}
}
add_action('user_register', 'after_registration');
Help would be much appreciated.
In the line
add_user_meta( $the_user, 'rpr_redirect_key', '/hubpage/' . $new_user_name, true);
$the_user isn't the ID. Try $the_user->ID or $user_id instead
what i want to achieve is, user login in my wordpress website and also login on vanilla forum, i have installed jsconnect plugin in vanilla forum, and using the php's jsconnect library from following location jsConnectPHP
Here is my code:
require_once('functions.jsconnect.php');
$clientID = "1501569466";
$secret = "xxxxxxxxxxxxxxxxxxxxxx";
$userD = array();
if( isset($_POST['log']) ){
$data = array();
$data['user_login'] = $_POST['u_user'];
$data['user_password'] = $_POST['u_pass'];
$data['remember'] = TRUE;
$user = wp_signon($data, FALSE);
if(!is_wp_error($user)){
$userD['uniqueid'] = $user->ID;
$userD['name'] = $user->user_login;
$userD['email'] = $user->user_email;
$userD['photourl'] = '';
$secure = true;
WriteJsConnect($user, $_GET, $clientID, $secret, $secure);
$redirect = "http://localhost/vanilla/entry/jsconnect?client_id={$clientID}";
echo "<script>document.location.href='".$redirect."';</script>";
}
}
when the user login on wordpress i redirect it to jsconnect url in vanilla where i just found only a progress image, and can't figure out where is the problem..
jsconnect authentication url expects jsonp array like the following:
test({"email":"test#test.com",
"name":"testuser",
"photourl":"",
"uniqueid":1234,
"client_id":"12345678",
"signature":"XXXX"})
You authorization url you specify inside jsconnect should see this output to process further. In fact I am stuck at that point. I could see vanilla forum when loaded gets this input but no login happens.
I'm trying to submit user information to a URL using GET, and then get the errors (if there any) and use them to tell the customer what went wrong. So, currently I have a form that submits this customer info into an iframe (so the page is not redirected and I can see the response from my shopping cart software). when the info is submitted, this is the response I get from the shopping cart server:
errorFound=1&responseCode=329&...etc.
I need to get this response code, and was wondering what the most simple way would be to do it. Once I get it I can tell the customer what the problem is... Should I use java to read the
data in the iframe once it loads? or can I use something like Fopen to open the URL and get the return data (can't enable fopen on my server though, but something like it?).
Java != javascript
A quick way to do it:
$errorcodes = array("329" => "Wrong blabla");
if( isset( $_GET['errorFound'] ) && isset( $_GET['responseCode'] ) ){
$errorNr = (int) $_GET['responseCode'];
$error = getErrorFromDB();
//OR
//$error = isset( $erorCodes[ $errorNr ] )? $errorcodes[ $errorNr] : false;
if( $error !== false){
exit( "<script type='text/javascript'>
alert( '".htmlspecialchars($error)."' )
</script>");
}
}
function getError( $code )
{
$code = (int) $code;
$db = getYourPdoInstance();
$q = $db->prepare("SELECT `message` FROM `errorCodes` WHERE `errorCode` = ?");
$q->execute( array( $code) );
$return = $q->fetch(2);
return isset($return['message'])?$return['message']:false;
}