How to keep the user logged on the entire web - php

I have a problem logging users. When logs, session work, but when you click to another page, the session will disappear and does not work and when I put session_start to the main page and to login.php, I got error that session is already running. Some ideas? Thanks
Main Page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="css.css">
<link rel="icon" href="favicon.ico">
<title>----</title>
</head>
<body>
<!-- HEADER _____________________________________________________________________________ -- >
<div id="whiteblock">
<div id="grayblock">
<div id="logo">
</div>
<h1>----</h1>
<h2>----</h2>
Registration
<?php
include "Login.php";
echo $_SESSION["LogiNick"];
?>
<div id="inputposunuti">
<form name="Log" id="Log" method="post">
<label for="Nick" class="inputtext">Nick:</label>
<input type="text" name="LogiNick" id="LogiNick" class="input"> <?php echo $EmptyNick; echo $Else; ?>
<label for="Pass" class="inputtext">Password:</label>
<input type="password" name="LogiPass" id="LogiPass" class="input"> <?php echo $EmptyPass; echo $Else; ?>
<input type="submit" name="LogIn" value="⇒">
</form>
</div>
</div>
<!-- HEADER _____________________________________________________________________________ -->
<!-- MENU _______________________________________________________________________________ -->
<div id="pruh">
<div id="search">
<form name="search" method="post">
<input type="text" name="hledat" id="sirka">
<input type="submit" name="subhledat" value="Search!" id="button">
</form>
</div>
<div id="menutext">
<p>Home</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
<p>----</p>
</div>
</div>
<!-- MENU _______________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<!-- CONTENT ____________________________________________________________________________ -->
<div id="teams"></div>
</div>
<p id="creator">Created by</p>
Login.php
<?php
session_start();
include_once "db.php";
global $db;
$Else = $EmptyNick = $EmptyPass = $EmptyNick = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$LogiNick = $_POST["LogiNick"];
$LogiPass = $_POST["LogiPass"];
if (empty($_POST["LogiNick"])) {
$EmptyNick = " - Nick";
}
if (empty($_POST["LogiPass"])) {
$EmptyPass = " - Password";
}
}
if(!empty($_POST["LogiNick"]) AND !empty($_POST["LogiPass"])){
$LogiPass = $_POST["LogiPass"];
$SHA = sha1($LogiPass);
$sql = "SELECT * FROM WEB_REGISTER WHERE Nick = :nick AND Heslo = :heslo";
$query = $db->prepare($sql);
$query->execute(array('nick' => $LogiNick, 'heslo' => $SHA));
$count = $query->rowCount();
if ($count > 0) {
$_SESSION["LogiNick"];
}
}
?>

You just set a session if you put a value into it.
$_SESSION["name"]=$value;

Related

HTML Form sends GET instead of POST (XAMPP, Apache, localhost)

I've looked up other questions with possible solutions to my problem, but they don't seem to work for me.
According to the Network console in Firefox, my contact form sends GET when I set the method to POST.
I have checked my HTML code for errors, but can't find any; no unclosed forms, divs, etc. I've checked the syntax for my php, too.
I also tried setting the submit button to <button type="submit" formmethod="post" formaction="form-to-email.php" name="submit" class="button">Und los</button>'but it doesn't help, either.
EDIT: Here's my complete HTML code for this page:
<!DOCTYPE html>
<html lang="" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="placeholder">
<meta name="keywords" content="placeholder">
<meta name="author" content="placeholder">
<title>MADesign.</title>
<link rel="author" href="robots.txt" />
<link rel="author" href="humans.txt" />
<!-- CSS -->
<link rel="stylesheet" href="css/maincss.css">
</head>
<body>
<div id="holder">
<!-- page header -->
<div class="bg-image-small">
<div id="main_menu">
<header id="page_header">
<img src="images/mad-logo-300px.png" alt="mad logo" id="mad-logo">
</header>
<!-- END page header -->
<!-- main navigation -->
<nav id="main-nav">
<ul>
<li>home</li>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>kontakt</li>
<li>impressum</li>
</ul>
</nav><!-- END main navigation -->
</div><!-- END main menu -->
</div><!-- END background image -->
<!-- main content -->
<main>
<!-- contact form -->
<form id="my-form" name="myForm" action="/form-to-email.php" method="post">
<h2>Let's get in touch.</h2>
<p>Schick mir eine Email an abc#placeholder.de oder nutze mein Kontaktformular.</p>
<div class="gender">
<input type="radio" name="titles" value="male" id="mr"
<?php if($titles == "male") echo "checked" ?>>
<label for="titles">Herr</label>
<input type="radio" name="titles" value="female" id="mrs"
<?php if($titles == "female") echo "checked" ?>>
<label for="titles">Frau</label>
<input type="radio" name="titles" value="nonbinary" id="mx"
<?php if($titles == "nonbinary") echo "checked" ?>>
<label for="titles">Hallo</label>
<input type="radio" name="titles" value="person" id="person"
<?php if($titles == "person") echo "checked" ?>>
<label for="titles">Person</label>
<div class="errormsg">
<?php echo $errors['titles']; ?>
</div>
</div>
<div class="form-block">
<label for="usrname">Name:</label><br>
<input type="text" name="usrname" id="usrname" class="styleinput" size="20" maxlength="30" value="<?php echo htmlspecialchars($usrname) ?>">
<div class="errormsg">
<?php echo $errors['usrname']; ?>
</div>
</div>
<div class="form-block">
<label for="email">Email:</label><br>
<input type="text" name="email" id="email" class="styleinput" size="20" maxlength="30" value="<?php echo htmlspecialchars($email) ?>">
<div class="errormsg">
<?php echo $errors['email']; ?>
</div>
</div>
<div class="user-input form-block">
<label for="user-input">Nachricht:</label><br>
<textarea class="styleinput" id="message-me" name="usrmsg" rows="4" cols="50" value="<?php echo htmlspecialchars($usrmsg) ?>"></textarea>
<div class="errormsg">
<?php echo $errors['usrmsg']; ?>
</div>
</div>
<button type="submit" formmethod="post" formaction="/form-to-email.php" name="submit" class="button">Und los</button>
<input type="reset" name="reset" class="button" value="Nochmal neu..." onclick="emptyMsg()">
<div id="message"></div>
</form>
<!-- END contact form -->
</main>
<!-- END main content -->
<!-- footer -->
<footer>
<p>&copy2019 placeholder</p>
</footer><!-- END footer-->
</div><!-- END holder -->
<!-- JavaScript and jQuery -->
<script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script>
<script src="js/mainjs.js"></script>
</body>
</html>
This is the PHP (saved in the same directory as kontakt.php):
<?php
$titles = $usrmsg = $usrname = $email = "";
$errors = array("email"=>"", "usrname"=>"", "usrmsg"=>"", "titles"=>"");
if(isset($_POST["submit"])){
//check Email
if(empty($_POST["email"])){
$errors["email"] = "Bitte Email Adresse angeben.";
} else {
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors["email"] = "Die Email Adresse sollte gültig sein.";
}
}
//check name
if(empty($_POST["usrname"])){
$errors["usrname"] = "Wie heißt du?";
} else {
$usrname = $_POST["usrname"];
$usrname = filter_var($usrname, FILTER_SANITIZE_STRING);
if(!preg_match("/^[a-zA-Z\s]+$/", $usrname)){
$errors["usrname"] = "Sorry! Der Name darf nur Buchstaben und Leerzeichen enthalten.";
}
}
//check message
if(empty($_POST["usrmsg"])){
$errors["usrmsg"] = "Hier sollte etwas Text stehen. Muss ja nicht viel sein.";
} else {
$usrmsg = $_POST["usrmsg"];
$usrmsg = filter_var($usrmsg, FILTER_SANITIZE_STRING);
}
//check titles
$titles = $_POST["titles"];
if ($titles==NULL) {
$errors["titles"] = "Welche Ansprache darf ich verwenden?";
}
}
?>
EDIT: Here's the JS for client-side form validation (it's not a finished version, some validations are still missing/may get changed, but so far it's working as it should):
var myForm = document.forms.myForm;
var message = document.getElementById('message');
myForm.onsubmit = function() {
//get IDs for the title
var mr = document.getElementById('mr');
var mrs = document.getElementById('mrs');
var mx = document.getElementById('mx');
var pers = document.getElementById('person');
//get ID for the textarea
var usrInput = document.getElementById('message-me');
if (myForm.usrname.value == "") {
message.innerHTML = "Moment! Wie heißt du?"
return false;
} else if (usrInput.value == "") {
message.innerHTML = "Das Nachrichtenfeld sollte nicht leer sein..."
return false;
} else if (email.value == "") {
message.innerHTML = "Wie lautet deine Email Adresse?"
return false;
} else if (usrInput.value.length < 10) {
//check min length of textarea
message.innerHTML = "Die Nachricht sollte etwas länger sein..."
return false;
} else if (!mr.checked &&
!mrs.checked &&
!mx.checked &&
!pers.checked) {
message.innerHTML = "Welche Ansprache darf ich verwenden?"
return false;
} else {
message.innerHTML = "";
return true;
}
I'm using XAMPP (Apache) to test this via localhost.
How can I get the form to send POST, not GET? Did I overlook syntax errors, typos or are there errors with my variables that I can't find? Thx for any input.
This happens sometimes. I don't think I am experienced enough to give you a perfect solution but here's a bunch of try outs you can implement:
Try to write the "post" keyword in capitals (like "POST").
Sometimes the xampp server does not reflect changes even after you save and refresh. Try refreshing with (ctrl+F5). This imposes a hard refresh causing the xampp server to reload all the resourses.
Try restarting the xampp server.
Please revert if anything was helpful....

Auto fill-in data (input field) from MySQL Database in PHP (PDO)

This post contains:
3 PHP pages
MySQL table picture
Picture of the form
As the title says, I need to extract some information from my database.
So far I have the following:
Index page <-- You need to login here with a personal code. (this is where I get the 'Session username' from that already works at the contact page)
Config page <-- Used for database access and all
Contact page <-- In here I would like to auto fill-in the users data.
Database table consists of:
username; email; realName (and some other stuff I don't need here)
So in the contact page I would like to see the following:
Card number = username (this already works)
Auto fill-in: realName and email according to the username.
Maybe it is possible to extract the info when logging in and storing these in the POST variable already? But how?
Database:
Table I need to use: 'members'
The info given by the user himself/herself = username
The info I need to auto fill-in = realName and email
Picture of the form.
The email should be in the SESSION statement, so I can send a confirmation email to the person, and the realName should be entered from the database.
These are the files currently running:
config.php:
<?php
ob_start();
session_start();
//set timezone
date_default_timezone_set('Europe/Brussels');
//database credentials
define('DBHOST','*****');
define('DBUSER','*****');
define('DBPASS','*****');
define('DBNAME','*****');
//application address
define('DIR','http://*****/');
define('SITEEMAIL','noreply#*****');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
contact form:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); }
?>
<html>
<head>
<title>*****</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/shiv.js"></script><![endif]-->
<link rel="stylesheet" href="siteassets/assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="siteassets/assets/css/ie8.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#next').keyup(calculate);
$('#nextprice').keyup(calculate);
$('#current').keyup(calculate);
$('#currentprice').keyup(calculate);
});
function calculate(e)
{
$('#total').val($('#next').val() * $('#nextprice').val() + $('#current').val() * $('#currentprice').val());
}
</script>
</head>
<body class="landing">
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<nav id="nav">
<ul>
<li>
Menu
<ul>
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
</ul>
</li>
<li>contact</li>
<li><a href='logout.php'>Logout</a></li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<h2>*****</h2>
<p>Slogan.</p>
<ul class="actions">
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
<li>contact</li>
</ul>
</section>
<!-- Main -->
<section id="main" class="container 75%">
<div class="box">
<?
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(strlen($_POST['name2']) == 0)
{ $error_msg ="- Please, provide us with your name.<br>"; }
if(!empty($error_msg))
{
//Een van de velden werd niet goed ingevuld
echo "<b>Your message can't be send due to the following reason:</b> <br><br>";
echo $error_msg;
echo "<br>Click on <a href='javascript:history.back(1)'>Go back</a> and provide us with your name.<br><br>";
}
else
{
$recipient = "*****";
$subject = "******";
$header = "From: " . $_POST['uwemail'] . "\n";
$mail_body = "Contact script werd op " . date("d-m-Y") . " om " . date("H:i") . " uur uitgevoerd.\n";
$mail_body .= "*****:\n\n";
$mail_body .= "Naam: " . $_POST['name2'] . "\n";
$mail_body .= "Met als kaartnummer: " . $_POST['card2'] . "\n";
$mail_body .= "******: " . $_POST['current2'] . "\n";
$mail_body .= "******: " . $_POST['next2'] . "\n";
$mail_body .= "Voor een totaal van: " . $_POST['total2'] . " EUR.";
$mail_body .= "\n\n -- ****** --";
mail($recipient, $subject, $mail_body, $header);
print "<b>IMPORTANT!</b>";
print "<br><br>*****.";
print "<br><br>***** ";
print $_POST['total2'];
print " *****";
print "<br><br>******.";
print "<br><br>******";
}
}
else
{
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Please enter your name. (mandatory)
<input type="text" name="name2" id="name" value="" placeholder="Your name" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Current Project - Smile
<input type="text" name="current2" id="current" value="" placeholder="How many tickets would you like?" />
</div>
<div class="6u 12u(mobilep)">
Next Project - Sand
<input type="text" name="next2" id="next" value="" placeholder="How many tickets would you like?" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice" value="10" placeholder="" />
</div>
</div>
<div class="6u 12u(mobile)">
<input name="uwemail" placeholder="Email" type="hidden" value="******"/>
</div>
<div class="6u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
<?php
}
?>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© *****. All rights reserved.</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<script src="siteassets/assets/js/jquery.min.js"></script>
<script src="siteassets/assets/js/jquery.dropotron.min.js"></script>
<script src="siteassets/assets/js/jquery.scrollgress.min.js"></script>
<script src="siteassets/assets/js/skel.min.js"></script>
<script src="siteassets/assets/js/util.js"></script>
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="siteassets/assets/js/main.js"></script>
</body>
</html>
Index page (where they have to login)
<?php
//include config
require_once('includes/config.php');
//process login form if submitted
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}//end if submit
?>
<html>
<head>
<title>******</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/iv.js"></script><! [endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 9]><link rel="stylesheet" href="assets/css/ie9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /> </noscript>
</head>
<body class="is-loading">
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<section id="main">
<header>
<h1>*****</h1>
<h1><a style="color:#FFFFFF" href=''>Coming soon.</a></h1>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Please Login</h2>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please contact us for a new card.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Enter your card number" value=" <?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="hidden" name="password" id="password" class="form-control input-lg" value="*****" tabindex="3" >
</div>
<br>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Login" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
<hr>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a style="color:#FFFFFF" href='*********'>Lost your card? Contact us.</a>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ******</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<!--[if lte IE 8]><script src="assets/js/respond.min.js"> </script><![endif]-->
<script>
if ('addEventListener' in window) {
window.addEventListener('load', function() { document.body.className = document.body.className.replace(/\bis-loading\b/, ''); });
document.body.className += (navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? ' is-ie' : '');
}
</script>
</body>
</html>
EDITED: Since you're having user class (ex.: $user->is_logged_in()), then in $_POST[] method ignore $_POST['name2'] as it can still be changed through DEV tools and instead change that to $_SESSION['username'] (assuming that's the correct value). This is much more reliable than using HTML field. The PHP part (of query) also differs because you're using PDO, but I can't help with this one because I'm using mysqli_, not PDO (sorry about that), but query itself should be similar.
"SELECT * FROM `table` WHERE `number` = '".$_POST['number']."'"
But don't forget to escape your string, otherwise, your query is vulnerable.
I fixed the problem.
In the user.php file I had everything prepared already, but I just didn't understand why it didn't work.
Turned out to be a simple error XD
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['realName'] = $row['realName'];
$_SESSION['email'] = $row['email'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
return true;
}
}
}
?>
I forgot to add the realName and email to this line: (idiot me :D)
$stmt = $this->_db->prepare('SELECT password, username, memberID, realName, email FROM members WHERE username = :username AND active="Yes" ');

Getting json response for android from PHP

I am newbie in php, kindly pardon me if I looks silly. I am still learning step by step with the help of online forums and stack community.
I have a form online which code is as below:
<?php
define('DIR_APPLICATION', str_replace('\'', '/', realpath(dirname(__FILE__))) . '/');
include(DIR_APPLICATION."config.php");
ob_start();
session_start();
$msg = 'none';
$sql = '';
if(isset($_POST['email']) && $_POST['email'] != '' && isset($_POST['password']) && $_POST['password'] != ''){
if($_POST['usertype'] == 'admin'){
//here for admin
$sql= mysql_query("SELECT * FROM admin WHERE a_email = '".make_safe($_POST['email'])."' and password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'teacher'){
//here for teacher
$sql= mysql_query("SELECT * FROM teacher WHERE t_email = '".make_safe($_POST['email'])."' and t_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'student'){
//here for student
$sql= mysql_query("SELECT * FROM student WHERE s_email = '".make_safe($_POST['email'])."' and s_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'parents'){
//here for parent
$sql= mysql_query("SELECT * FROM parent WHERE p_email = '".make_safe($_POST['email'])."' and p_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'librarian'){
//here for employee
$sql= mysql_query("SELECT * FROM user WHERE u_email = '".make_safe($_POST['email'])."' and u_password = '".make_safe($_POST['password'])."'",$link);
}
else if($_POST['usertype'] == 'accountant'){
//here for employee
$sql= mysql_query("SELECT * FROM user WHERE u_email = '".make_safe($_POST['email'])."' and u_password = '".make_safe($_POST['password'])."'",$link);
}
if($row = mysql_fetch_array($sql)){
//here success
$_SESSION['objLogin'] = $row;
$_SESSION['login_type'] = $_POST['usertype'];
if($_POST['usertype'] == 'admin'){
header("Location: dashboard.php");
die();
}
else if($_POST['usertype'] == 'teacher'){
header("Location: t_dashboard.php");
die();
}
else if($_POST['usertype'] == 'student'){
header("Location: s_dashboard.php");
die();
}
else if($_POST['usertype'] == 'parents'){
header("Location: p_dashboard.php");
die();
}
else if($_POST['usertype'] == 'accountant'){
header("Location: a_dashboard.php");
die();
}
else if($_POST['usertype'] == 'librarian'){
header("Location: l_dashboard.php");
die();
}
}
else{
$msg = 'block';
}
}
function make_safe($variable)
{
$variable = strip_tags(mysql_real_escape_string(trim($variable)));
return $variable;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SITE TITLE | Log in</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="plugins/iCheck/square/blue.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<b>SITE</b> TITLE
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form onSubmit="return validationForm();" role="form" id="form" method="post">
<div class="form-group has-feedback">
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<select class="form-control" name="usertype" id="usertype">
<option value="-1">-- Select User Type --</option>
<option value="admin">Admin</option>
<option value="teacher">Teacher</option>
<option value="student">Student</option>
<option value="parents">Parents</option>
<option value="accountant">Accountant</option>
<option value="librarian">Librarian</option>
</select>
</div>
<div class="row">
<div class="col-xs-8">
Forget Password?<br>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" id="login" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.2.0 -->
<script src="plugins/jQuery/jQuery-2.2.0.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="plugins/iCheck/icheck.min.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
<script type="text/javascript">
function validationForm(){
if($("#email").val() == ''){
alert("Email Required !!!");
$("#email").focus();
return false;
}
else if($("#password").val() == ''){
alert("Password Required !!!");
$("#password").focus();
return false;
}
else if($("#usertype").val() == '-1'){
alert("Select User Type !!!");
return false;
}
else{
return true;
}
}
</script>
<!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME-->
<!-- JQUERY SCRIPTS -->
<script src="assets/js/jquery-1.10.2.js"></script>
<!-- BOOTSTRAP SCRIPTS -->
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
This form works perfectly.
But my issue is I am creating an android form for this online version where I need a json response. So I tried the following in the browser:
mydomain.com/index.php?email=user#example.com&password=mypass&usertype=student
This results in the same page.
I am confused why this is not entering the page.
I can understand that somewhere I am wrong but can't figure it out.
Kindly help please.
As #Akhil #Vijay and #MiguelJimenez suggested
I changed $_POST to $_REQUEST and it worked like a charm
So, if any one getting stuck in this issue this might help you guys hopefully.

PHP MySQL display image from database

Hi I have form to make new article with informations and image. I susccesfuly save all info and image to database (i guess). And when I want to display info and image so only info works.
See in picture.
Any help? Thanks a lot
Inserting_post.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>APK Market</title>
<link rel="stylesheet" type="text/css" href="../style/style.css">
<link href="../bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<script src="../bootstrap/js/bootstrap.min.js"></script>
<script src="../bootstrap/js/bootstrap.js"></script>
</head>
<body>
<form method="post" action="insert_post.php" enctype="multipart/form-data">
<div class="new_post">
<div class="headtitle">Insert new post</div>
<div class="new_title">
<p>New title</p>
<input type="text" name="title">
</div>
<div class="new_author">
<p>Author</p>
<input type="text" name="author">
</div>
<div class="new_keywords">
<p>Keywords</p>
<input type="text" name="keywords">
</div>
<div class="new_image">
<p>Image</p>
<input type="file" name="image">
</div>
<div class="new_content">
<textarea name="content" cols="20" rows="8"></textarea>
</div>
<div class="submit">
<input type="submit" name="submit" value="OK">
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="../bootstrap/js/bootstrap.js"></script>
</body>
</html>
<?php
include("../includes/connect.php");
if(isset($_POST['submit']))
{
$games_date = date('y-m-d-h');
$games_title = $_POST['title'];
$games_author = $_POST['author'];
$games_keywords = $_POST['keywords'];
$games_image = $_FILES['image']['name'];
$games_tmp = $_FILES['image']['tmp_name'];
$games_content = $_POST['content'];
if($games_title=="" or $games_author=="" or $games_keywords==""
or $games_content=="")
{
echo"<script>alert('any field is empty')</script>";
exit();
}
else
move_uploaded_file($games_tmp,"../uploaded_images/$games_image");
$insert_query= "insert into games(games_title,games_date,games_author,games_image,
games_keywords,games_content)
values ('$games_title','$games_date','$games_author','$games_image',
'$games_keywords','$games_cont ent')";
}
if(mysql_query($insert_query))
{
echo "<center><h1>Post published seccesfuly!</h1></center>";
}
?>
display page:
<div class="content">
<?php
include('connect.php');
$select_posts = "select * from games";
$run_posts = mysql_query($select_posts);
while($row=mysql_fetch_array($run_posts))
{
echo '<p class="games_title_result">' .$games_title = $row['games_title'];
echo '<p class="games_image_result"><img src="<?php echo $row["games_image"];?>';
echo '<p class="games_content_result">' .$games_content = $row['games_content'];
echo '<p class="games_date_result">' .$games_date = $row['games_date'];
echo '<p class="games_author_result">' .$games_author = $row['games_author'];
}
?>
</div>
Here's my answer:
echo '<p class="games_image_result"><img src="uploaded_images/'.$row["games_image"].'" />';
You got a syntax error where you include a <?php and ?> inside your php, and on your echo at that.
So when you look at your img's src, it would have those.
Also, you forgot to close your img tag and your other p tags.
Your image tag isn't closed properly and the path to the image is not complete. You are only specifying the filename. I am not sure about your directory structure
echo '<p class="games_image_result"><img src="uploaded_images/<?php echo $row["games_image"];?>" />';
Display Image from DataBase using php
# SQL Statement
$sql = "SELECT `idimage` FROM `yourTableName` WHERE id=" . mysqli_real_escape_string($_GET['id']) . ";";
$result = mysqli_query("$sql") or die("Invalid query: " . mysqli_error());
# Set header
header("Content-type: image/your image name which type of your image");
echo mysqli_result($result, 0);
}
else
echo 'Please check the ID!';
?>
I wish it's may be help you

Echo not displaying, or adding ID, but shows up in database

I set up a PHP database that worked perfectly on my local server. Then, when I went to put it online through my hosting site, Site5, I was getting these kinds of errors: "Cannot modify header information – headers already sent by...". So I changed the PHP file on Site5 to have output buffering turned on. Now, I am not getting an error, however, whenever I input data, it doesn't echo it back - however, it does show up in the database in phpMyAdmin (but without an ID).
Any ideas as to why it isn't echoing back and why it's new data isn't getting an ID?
Here it is live (and broken):
http://hjaramillo.com/tell_me/index.php
<!DOCTYPE html>
<html class="no-js" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A Message For You</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="css/media.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
</head>
<?php
ob_start();
//error_reporting(0);
require 'db/connect.php';
require 'functions/security.php';
error_reporting(E_ALL);
$records = array();
if(!empty($_POST)){
if(isset($_POST['first_name'],$_POST['location'],$_POST['message'])) {
$first_name = trim($_POST['first_name']);
$location = trim($_POST['location']);
$message = trim($_POST['message']);
if(!empty($first_name) && !empty($location) && !empty($message)) {
$insert = $db -> prepare("INSERT INTO message (first_name, location, message, date) VALUES (?,?,?,NOW())");
$insert->bind_param('sss',$first_name,$location,$message);
if($insert -> execute()){
header ('Location: index.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM message ORDER BY id DESC LIMIT 1")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results -> free();
}
}
?>
<?php
if (!count($records)){
echo 'No messages';
} else{
?>
<?php
foreach($records as $r){
?>
<body>
<?php
}}
?>
<div class="form-show">
<div class="post-icon">
<img src="images/post_icon.png"/>
</div>
</div>
<div class="form-background">
<div class="form-container">
<div class="form-title">
<p>Tell someone that:</p>
</div>
<form action="index.php" method="post">
<div class="fields msg">
<!--<label for="message">Message</label>-->
<textarea name="message" id="message" autocomplete="off"></textarea>
</div>
<div class="fields">
<ul>
<li> <label for="first_name">Name</label> </li>
<li> <input type="text" class="s-input" name="first_name" id="first_name" autocomplete="off"> </li>
</ul>
</div>
<div class="fields last">
<ul>
<li><label for="location">Location</label></li>
<li><input type="text" class="s-input" name="location" id="location" autocomplete="off"></li>
</ul>
</div>
<input type="submit" value="Post" id="submit-button">
</form>
<div>
</div>
</div>
</div>
<div class="msg-container">
<div class="msg-intro">
<p> On <?php echo escape($r->date); ?>,</p>
<p><span style="text-transform:capitalize;"><?php echo escape($r->first_name); ?> </span> from
<span style="text-transform:capitalize;"><?php echo escape($r->location); ?></span> wanted to tell you:</p>
</div>
<div class="msg-content">
<p><?php echo escape($r->message); ?></p>
</div>
</div>
</body>
<script type="text/javascript" src="js/application.js"></script>
</html>
Someone earlier asked if my ID was set to AUTO INCREMENT - it wasn't. That was the problem, thanks!

Categories