PHP UPDATE with if and else statement - php

I need a little help with my script, I am making a library sign in/out and page and I have it working so that it posts the form when they sign in and out, but i want to make it to where if they are trying to sign out and they actually never signed in it would pop-up a js alert tell them that and I can't quite get it.
Here's the code:
<?php
session_start();
include_once("connect.php");
date_default_timezone_set("America/Winnipeg");
$date = ("m-d-Y");
$timeout = date("g:i:s a");
//search for existing entries
if ("SELECT EXISTS(SELECT * FROM signin_out WHERE
lname='".$_POST['lastname']."' AND fname='".$_POST['firstname']."'
AND date='".$date."')") {
//if they exist run this
mysql_query("UPDATE signin_out SET timeout='" . $timeout . "'
WHERE lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "' AND timeout='' ");
header("Location: ../index.html");
//if they don't exist run this
} else {
header("Location: ../index.html");
echo "<script type='text/javascipt'>\n";
echo "alert('You did not sign in!');\n";
echo "</script>";
}
?>

The HTTP Location header already sends them to ../index.html long before the JavaScript gets echoed out. You need to have a logout.php page with that JavaScript or a $_GET variable for the page you redirect them to, and trigger the alert box there.
For instance:
...
} else {
header('Location: ../index.php?notloggedin');
}
And somewhere in your index.php:
<?php
if(isset($_GET['notloggedin'])) {
echo '<script>alert("You did not sign in!");</script>';
}
?>
Although I find that an alert box is rather intrusive, I'd rather do:
<?php
if(isset($_GET['notloggedin'])) {
echo '<p><strong>You did not sign in!</strong></p>';
}
?>

Related

PHP opens 2nd session unwanted

Requirement: use QRBOT-app to scan a barcode on a mobile and give the number scanned to the website.
Problem: I've a session open (1), from here I'm opening the app (see ScanBardcode.php), I scan and the app returns to the callback-URL including the required parameters. However I do expect it is re-using it's session, it creates a new one (2). Can someone help me? It does have both sessions active and both pages keep using it's own session. I can only test it on my cell phone, which I checked is using each time (the initiate-1 and the callback-2 the same browser)
What I tried already:
1. Pass the sessionID in the callback URL (QRBOT doesn't allow parameters)
2. Set Session.auto_start to 1
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id() . "!";
$_SESSION['BarCode'] = "VoorraadTellen";
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
//URL to open qrbot.
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php
<?php
$a = session_id();
if(empty($a))
{
session_start();
}
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Adding screenshot when I add the sessionId in the URL as a parameter:
enter image description here
Update to ScanBarcode.php
`echo "click"
as far as i know you don't need the whole check with session_id(). PHP Documentation for session_start() says:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
this is also my experience. every time i used session_start() i just put it at the top of every file (or included it like you did)
When you pass the session ID in the URL, you need to use the parameter to set the session ID before calling session_start(). Change sessie.inc.php to:
<?php
if (isset($_GET['s'])) {
session_id($_GET['s']);
}
session_start();
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Working with both #Tsai and #Barmar we found the solution.
We fixed it by:
- Encoding the URL by using urlencode-function
- Take the sessionID from URL and apply that using session_id-function before initiating the start_session (see also).
The cleaned up code below; hopefully someone would be able to use it also.
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id();
//URL to open qrbot.
$CallbackUrl = "http://ilonashairstyling.nl/2016UAT/module/Ilonas_admin/ScanBarcodeCallBack.php?s=" . htmlspecialchars(session_id());
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
ini_set("session.use_cookies",0);
ini_set("session.use_trans_sid",1);
session_id($_GET['s']);
//print_r($_SESSION); //You can test it with this code
//print(session_id()); //You can test it with this code
ini_set("session.use_cookies",1);
ini_set("session.use_trans_sid",0);
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php is unchanged

Echo success message after submitted form but before redirect and exit

Don't know how long i have worked on this, but nothing looks to be working. All i want to do is output a success message before it redirects and exits.
This is what i got to check for success/fail to the database
$sql = ("INSERT INTO test3 (test1, betvalue, bookmaker, status, aktiv) VALUES ('$bettype', '$betvalue', '$bookmaker', '$status', '$aktiv')");
$result = mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) >0 ) {
echo "Wow it works"; <-- Not working
header("Location: nybonus.php");
exit;
} else {
echo ("<div class='alert alert-danger' role='alert'>" . $sql . "</div><div class='alert alert-danger' role='alert'>" . mysqli_error($conn) . "</div>");
}
It does not output any echo if it has be successful, i have tried making it sleep with correct flushing to try to output an messsage, but it does not work at all. Is there a better way to do it? Also can someone explain why it wont echo before the header and exit?
Could you achieve what you want by setting a session variable and checking for the state of that variable on reload:
$message = '';
if(isset($_SESSION['success'])) {
if($_SESSION['success'] == 'success') {
$message = 'Success';
}
}
$sql = ("INSERT INTO test3 (test1, betvalue, bookmaker, status, aktiv) VALUES ('$bettype', '$betvalue', '$bookmaker', '$status', '$aktiv')");
mysqli_query($conn, $sql);
if(mysqli_affected_rows($conn) > 0) {
$_SESSION['success'] = 'success';
header('Location: nybonus.php');
exit;
}
else {
$_SESSION['success'] = 'fail';
.....
}
<script>
$("#message").fadeOut(2000, function() {
$("#message").fadeIn(0, function() {
document.getElementById("message").innerHTML ="<br>";
});
});
</script>
<div id="message">
<?php echo $message; ?>
</div>
The problem is when you use the "header" it has to be first.
You can't print anything else to the screen before the header.
It's the same as when you're setting cookies.
So in your case you can't do the redirect with "header".
You could use a meta refresh.
<meta http-equiv="refresh" content="0; url=http://www.somewebsite.com">
The "content" is number of seconds to wait before doing refresh.
You'll have to explain what you're trying to accomplish more precisely... like step 1 do this step 2 do this and so on.
Previously I understood you had asked how to do a redirect after echoing a message.
So now explain more detail in steps what you're wanting to do and maybe I can help.
If you mean the user is one "page1" and they submit a form and then on the resulting page you want to display the message? Then redirect...
You would just need to make the form action be the same url path as the page they are currently on.
Do you follow me?

Strategy to pass data from included PHP file

The following code presents a way that I am currently rendering my pages through index.php. The problem is that I'm not sure how to re-think this so I can pass a page title before the template has been included.
How other way I could do this? This is just my index page, please ask if more code needed.
include($cms->GetTheme() . "/head.php"); This should get the Title information before being included, but I'm not sure how to pass data there from later included page.
include('config/config.inc.php');
$cms = new cms();
if(($_SERVER['REQUEST_METHOD'] === 'GET' || $_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_GET['page'])) {
include($cms->GetTheme() . "/head.php");
$cms->IncludeModule($_GET['page']); <- actual page being included
include($cms->GetTheme() . "/foot.php");
} // end (GET || POST) && GET
else { // just index.php
include($cms->GetTheme() . "/head.php");
foreach($cms->GetModuleList() as $module) {
echo " $module <br />";
}
include($cms->GetTheme() . "/foot.php");
} // end ELSE
Example page being included. The $this->SetTitle($module_name); I would use to set the page title.
<?php
$module_name = 'Log out user';
$module_directory = 'admin';
$this->SetTitle($module_name); // setting page title
if(count(get_required_files()) < 2) {
header('Location: index.php');
}
else {
if(isset($_SESSION['user'])) {
$this->DestroyUser();
echo "You have been logged out! Please navigate to the Login Page.";
}
else {
header('Location: index.php?page=login');
}
}
?>
There are echos all over the place. Try and limit the places where you do that by storing the output, rather than printing it all out straight away.
In your module for example, you could do $this->content = "You have been logged out..."
Then you can change the order of execution:
$cms->IncludeModule($_GET['page']);
include($cms->GetTheme() . "/head.php");
echo $cms->content;
include($cms->GetTheme() . "/foot.php");

how to assign variables to a redirect header when processing a PHP form

I have a form that I am validating via captcha.
I have an if statement.
If user enter wrong captcha, it tells it to go back.
else the page should re-direct to the following
http://tre.emv3.com/D2UTF8?emv_tag=876020001C384269&emv_ref=EdX7CqkdLe_d8SA9MOPQNCffL0p6Hq3D-jmueKEyWsbQKbo&FIRSTNAME_FIELD=XXXXXXXXX&LASTNAME_FIELD=XXXXXXXXX&DATEOFBIRTH_FIELD=XXXXXXXXX&EMAIL_FIELD=XXXXXXXXX&EMVCELLPHONE_FIELD=XXXXXXXXX&STORE_NAME_FIELD=XXXXXXXXX&
where every XXXXXXXX should be replaced by the variables from the form.
when I try the code below, the variables do not get replaced.
thank you for your help.
<?php session_start(); ?>
<?php
ob_start();
date_default_timezone_set("Europe/London");
include_once $_SERVER['DOCUMENT_ROOT'] . '/maininc/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "THIS IS WRONG.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}else{
$FIRSTNAME_FIELD = $_POST['FIRSTNAME_FIELD'];
$LASTNAME_FIELD = $_POST['LASTNAME_FIELD'];
$DATEOFBIRTH_FIELD = $_POST['DATEOFBIRTH_FIELD'];
$EMAIL_FIELD = $_POST['EMAIL_FIELD'];
$EMVCELLPHONE_FIELD = $_POST['EMVCELLPHONE_FIELD'];
$STORE_NAME_FIELD = $_POST['STORE_NAME_FIELD'];
header('location: http://tre.emv3.com/D2UTF8?emv_tag=876020001C384269&emv_ref=EdX7CqkdLe_d8SA9MOPQNCffL0p6Hq3D-jmueKEyWsbQKbo&FIRSTNAME_FIELD=echo$FIRSTNAME_FIELD;&LASTNAME_FIELD=echo$LASTNAME_FIELD;&DATEOFBIRTH_FIELD=echo$DATEOFBIRTH_FIELD;&EMAIL_FIELD=echo$EMAIL_FIELD;&EMVCELLPHONE_FIELD=echo$EMVCELLPHONE_FIELD;&STORE_NAME_FIELD=echo$STORE_NAME_FIELD;&');
}
ob_end_flush();
exit;
?>
get rid of the echo's in your link and use header(" .. ") instead of '
read here why http://php.net/manual/en/language.operators.string.php
Your string in the header function is surrounded by '. This will not convert variables. Change the surrounding ' with " and also remove the echo command.
header("location: http://tre.emv3.com/D2UTF8?emv_tag=876020001C384269&emv_ref=EdX7CqkdLe_d8SA9MOPQNCffL0p6Hq3D-jmueKEyWsbQKbo&FIRSTNAME_FIELD=$FIRSTNAME_FIELD&LASTNAME_FIELD=$LASTNAME_FIELD&DATEOFBIRTH_FIELD=$DATEOFBIRTH_FIELD&EMAIL_FIELD=$EMAIL_FIELD&EMVCELLPHONE_FIELD=$EMVCELLPHONE_FIELD&STORE_NAME_FIELD=$STORE_NAME_FIELD");

PHP function is automatically called when page loads, instead of being called through onclick event

I'm trying to redirect users of a web page to one of two different pages, depending on which of two buttons they click. My approach was to link each onclick event to a javascript function, which would in turn call a php function which uses the header() function to redirect to the appropriate page. Unfortunately, the latter of the two php functions, namely insertIntoTable(), is being called automatically each time the page loads and redirecting, without giving the user a chance to even look at the page with the buttons. I'm wondering if this is an artifact of way PHP is expanded? I don't really understand, becauseit seems like the wrapping javascript function shouldn't be called until the onclick event listener does so, and the php functions shouldn't be called until on the the javascript functions linked to onclick do so. Here is the code...
<?php
session_start();
?>
<html>
<head>
<script>
function createATable()
{
<?php createATable(); ?>
}
function insertIntoTable()
{
<?php insertIntoTable(); ?>
}
</script>
</head>
<body>
<?php
// Define our redirection functions for button click events
function createATable()
{
header("Location: http://codd.edu/Project2/createtable.php?<?php echo htmlspecialchars(SID); ?>");*/
}
function insertIntoTable()
{
header("Location: http://codd.edu/Project2/insertintotable.php?<?php echo htmlspecialchars(SID); ?>");*/
}
// Set session variables so that we don't need to worry about whether
// we're coming from sign in or registration - if $Session['user_name']
// isn't set, we know were coming from the sign in
if (!$_SESSION['user_name'])
{
$_SESSION['user_name'] = $_POST['nametextbox'];
$_SESSION['user_psswd'] = $_POST['psswdtextbox'];
echo "<br />setting session variables";
}
echo "<br />Not setting session variables";
// If we aren't setting the session variables, then we are coming from the
// registration page, and therefore know that this isn't an admin account
$_SESSION['is_admin'] = "false";
// Connect to database
$conn = mysql_connect("localhost", "601", "23");
or die('Could not connect: ' . mysql_error());
// Open database
mysql_select_db("601", $conn)
or die('Could not find database: ' . mysql_error());
// Get USER tuples, if any
$user = mysql_query("SELECT * FROM USERS WHERE name='$_SESSION[user_name]' AND password='$_SESSION[user_psswd]'");
// If there are no entries for this SELECT command, we cannot
// allow the user to log in
$num_user = mysql_num_rows($user);
if ($num_user < 1)
{
$_SESSION['is_user'] = "false";
header("Location: http://codd.edu/Project2/login.php?<?php echo htmlspecialchars(SID); ?>");
exit;
}
else
{
$_SESSION['user_id'] = SID;
$_SESSION['is_user'] = "true";
echo "Welcome ", $_SESSION['user_name'], "!";
echo "<br />User ID: " . $_SESSION['user_id'];
echo "<br /> User Password: " . $_SESSION['user_psswd'];
echo "Is valid user? " . $_SESSION['is_user'];
session_destroy();
echo "<button name='createtable' onclick='createATable()'>Create a Table</button>";
echo "<br /><button name='insert' onclick='insertIntoTable()'>Insert into Table</button>";
}
?>
</body>
</html>
I see no reason why createATable() shouldn't be called anytime the page is loaded. PHP is evaluated before javascript and on a different environment. Moreover, PHP allows you do define/declare a function after you call it, that is exactly what you're doing.
Pretend to be the PHP interpreter: it has no idea of what javascript is. You can even wrap the <?php createATable(); ?> line with yadayadayada ... qweryasdasd before and after it, and it will run.
Please, read this and see if it helps: http://www.developer.com/tech/article.php/923111/Client-side-Versus-Server-side-Coding---Part-1.htm
PS.: this is not related to your question, but please take a look at this: http://en.wikipedia.org/wiki/SQL_injection
Php runs on the server, the htnl output goes to the client.
Instead of trying to use php to redirect, use javascript or a simple a href.

Categories