how i require session for a function - php

i have in my sandbox many of function, some of the function are public, and other's i want them to be only for website member's.
this is an example for a function i want it to be for website members only
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT * FROM pages WHERE name = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<div class=entry>';
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
echo '</div>';
}
is there any way to do that?

"how i require session for a function"
Use the following, as an example:
if(!isset($_SESSION['session_name'])){ die(); }
and to include session_start(); inside all of the files used, and at the * top.
(* Depending on the condition).
For more information on sessions, visit the following:
http://www.php.net/manual/en/features.sessions.php
Footnotes:
Should you be faced with an headers already sent... error message later on, you can make use of ob_start(); placed above session_start().
For example:
<?php
ob_start();
session_start();
// code

Your question is really not clear.
You can use something like:
// Private function for members
function privateFunction($isMember=false){
if($isMember){
// DO your things
}
else{
callError();
}
}
Or make use of PHP Session variables directly into your function ?

Related

how to save variables after using header function php

After i submit a form and save the info to a database i use the header function to redirect to a more user friendly url but the variable $checkError is not saving, it gets reset after the header redirect. How can i save the variable even if the page gets refreshed?
if(isset($_GET['submit'])){
// get the post records <<
$id = '2';
$title = $_GET['title'];
$link = $_GET['link'];
// database connection
$con = mysqli_connect("localhost", "user", "password", "db_test");
$sql = "INSERT INTO test (id, title, link)
VALUES ($id, '$title', '$link')";
$rs = mysqli_query($con, $sql);
if($rs){
$checkError = '<div class="success">Success!</div>';
}else{
$checkError = '<div class="error">Not working!</div>';
}
mysqli_close($con);
//redirect to user friendly url
header("Location: /index.php?id={$id}");
}
You can write this to session data and recall it later, as one potential solution.
Modify/add in your example code block:
session_start();
if($rs){
$_SESSION['checkData'] = '<div class="success">Success!</div>';
}else{
$_SESSION['checkData'] = '<div class="error">Not working!</div>';
}
header("Location: /index.php?id={$id}");
And back on index.php, you would need to add/modify:
session_start();
if( isset( $_SESSION['checkData'] ) ){ // check whether it's set
echo $_SESSION['checkData']; // output variable
unset( $_SESSION['checkData']; // reset variable
}
You can use $GLOBALS OR $_SESSION as an array for $GLOBALS more details click here
you can use it as the below code in your header file
set value in $GLOBALS
$GLOBALS['checkError'] = '<div class="success">Success!</div>';
get value from $GLOBALS
echo $GLOBALS['checkError'];
Another way, very easy to implement is to skip $checkError variable and redirect user to a specific page:
// ...
$rs = mysqli_query($con, $sql);
mysqli_close($con);
$page = $rs ? 'success' : 'failure';
header("Location: /{$page}.php?id={$id}");
You have to store your data in cookies or sessions before the redirect.
A session is also used to store data, but I suggest you store data in cookies because the session stores data on the server-side, creating performance issues, whereas cookie stores data on the client-side.
You can check the critical difference of Cookie and Session
first.php
<?php
if($rs){
setcookie('checkError', '<div class="success">Success!</div>');
}else{
setcookie('checkError', '<div class="error">Not working!</div>');
}
?>
second.php
<?php
if(!isset($_COOKIE['checkError'])) {
echo $_COOKIE['checkError'];
}
?>
I hope this is helpful to you.

PHP-Unable get values from $_SESSION, error msg is Notice: Undefined variable: _SESSION

First let me explain my code.
It comprises of three php files.
inc_fn_header_and_menu.php, contains the HTML and CSS header details
and it initializes the session via session_start();
This is later included in project_status.php] .
In project_status.php] , I have included another file
project_status_app.php which contains a HTML form.
project_status.php:
<?php
include 'inc_fn_header_and_menu.php';
function includeFile($file,$variable) {
$var = $variable;
include($file);
}
if (isset($_GET['id']) && $_GET['id']!="") {
$pid = $_GET['id'];
$_SESSION['pidForApproval'] = $_GET['id'];
$query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\'';
$result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n".
mysqli_error());
foreach ($result as $row) {
$status = $row['status'];
?>
project_status_app.php
In project_status_app.php I am attempting to retrieve pidForApproval from the $_SESSION array.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include '../../inc/fastlogin.php';
$sql = "UPDATE pp SET customer_purchase_remarks ='{$_POST['remarkstxt']}' WHERE pp.pid='{$_SESSION['pidForApproval']}'";
$result = mysqli_query ( $fastdb, $sql ) ;
if (mysqli_affected_rows($fastdb) != 1) {
$_SESSION['err_cpa_rmks'] = "<p>Error while updating WHERE id='{$_SESSION['pidForApproval']}'</p>";
} else {
$_SESSION['suc_cpa_rmks'] = "<p>Records was updated successfully.</p>";
}
header ("location: project_status.php?id="$_SESSION['pidForApproval']);
exit();
}
?>
When I load project_status.php, project_status_app.php is supposed to display the form. Once the user fills in the form the and the submit button has been pressed, the UPDATE statement is supposed to run and then it is supposed to navigate back to project_status.php?id=FA142. But the update is failing and the when the project_status.php is loaded back, the url looks like this http://localhost/fast/project_status.php?id= . The id is empty. It is supposed to be something like this http://localhost/fast/project_status.php?id=FA142. With the id being populated at the
header ("location: project_status.php?id=".$_SESSION['pidForApproval']);
I suspected that my $_SESSION['pidForApproval'] is not being populated in project_status.php but I echoed back $_SESSION['pidForApproval'] in that file itself and I can see it is being populated. Hence, I suspect that the $_SESSION['pidForApproval'] is not being passed to project_status_app.php. I have already attempted to include session_start(); clause in project_status_app.php but that gives an error, stating that the session has already started, in inc_fn_header_and_menu.php. Can someone help me as to why the $_SESSION['pidForApproval'] is not being passed on to the project_status_app.php file. Thank you.

Redirect if sql column has a specific value

Am new to php, so any help would be greatly appreciated. I have a page to create account for users, and while creating account, there is a select field which has three specific value to select from "notfcode" "tfail" **"tfcode".
There is another page check.php which allows the user check his ttype. What i want to do is make the page try to read the sql table row which is ttype and if the value present on the user's account is "notfcode" it redirects to notfcode.php page, if its "tfail" it redirects to tfail.php and if its "tfcode" it stays on the page. below is the code i have been battling with without success.
<?php session_start();
include_once ('session.php');
require_once 'class.user.php';
if(!isset($_SESSION['acc_no'])){
header("Location: login.php");
exit();
}
$reg_user = new USER();
$stmt = $reg_user->runQuery("SELECT * FROM account WHERE acc_no=:acc_no");
$stmt->execute(array(":acc_no"=>$_SESSION['acc_no']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$email = $row['email'];
$temp = $reg_user->runQuery("SELECT * FROM transfer WHERE email = '$email' ORDER BY id DESC LIMIT 1");
$temp->execute(array(":acc_no"=>$_SESSION['acc_no']));
$rows = $temp->fetch(PDO::FETCH_ASSOC);
$transfertype = $row['ttype'];
if(isset($_SESSION['acc_no'])){
$transfertype = $row['ttype'];
if($transfertype == nocodetf){
header("Location: nocodetf.php");
}
elseif($transfertype == tfail){
header("Location: nocodetf.php");
}
else {
header("Location: check.php");
}
}
include_once ('counter.php');
?>
When the page loads up, it does nothing, no redirects which is what i intend. A pointer in the right direction will be appreciated.
This are strings.
if($transfertype == "nocodetf"){
or
if($transfertype == 'nocodetf'){
Activate PHP error reporting than PHP shows you this.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$transfertype = "foo";
if ($transfertype == nocodetf) { # <-- as you did it
//...
}
// <b>Warning</b>: Use of undefined constant nocodetf - assumed 'nocodetf' (this will throw an Error in a future version of PHP) in ...
I was finally able to resolve it using this code
<?php
$transfertype = $row['ttype'];
if($transfertype == 'nocodetf'){
header('Location: nocodetf.php'); }
else if($transfertype == 'failtf'){
header('Location: failtf.php');
exit();
}
?>
The problem seemed to be in the fact that i wasn't quoting the value which php should try to get from the sql column.

Use SESSIONS variables between different php files

I am new to $_SESSIONS but needs it to re-use variables between different php files. In the below code I want to use the variable $word in another php file, but I am unsure how to do this.
My php file looks like this:
<?php
if (isset($_POST["search"])) {
//include database connection
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
echo $word, " text bla";
}else {
echo $word, " text bla bla";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
}
}?>
Looking forward to your suggestions.
---UPDATE Sessions still not working on page2.php?---
I do not understand why $_SESSION do not work. One page1.php I can echo($_SESSION['word']) and get the correct value, but one page2.php I get ('$'."_SESSION['word'] isn't set because you had never been at file one");
I tested all the below solutions but none of them worked = same result on page2.php.
My page1.php file.
<?php
session_start();
//if we got something through $_POST
if (isset($_POST["search"])) {
// include database connection
$connect = mysql_connect('localhost', 'root', 'NomiS123') or die(mysql_error());
mysql_select_db('workcard');
// sanitize user input
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
// build search query to the database
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
// get results
$_SESSION['word'] = $word;
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
$_SESSION['word'] = $word;
echo($_SESSION['word']. "<br>");
var_dump($_SESSION);
echo "<br>";
echo "link link <br>";
echo "new card <br>";
echo "New Search";
} else {
echo $word, " bla bla text <br> Create card <br>";
echo "Edit info on: ", $word, "<br>";
echo "New Search <br>";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
//$results->free();
}
}
// mysql_close($connect);
?>
My PAGE2.php file.
<?php
session_start();
if(isset($_SESSION['word'])) {
$word = $_SESSION['word'];
echo($word);
} else {
die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
?>
I am going insane over this.
UPDATE - SOLVED
I tested all the below suggestions but none of them worked which was weird because I could set and echo out the sesson_id() on page1.php and page2.php, but on page2.php I got a different sesson_id(). I began to look into my MAMP sessions settings, but everything was correct set. The solution was "simply" to place the session_start(); on the very top on page2.php. And by the very top I mean before everything even the <!DOCTYPE html> etc. Solved + lesson learned :-)
First you must start the seesion via session_start(); directly after the opening PHP 'tag' (<?php session_start();... ?>)
Then you must save your variable to the session.
You can use $_SESSION['word'] = $word; for this purpose.
And in the other file you must also use session_start(); at the very first after the <?php 'tag'.
Then you could access the old variable via $word = $_SESSION['word'];.
You now can also use $word in the second file. But you only can use it if it's set (and you where at the first file before).
File one:
<?php
session_start();
if (isset($_POST["search"])) {
//include database connection
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
$_SESSION['word'] = $word;
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
echo $word, " text bla";
}else {
echo $word, " text bla bla";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
}
}?>
File two:
<?php
session_start();
if(isset($_SESSION['word'])) {
$word = $_SESSION['word'];
} else {
die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
echo $word;
?>
Hope this helps ;)
To use PHP sessions you would do the below:
Initiate the session, session_start();
Note: session_start(); must be the first line of PHP in your file.
Create the session, $_SESSION['word'] = $word;
To access it on another page:
Initiate the session, session_start();
Access the session, $word = $_SESSION['word'];
session_start() means that you are using session variables, make sure it's at the top of the page. To make a session you do: $_SESSION['word'] = [some value]. This can be used between pages as long as you have session_start() at the top. Make sure to make sure it's set first, if it's not set initialize.
<?php session_start(); ?>
...
<?php
if ( isset($_SESSION['word']) ) {
$_SESSION['word'] = /* change existing session value */;
} else {
$_SESSION['word'] = /* new session value */;
}
?>
You first of all should start the session using the function 'session_start()'.
Place this in your index.php/bootstrap.php (a file that is always loaded when loading your website).
After that, you can use the '$_SESSION' global to set data.
//In your index.php/boostrap.php
session_start();
In the file you want to save the $word:
$_SESSION['myword'] = $word;
And from that point you can use this variable on another page.
//On another page, after the variable is being set
echo $_SESSION['myword'];
Be aware that when you are using shared webhosting, your session data is often stored in a global folder on the webserver and can be used by every website on that server. To prevent this, you should change you session save path using the 'session_save_path()' function or by creating you own session handler.
Call session_start(); at the beginning of the PHP file, and if anything is set in the $_SESSION super global array, you can re-access it.
If it isn't set you can set it with:
$_SESSION['a name']= 'some thing';
So for your example:
PHP FILE1
<?php
session_start();
$_SESSION['word'] = $_POST['word']
?>
PHP FILE2
<?php
session_start();
echo $_SESSION['word'];
?>
There are many many ways to accomplish this it all depends on how you want to use it. You can include your file in that file, you can use require or require_once, or yes you can use the session super global.
The $_SESSION super global will be accessible to all files within your application. The only thing you need to make sure you do is use session_start() on the page as the first thing on that page. If you use session_start() after any output has gone to teh browser it will not work. Usually you will want to run session_start() as the first line on your index.php file. Then you can use ...
<?php
if (isset($_POST["search"])) {
//include database connection
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
$_SESSION['word'] = $word;
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
echo $word, " text bla";
}else {
echo $word, " text bla bla";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
}
}?>
then in any page you want access to it just cal it up...
<?php
echo $_SESSION['word'];
Hope that helps

Create a function that sets $_SESSION variables

I created a site where you need to login to visit the different pages, nothing special.
To keep the user logged in, I'm setting the session on top of every page.
My problem is, I don't wanna have to set the different session variables on top on each page. I'd rather have one function I can call to set them. Plus I don't need all those variables on each page, so I'd like the function to accept optional parameters (like the email, or profile picture that are not used on every page).
I call this on top of each page:
<?php
require_once 'session.php';
confirm_logged_in();
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$picture = $_SESSION['picture'];
$group = $_SESSION['group'];
?>
I would like to make it more like this and be able to set only the variables I need:
<?php
require_once 'session.php';
confirm_logged_in();
set_variables($username, $email);
?>
The 'session.php' file is like this:
<?php
session_start();
function logged_in(){
return isset($_SESSION['username']);
}
function confirm_logged_in(){
if(!logged_in()){
header('location: start.php');
}
}
?>
I've tried a few things, but it just led me to huge amounts of errors.
Has someone already done this or found a script doing this? Is that possible?
First of all, if what you want to do is overload your function, you can't do that. For more info on that see this. However, you can do this:
<?php
set_variables($username, $email, $picture,$group)
{
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['picture'] = $picture;
$_SESSION['group'] = $group;
}
?>
Put this function in your session.php file.
I am not sure if I understood right, but if I did, all you need to do is create a new file, let's call it "Session_Variables.php".
After you created the file, paste the following code into it:
<?php
require_once 'session.php';
confirm_logged_in();
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$picture = $_SESSION['picture'];
$group = $_SESSION['group'];
?>
Then, finally, just replace the old code with:
include("Session_Variables.php");
Not directly related to the question you are asking, but you should really add exit; after a redirect header. Clients can ignore headers and still load your page even while not being logged in.
if you want to make set_variables($username, $email) work like i think you wanted, you need to write something like this.
Session.php
<?php
session_start();
function logged_in(){
return isset($_SESSION['username']);
}
function confirm_logged_in(){
if(!logged_in()){
header('location: start.php');
}
}
//Only Picture and group are Optionals
function set_variables($username, $email, $picture = '', $group = ''){
//you can check here is thoses variables are set or valid before assign them
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['picture'] = $picture;
$_SESSION['group'] = $group;
}
//create a function that we need to retrieve thoses values
function get_variable($name){
if ( isset( $_SESSION[$name] ) ) return $_SESSION[$name];
return FALSE; //if the variable is not set.
}
?>
And you can use it like this
<?php
require_once 'session.php';
confirm_logged_in();
set_variables($username, $email);
$username = get_variable('username');
?>
I think you need to move the session_start(); to the actual page. Using a require_once on the session_start(); is not a good plan.

Categories