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.
Related
ers
I'm attempting to learn how to create a registration and authentication for a website using the slim framework. My objective is to make a handler for POST and when properly authenticated, the website will save and the username and the name. So that the next time the user goes to the page, the website will greet them by stating their name. I will be doing this through two separate PHP files, however I believe the issue is in this PHP file.
Here is what I currently have:
$app->post('/users', function (Request $request, Response $response, array $args) {
$user = array('username'=> $_POST['username'], 'password' => $_POST['password'], 'name' => $_POST['name']);
$res = saveUser($user);
if($result === true) { return $response->withRedirect('login.html', 302); }
return $response->withRedirect('registration.html#',$result,302); });
$app->post('/auth', function (Request $request, Response $response, array $args) {
if(isset($_POST['username']) {
return $response->withRedirect('welcome.php', 302);
}
if(authUser($_POST['username'], $_POST['password']) === true) {
$_SESSION["username"] = $_POST['username'];
$_SESSION["name"] = $_POST['name'];
return $response->withRedirect('welcome.php', 302);
}
else { //authentication doesn't work, destroy session and go to login page
session_destroy();
return $response->withRedirect('login.html',302);
}
To my understanding, the username, password, and the user's actual name should be saved in _POST. However, when I use:
var_dump($_POST);
The password and the username are the only ones that show up when they are being called. Which leads me to believe that this is why my "welcome.php" does not greet the user.
Here is the contents of my welcome.php:
<?php session_start(); ?>
!DOCTYPE html
<title> Welcome! </title>
<h1> Welcome Page </h1>
<section>
<p>
<?php
if(isset($_SESSION['name'])) { echo "Grettings " . $_SESSION['name']. "! ";}
?> Click here to login OR here for registration.
</p>
</section>
I think my error must be how I am trying to call it or within the isset function, but again, I do not know why name has not been properly saved.
It's mostly considered bad form to access the globals this way. As you're running slim, they've a request object available for you to use that you're already passing in:
$myArgs = $request->getQueryParams();
foreach($myArgs as $key => $value){
echo $key . '=>' . $value . PHP_EOL;
}
That said, the cause of your problem is this:
$response->withRedirect(..)
This returns to the browser a http 302 redirect to a new url. This is a second hit. The first hit is a POST to /auth, the second hit is a GET request to /welcome.php
Another thing that jumps out at me is your logic path on /auth. If 'username' is set in $_POST, then you're sending them to welcome.php first thing, the other code (like the call to the authUser(..) function) never get executed. As you are never setting $_SESSION['username'] to anything, it's still blank.
Last thing I'll say is just a style point; I personally try to use single quotes(') for strings whenever possible and avoid double quotes("), as double quotes tell PHP that the string may have special tokens in it that may need parsed. If you're not parsing tokens, just use single quotes. Other than that, welcome to PHP and I'm excited to see what you make!
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?
I'm sorry, I followed WikiHow steps (link is down there) and I made everything but here is the problem:
My index.php contains password input.
if(isset($_POST['login']))
{
require('session.class.php');
if(hash('sha256', $_POST['pass']) == hash('sha256', 'password123'))
{
$session = new session();
$session->start_session('_s', false);
$_SESSION['namesession'] = 'something';
header(location: /mama.php);
}
else
{
echo "<font color='#FF0000'>Wrong password!</font>";
}
}
I don't understand how to put session check on other pages. Other words:
How to put inside if password is correct, you can stay on mama.php page..
http://www.wikihow.com/Create-a-Secure-Session-Management-System-in-PHP-and-MySQL#Create_session.class.php_file_sub
When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
So if you want to check the post data put the if statement after the session_start().
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)){
I made a login script, when I want to check when the user is logged in, I use the function logged_in(), which consists of:
function logged_in()
{
if(isset($_SESSION['id']))
{
return true;
}
else
{
return false;
}
}
the session is set here:
else if ($login === true)
{
echo 'Login success.';
include 'include/aside.php';
include 'include/footer.php';
$userid = id_from_username($username);
$usernameforsession = username_from_id($userid);
$_SESSION['id'] = $userid;
$_SESSION['username'] = $usernameforsession;
header( "refresh:2;url=index.php");
exit();
}
And this is an example of me using it in 'index.php':
if(logged_in() === true)
{
echo 'Site content when user is logged in.';
} else if(logged_in() === false)
{
include 'include/widgets/register.php'; //registration form
}
And yes, the function is included in every page.
I made this function so it should work...
Why isn't it working?
Replace this code:
if(logged_in() === true)
With this code:
if(isset($_SESSION['id']))
That cuts out all the middlemen.
Although you have listed quite a bit of code, are you sure you are including session_start(); at the top of each page? You need to call this before you do anything at all with the session variables.
The second thing is that the error message is showing that the function isn't defined - are you sure you have it either in the source for the page or as an include to the code that defines it on each page?
If you have it in a file called 'functs.php', you need to include() it in every page that will make a call to that function.
If you are absolutely sure that the declaration is being included on every page, then I would suggest that you check to make sure the function is not declared as a method inside an object.