PHP Function not available on another page - php

I am trying to get a function to output on a page on my site.
All my functions are in functions.php, which I include in the head on all pages.
Here is an example function:
function get_username(){
$userID = $_SESSION['user'];
if($userID){
$username = mysqli_query($dbconfig,"SELECT * FROM users WHERE userId='$userID'");
while($row = mysqli_fetch_assoc($username)) {
return $row['userName'];
}
}
}
When calling the function get_username nothing is returned. To verify, I print the session to check the data exists, which it does.
I have also tried just echoing a simple word in the function like this:
function get_username(){
echo 'test';
}
Again nothing is outputted. As mentioned above the functions.php is included in the head of the page.
Any ideas?

Related

security for a page function in php

so here I have a page that holds all the functions.
I give name "init-admin" and I call all these functions on all admin pages
this is the content of init-admin.php
<?php
session_start();
require_once "admin-functions/db.php";
require_once "admin-functions/admin.php";
require_once "admin-functions/navigation1-content.php";
require_once "admin-functions/navigation1-press.php";
require_once "admin-functions/navigation1-restrospective.php";
require_once "admin-functions/navigation1-inquiries.php";
require_once "admin-functions/navigation2-earrings.php";
require_once "admin-functions/navigation2-necklaces.php";
require_once "admin-functions/navigation2-bracelets.php";
require_once "admin-functions/navigation2-sets.php";
require_once "admin-functions/navigation2-men-jewelrys.php";
require_once "admin-functions/navigation2-object_arts.php";
require_once "admin-functions/navigation2-rings.php";
require_once "admin-functions/navigation2-pin_pendant.php";
?>
and this is one of the functions I call as an example. Its function name is "admin.php" this is his content
//1. REGISTER
function Register($username, $email, $password){
global $connect;
$username = mysqli_real_escape_string($connect, $username);
$email = mysqli_real_escape_string($connect, $email);
$password = mysqli_real_escape_string($connect, $password);
$password = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO admin (admin_username, email, password, actor) VALUES ('$username', '$email', '$password', '1')";
if( mysqli_query($connect, $query) ){
return true;
}else{
return false;
}
}
function prevent_twin_names($username){
global $connect;
$username = mysqli_real_escape_string($connect, $username);
$query = "SELECT * FROM admin WHERE admin_username ='$username'";
if( $result = mysqli_query($connect, $query) ){
if(mysqli_num_rows($result) == 0) return true;
else return false;
}
}
my problem here if i give session like
require_once "core-admin/init-admin.php";
if( !isset($_SESSION['admin_username']) ){
$_SESSION['msg'] = 'page can not open';
header('Location:admin_login.php'); exit();
}
on the function page I get an error "to many redirect".
so I want to ask here if the function page if not given session will be dangerous?
but if I try to call the page function in the browser page that appears only blank pages.
can anyone explain? ty
Okay, so you seem to have various problems here, I will try to answer one question at a time.
header()
With PHP we have the header function; we can use for various purposes, to change the location of the page:
header('Location: index.php');
Or to set the type of content your page is displaying:
header('Content-Type: text/plain');
This is useful when dealing with certain parts of your code. header location is probably the most used function, but you have to be careful when using it. It's usually bound to run you into problems.
The error you are getting comes from redirecting the user too many times with one attempt. That, I believe, is different for each browser.
To fix that error you have to look for where else you set a header, and make sure you only set one header per page. Also note:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Functions
So first let's deal with your function questions. The reason your function page is blank when you load it in your browser it's because it's inside of a function. That means that the block of code before your eyes will only run when initiated. Thus, a blank page.
In practice this would look like:
function foo()
{
return 'Hello Foo!';
}
To get the output out of that function I have to initiate it in my code somewhere, either in it's own file (not a good practice) or where in the code I need it. You can initiate it by
echo foo();
or assign it to a variable:
$foo = foo();
The purposes of functions is so that you do not have to write the same code over and over again. You write one block of code with general guidelines and each time you need the code to be executed, you then call the function.
Sessions
Now that we have discussed functions, please do not add a session to your function. You want functions to be as reusable as possible, add a session at the top of your page.
<?php
session_start();
// some code ...
if(isset($_POST['submit'])
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if( Register($username, $email, $password) === true )
{
echo 'Registration Complete';
}
else
{
echo 'Registration failed';
}
}
?>
<html>
<head>
</head>
<body>
<form id="registration">
</form>
</body>
</html>
Now when the register, you can call the function. That would be better practice than to start you session with your function.
Here's why, your registration function will come after some code has already been written; a session has to start at the top. Or else it would not run properly. To fix that you can create a function which create a session for you:
function start_my_session()
{
session_start();
}
This one is very simple, but you can buff up your security with different session function. For more information on session security look at PHP's Manual.

How to pass session variable

I'm trying to use a Single Sign-on function for a specific script but it's not working. I think the problem is when I try to change between the 2 sessions.
I know about session_start(); should be on the first line but I don't know how to do that in a function called.
Here the function code :
function singleSignOn(){
session_name('Main');
session_start();
$username = $_SESSION['id'];
session_id('Specific');
session_start();
return $username;
}

Compare values given by user to values in ini file

I am trying to make a login validation page for my class and this is the code I have for the page LoginDataModel.php.
<?php
//define a constant variable for fxUsers.ini
define('FX_LOGIN_INI_FILE', 'fxUsers.ini');
class LoginDataModel {
private $ini_array;
//construct class will read and store an associative array
public function __construct() {
$this->ini_array = parse_ini_file(FX_LOGIN_INI_FILE);
}
//validateUser function will compare the username and password
//given by the user to the values stured in the ini file.
public function validateUser($username, $password){
if(in_array($username,$this->ini_array) && in_array($password,$this->ini_array)){
return TRUE;
} else {
return FALSE;
}
}
}
?>
This code will be called in my login.php page once the user passes through his credentials. If the users credentials do not match, he will simply be rerouted back to the login page to try again. The code for the login page is
<?PHP
//check for key to see if this is the first time loading the page
if (empty($_POST['txtUser'])){
$user = '';
$pass = '';
} else {
$user = $_POST['txtUser'];
$pass = $_POST['txtPassword'];
}
//call method from a different file
require_once ('LoginDataModel.php');
$LoginDataModel = new LoginDataModel();
$control = $LoginDataModel->validateUser($user, $pass);
//if user and password match, continue to next file and exit current file
if($control === TRUE){
include 'fxCalc.php';
exit();
}
?>
While I believe to have everything set, The only thing I need is how to compare the values between the user and the values in the ini file. Any help would be appreciated
EDIT
I should have mentione that my ini file will just be
[section]
admin = pass
EDIT 2
My code reflect the changes I've made thanks to the support from this post as well as looking back at my text book. My problem is now that When I pass the user and pass through the file, it returns as false even though the strings match perfectly.
You are doing the wrong way of comparison in the below line..
if($ini_array == $username && $ini_Array == $password){
The parse_ini_file() returns an array , so you just can't check a variable $username inside an array (i.e. $ini_array) using a == operator. You should be using array_search or in_array() functions as such.
Something like...
if(in_array($username,$ini_array) && in_array($password,$ini_Array)){

class not retainining protected values

I've looked at existing answers for my problem.
I've echo'd the value right through the process and right up until the "header('Location" instruction the values remain intact.
I don't think it's a serialization problem as suggested for similar problems...
Here are the relevant bits of the class:
class clsSetUser {
protected $UserID = 0;
public function initUser($id) {
// get user details from database
$this->setUserID($id);
// etc...
}
private function setUserID($value) { $this->UserID = $value; }
public function getUserID() { return $this->UserID; }
}
common.php:
if(unset($clsUser)) $clsUser = new clsSetUser;
login-exec.php:
$clsUser->initUser($id);
header("Location: somewhere.php");
somewhere.php:
echo $clsUser->getUserID();
// here it equals 0
any ideas? does "header" serialize everything?
This is because PHP is actually starting from a clean slate in somewhere.php.
header("Location: somewhere.php"); sends a command the browser to connect to a different page. In this page non of variables of the previous page are available in PHP.
You need to set the userId in the $_SESSION so that you can reload the user from the database when he visits somewhere.php.
login-exec.php
$clsUser->initUser($id);
$_SESSION['user_id'] = $id;
header("Location: somewhere.php");
somewhere.php
$clsUser->initUser($_SESSION['user_id']);

Getting Fatal Error in get_results of WordPress

<?php
if (isset($_GET['confirm_code'])) {
__construct();
}
function __construct() {
global $wpdb;
$table_one = $wpdb->prefix . "fantasticemailnewsletter_temp";
$confirm = $_GET['confirm_code'];
$mylink = $wpdb->get_results("SELECT * FROM $wpdb->$table_one WHERE confirm_code = $confirm");
if ($mylink) {
echo $mylink->confirm_code;
echo "success";
echo $wpdb->show_error();
} else {
echo "You Subscription is not process right now please try again later";
}
}
?>
I’m trying to create a newsletter plugin in WordPress. I make a confirmation link for the corresponding subscriber to prevent spammers, creating a random key for every subscription e-mail. I pass the random key with query string through mail like this:
http://www.example.com/wp-content/plugins/plugininname/includes/subscriber.php?confirm_code=%2248c9c7d48165379b49f58962c0092466%22
In subscriber.php only, I’m using the above code, but for some reason, there’s an error at get_results():
Fatal error: Call to a member function get_results() on a non-object
How can I overcome this prob.
The error looks like the object of wpdb hasn't been instantiated.
Generally a method of a class shall be called after an object has been instantiated, if the method is not a static one. Otherwise this error shows.
I would check other parts of code or the file to see whether it's executed before WP code.
For example, if the file isn't a plugin or a theme (which means the file stands alone) and you haven't properly called WP framework header file before executing this file, the $wpdb object may not have been instantiated. I would definitely try the code by #Rikesh in the comment of your question.
you dont need to redeclare wpdb in query $wpdb-> as you already declared in this line $table_one = $wpdb->prefix . "fantasticemailnewsletter_temp";
<?php
if(isset($_GET['confirm_code'])) {
__construct();
}
function __construct() {
global $wpdb;
$confirm = $_GET['confirm_code'];
$mylink = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}fantasticemailnewsletter_temp WHERE confirm_code = $confirm");
if($mylink) {
echo $mylink->confirm_code;
echo "success";
echo $wpdb->show_error();
}
else {
echo "You Subscription is not process right now please try again later";
}
}
?>
$query = $wpdb->query("SELECT * FROM $wpdb->$table_one WHERE confirm_code = $confirm");
$mylink = $wpdb->get_results($query);

Categories