after connecting wordpress with another server, I get a special ID from that other server, but it is related to the ID from the wordpress user, how can I save this second ID to the base, and submit it to the user who after the login ?
$user_id = $arr['id'];
if($user_id){
$_SESSION['user_id'] = $user_id;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "localm");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//
// Attempt insert query execution
$sql = 'INSERT INTO wp_users (user_id) VALUES ("'.$user_id=$_SESSION['user_id'].'");';
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
I am currently using $ _SESSION and this id is saved while in that browser, but when the time it is signed it is gone. That is why I have to keep it in the base .. Which resets would be the easiest for this case? Thanks everyone
This will work with you if I understood the question ..
You will save the another ID to the add_user_meta, Then call it using the current Wordpress user ID and get_user_meta
function save_ID( $user )
{
//get current user details
if( !$user ) { $user = wp_get_current_user(); }
//check if session registered
if( !isset($_SESSION['user_id']) ){ return; }
//store the 2nd ID to user_meta
$user_id = $user->ID;
$another_id = esc_html( esc_js( $_SESSION['user_id'] ) );
add_user_meta( $user_id, 'user_2nd_id', $another_id);
}
add_action( 'wp_login', 'save_ID');
I hope I helped you.
Thanks.
Related
I am trying to develop a registration form.
When I fill all the filed and submit the form, no error showing
the server is connected but no data on mysql database table. Bellow L attached the action file of form. What do I miss? and how can I solve it?
<?php
$mysqli_servername = "localhost";
$mysqli_username = "admin_try";
$mysqli_password = "rFT5hePS5u";
$mysqli_database = "indepe";
// Create connection
$conn = mysqli_connect($mysqli_servername,$mysqli_username,$mysqli_password,$mysqli_database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'>Back to main page</a>";
if (isset($_GET["submitreg"]))
{
$id= mysqli_real_escape_string($conn, $_POST['id']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$re_password = mysqli_real_escape_string($conn,$_POST['re_password']);
$compnay = mysqli_real_escape_string($conn,$_POST['compnay']);
$contact = mysqli_real_escape_string($conn,$_POST['contact']);
$tell = mysqli_real_escape_string($conn,$_POST['tell']);
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell);
VALUES('id','$country','$email','$password','$re_password','$compnay','$contact'),'$tell'";
if ($conn->query($sql) === TRUE) {
echo "record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
if (mysqli_query($conn, $sql)) {
echo " record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
//$conn->close();
mysqli_close($conn);
?>
There are few errors in your insert query
Remove the semicolen after tell in your insert query
You gave id in values instead of $id
$tell is outside the bracket
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell) VALUES('$id','$country','$email','$password','$re_password','$compnay','$contact','$tell'");
Im not sure whether that is your problem or it occured your copying your code..because no error was shown
I think you mistake in insert query remove semicolon before VALUES keyword and if id column auto increment then no need to add it in insert query otherwise you need add it properly and ,'$tell' is outside the bracket please make it proper
$sql = "INSERT INTO registration(country,email,password,re_password,compnay,contact,tell) VALUES ('$country','$email','$password','$re_password','$compnay','$contact','$tell')";
I thing you need to add privileges to particular user to insert records. as you have declared $mysqli_username = "admin_try";. now go to localhost/phpmyadmin and then add privileges to particular user!!
You are using $_GET check and for submitting the form which is wrong. It's always recommened to do POST request for form submission.
if (isset($_GET["submitreg"]))
But, later in your code to get the the data you are using $_POST.
$id= mysqli_real_escape_string($conn, $_POST['id']);
Please check your form method in html make it POST and change
if (isset($_GET["submitreg"]))
to
if (isset($_POST["submitreg"]))
I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify
i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .
I have a page which only admins can access once they click a link. If the logged in user is a standard user then they should not be able to access the page. However, when a standard user tries to access the admin page they have access to the page.
I would appreciate a pair of second eyes to see if they can spot anything wrong with the code which would make the functionality work as intended.
Thanks
<?php
if(check_login() && isAdmin()) {
echo 'welcome administrator';
} else {
header('Location: login.php');
exit;
}
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID ='" . $_SESSION['sess_uid'] . "'";
$mainaccess = $conn->query($sql);
print_r($mainaccess);
if(!$mainaccess){
echo $conn->error;
}
if ($mainaccess -> userLevel == 0) {
return true;
} else {
return false;
}
}
function check_login () {
if(isset($_SESSION['sess_uid']) && $_SESSION['sess_uid'] != '') {
return true;
} else {
false;
return;
}
}
?>
The issue is that you are selecting from the database users where they have admin access already ie
SELECT `userID` FROM `usertable` WHERE `userLevel` = 0
So you are always showing anyone as an admin. The query needs to be changed to check specifically if the logged in user is an admin. So changing the query to something like so
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
Where $_SESSION['sess_uid'] is the userID
We have to remove both the userLevel check, as this is irrelevant when selecting the user, we also have to change from SELECT userID, to SELECT *, as if you only select the userID, you will not have the userLevel in your array and the line
$mainaccess -> 'userLevel' == 0
Will not work. By selecting everything you ensure all attributes can be accessed, ie
$mainaccess -> 'userLevel'
$mainaccess -> 'userID'
Update
The correct way to access the table data will be using either
Object (this is the method you will use)
$mainaccess -> 'userLevel'// Incorrect
$mainaccess->userLevel //correct
Array
$mainaccess -> 'userLevel'// Incorrect
$mainaccess['userLevel'] //correct
Please change this line
You query is also incorrect please use this block of code as your sql query is not pulling in the right info.
function isAdmin()
{
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
if($result = $mainaccess = $conn->query($sql))
{
while($obj = $result->fetch_object())
{
$user = $obj;
}
}
if ($user->userLevel == 0)
{
return true;
}
else
{
return false;
}
}
You really need something like:
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT `userID` FROM `usertable` WHERE `userLevel` = 0 AND userID ='" . $_SESSION['sess_uid'] . "'";
As I said in the comments, you are looking for ANYONE with admin access, but you really want to know whether THIS user has admin access, therefore you have to validate what user you are trying to figure out has access. I just put the code together above, thinking you are storing the userID in the session (as per your later code) but you may need to change this
Your approach is wrong. The link should only be shown to logged in admins.
Try something like this test code.
<?php
session_start();
$_SESSION['admin'] = 0;//set only by logging in
$html ="Test<br>";//page html
if ($_SESSION['admin']== 0) {
$html .="<a href=\"adminpage.php\" >Admin</a>";
}
echo $html;
?>
Modify to suit your requirements.
I'm terrible with PHP/SQL, so any help would be appreciated.
Basically I have a form that posts the values 'firstname' & 'surname' to another page. What I want that page to do, is check to see if the user's name is already on the table 'Members'. If it is I want it to continue loading this page, but if they aren't on the database, I want the viewer to be re-directed to an existing sign up page.
Here is the code I've been working on, I'm not sure if I'm heading in the right direction or not.
<?php
$con = mysql_connect("localhost","site","xxxxxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("site", $con);
$query = "SELECT * FROM Members WHERE firstname='$_POST[firstname]' and surname='$_POST[surname]'";
$result = mysql_query($query);
if ($result==$something)
{
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
?>
This will do the trick:
<?php
$con = mysql_connect( "localhost", "site", "xxxxxxxx" );
if ( !$con ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("site", $con);
1st, remove the sql injection part at least like this:
$firstname = strip_tags( $_POST[ 'firstname' ] );
$surname = strip_tags( $_POST[ 'surname' ] );
2nd, I didn't change it, but you need to remove the * and enter only specific values you want to load. Even if those are all the values, still write them manually.
$query = "SELECT * FROM Members WHERE firstname='" . $firstname . "' and surname=' " . $surname. "'";
$result = mysql_query( $query );
3rd, you can check for row count, if you got some value, there is an entry with those variables
if ( mysql_num_rows($result) >= 1 ) {
// the page you want
} else {
// redirect user to another page
header( "Location: signup.php" ); die;
}
?>
Edit:
Think adding some unique requests to your query. What will happen if two users have identical names and surnames or if a new one wants to join, but the name and lastname is already in the db ...
if (mysql_num_rows($result) == 1)
{
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
Also, you're query is prone to SQL injection big time
$rows = mysql_num_rows($results);
if ($rows == 1)
{
echo "login successful"; //user continues loading page
}
else
{
header ('location: signup.php'); //user is redirected to sign up page
}
You can simply put a header( "Location: host/site.php" ) function call in your else branch followed by a die()
if(mysql_num_rows($result) > 0){
echo "great success"; //user continues loading page
}
else
{
echo "fail"; //user is redirected to sign up page
}
use this