how does $_session work? and have i done something wrong? php - php

i am new to php and coding in general. i wanted to make a signup/login system. the signup and login function works but when i login i want to stay on index.php and change the context. but for some reason it doesn't work. have i done something wrong?
this is my login code:
(gebruikersnaam = username & wachtwoord = password)
<?php
if(!isset($_SESSION)){
session_start();
}
include "../../db/dbconnect.php";
include "logs.inc.php";
$gebruikersnaam = mysqli_real_escape_string( $db, $_POST['gebruikersnaam'] );
$wachtwoord = mysqli_real_escape_string( $db, $_POST['wachtwoord'] );
$salt = "46elg9hl50h[[erlt".$wachtwoord."tesy45745jytj57sasfq";
if( empty( $gebruikersnaam ) || empty( $wachtwoord ) ){
header( "Location: ../index.php?/Fields=Empty" );
exit();
}
$sql = mysqli_query( $db, "SELECT * FROM organisatie WHERE OrgGebNaam='$gebruikersnaam' OR OrgEmail='$gebruikersnaam'" );
$result = mysqli_num_rows( $sql );
if( $result < 1 || $result > 1){
header( "Location: ../index.php?/Error/result" );
exit();
}
else {
if( $row = mysqli_fetch_assoc( $sql ) ){
$hashCheck = password_verify( $salt, $row['OrgWW']);
if( $hashCheck == false ){
header( "Location: ../index.php?/Error/Password_Incorrect#1");
exit();
}
else if( $hashCheck == true ){
$_SESSION['ID'] = $row['gebruikerID'];
$_SESSION['Geb'] = $row['gebruikersnaam'];
log_ingelogd();
header( "Location: ../index.ad.php?/Welcome.".$gebruikersnaam );
exit();
}
}
else{
header( "Location: ../index.php?Error/Password_Incorrect#2");
exit();
}
}
?>
and this is index.php:
<?php
include 'header.php';
include '../db/dbconnect.php';
error_reporting(0);
if( !isset( $_SESSION['ID']) && !isset( $_SESSION['Geb'])) {
?>
<section>
<table id="login-table">
<form action="include/login2.inc.php" method="POST">
<tr>
<td colspan=2 style="text-align: center;"> Login Formulier</td>
</tr>
<tr>
<td><div class="table-text">Gebruikersnaam: </div></td>
<td><input type="text" class="login-table-text" name="gebruikersnaam" required title="Vul hier uw gebruikersnaam in." placeholder="Gebruikersnaam"></td>
</tr>
<tr>
<td><div class="table-text">Wachtwoord: </div></td>
<td><input type="password" class="login-table-text" name="wachtwoord" required title="Vul hier uw wachtwoord in." placeholder="Wachtwoord"></td>
</tr>
<tr>
<td colspan=2 style="text-align: center;"><button id="login-btn" name="submit">Inloggen</button></td>
</tr>
</form>
<form action="signup.php" method="POST">
<tr>
<td colspan=2><hr></td>
</tr>
<tr>
<td><div class="table-text">Als u geen account heeft: </div></td>
</tr>
<tr>
<td colspan=2 style="text-align: center;"><button id="signup-btn" name="signup">Maak een account aan ></button></td>
</tr>
</form>
</table>
</section>
<?php
} // ending if statement.
$gebruikersnaam = $_SESSION['Geb'];
$sql = mysqli_query( $db, " SELECT * FROM gebruikers WHERE gebruikersnaam = '$gebruikersnaam'" );
$row = mysqli_fetch_assoc( $sql );
if( $row['IsAdmin'] == 1){
?>
<div class="container">
<div class="box">
<table class="box-information">
<tr class="box-information-titel">
<td>Gebruikers</td>
</tr>
</table>
<p class="box-information-omschrijving">Bekijk hier de gegevens van alle gebruikers, maak gebruikers aan, verwijder gebruikers en bewerk de gegevens van gebruikers.</p>
<div id="box-btn-gebruiker">
<button class="box-btn">Bekijk ></button>
</div>
</div>
<div class="box">
<table class="box-information">
<tr class="box-information-titel">
<td>Onderhoud</td>
</tr>
</table>
<p class="box-information-omschrijving">Bekijk hier het onderhouds tabel zodat u onderhoud kan uitvoeren.</p>
<div id="box-btn-onderhoud">
<button class="box-btn">Bekijk ></button>
</div>
</div>
<div class="box">
<table class="box-information">
<tr class="box-information-titel">
<td>Organisatie</td>
</tr>
</table>
<p class="box-information-omschrijving">Bekijk hier alle gegevens die een organisatie heeft.</p>
<div id="box-btn-organisatie">
<button class="box-btn">Bekijk ></button>
</div>
</div>
<div class="box">
<table class="box-information">
<tr class="box-information-titel">
<td>Factuur</td>
</tr>
</table>
<p class="box-information-omschrijving">Bekijk hier alle openstaande facturen, maak facturen en factuurregels.</p>
<div id="box-btn-factuur">
<button class="box-btn">Bekijk ></button>
</div>
</div>
</div>
<?php
}
include 'footer.php';
?>
can someone tell me what i did wrong?
edit: (im not sure but...) i think the problem lies here:
$gebruikersnaam = $_SESSION['Geb'];
$sql = mysqli_query( $db, " SELECT * FROM gebruikers WHERE gebruikersnaam = '$gebruikersnaam'" );
$row = mysqli_fetch_assoc( $sql );
if( $row['IsAdmin'] == 1){
edit: this is my header.php:
<?php
if(!isset($_SESSION)){
session_start();
}
?>

Maybe missing session_start(); in file index.php

Related

Delete image(s) associated with record from folder

I have a page that allows for multiple record deletes using checkboxes and all works fine.
However, each record may have an image associated with it stored in a folder that would also need to be deleted but I have no idea how to achieve this even though I've searched Stackoverflow and Google.
How do I delete the record(s) from the MySQL database and the image(s) associated with it from the folder?
What I have so far is:
The code that deletes the records:
if ( isset( $_POST[ 'chk_id' ] ) ) {
$arr = $_POST[ 'chk_id' ];
foreach ( $arr as $id ) {
#mysqli_query( $KCC, "DELETE FROM pageContent WHERE contentID = " . $id );
}
$msg = "Page(s) Successfully Deleted!";
header( "Location: delete-familyservices.php?msg=$msg" );
}
The form that selects the records to delete:
<form name="deleteRecord" id="deleteRecord" method="post" action="delete-familyservices.php">
<?php if (isset($_GET['msg'])) { ?>
<p class="alert alert-success">
<?php echo $_GET['msg']; ?>
</p>
<?php } ?>
<table width="100%" class="table table-striped table-bordered table-responsive">
<tr>
<th>Page Title</th>
<th>Page Text</th>
<th>Page Image</th>
<th>Delete</th>
</tr>
<?php do { ?>
<tr>
<td width="30%" style="vertical-align: middle">
<h4 style="text-align: left">
<?php echo $row_rsContent['contentTitle']; ?>
</h4>
</td>
<td width="45%" style="vertical-align: middle">
<?php echo limit_words($row_rsContent['contentData'], 10); ?> ...</td>
<td align="center" style="vertical-align: middle">
<?php if (($row_rsContent['contentImage']) != null) { ?>
<img src="../images/<?php echo $row_rsContent['contentImage']; ?>" class="img-responsive">
<?php } else { ?> No Image
<?php } ?>
</td>
<td width="5%" align="center" style="vertical-align: middle"><input type="checkbox" name="chk_id" id="chk_id" class="checkbox" value="<?php echo $row_rsContent['contentID']; ?>">
</td>
</tr>
<?php } while ($row_rsContent = mysqli_fetch_assoc($rsContent)); ?>
</table>
<p> </p>
<div class="form-group" style="text-align: center">
<button type="submit" name="submit" id="submit" class="btn btn-success btn-lg butt">Delete Selected Page(s)</button>
<button class="btn btn-danger btn-lg butt" type="reset">Cancel Deletion(s)</button>
</div>
</form>
The final piece of code, which is a confirmation script:
<script type="text/javascript">
$( document ).ready( function () {
$( '#deleteRecord' ).submit( function ( e ) {
if ( !confirm( "Delete the Selected Page(s)?\nThis cannot be undone." ) ) {
e.preventDefault();
}
} );
} );
</script>
I've seen the unlink() function mentioned but I don't know if this is what to use or have any idea how to incorporate it into the existing code if it is.
you'll have to use the path of the image which is stored on you database like so :
unlink(' the link of the images which is fetched from db'); // correct
don't forget to check for image existence file_exists() //
Got this from another site and a bit of trial and error.
if($_POST) {
$arr = isset($_POST['chk_id']) ? $_POST['chk_id'] : false;
if (is_array($arr)) {
$filter = implode(',', $arr);
$query = "SELECT *filename* FROM *table* WHERE *uniqueField* IN ({$filter})";
$result = mysqli_query(*$con*, $query);
while ($row = mysqli_fetch_object($result)) {
$pathToImages = "*path/to/images*";
{
unlink("{$pathToImages}/{$row->contentImage}");
}
}
// DELETE CAN BE DONE IN ONE STATEMENT
$query = "DELETE FROM *table* WHERE *uniqueField* IN ({$filter})";
mysqli_query(*$con*, $query);
$msg = "Page(s) Successfully Deleted!";
header("Location: *your-page.php*?msg=$msg");
}
}
Thanks to everyone who contributed.
Hope this is of some help to others.

Error in sql query with php and mysql?

I got this error
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near '' at line 1
and here is my code
<?php
$titulo = "Baja de usuario";
require "conexion.php";
$usu_nombre = $_POST["usu_nombre"];
$usu_id = $_POST["usu_id"];
$sql = "DELETE FROM usuarios WHERE usu_id = ".$usu_id;
$resultado = mysqli_query($link, $sql) or die(mysqli_error($link));
$chequeo = mysqli_affected_rows($link);
include "encabezado.php";
?>
Can't really find the syntax error there, any idea?
the $_POST["usu_id"] comes from here:
$titulo = "Formulario de baja- Usuarios - Proyecto integrador";
require "conexion.php";
$usu_id = $_GET["usu_id"];
$sql = "SELECT usu_id, usu_login ,usu_clave, usu_nombre, usu_email FROM usuarios WHERE usu_id = ".$usu_id;
$resultado = mysqli_query($link, $sql) or die(mysqli_error($link));
?>
<?php include "encabezado.php"; ?>
</head>
<body>
<div id="top"><img src="imagenes/top.png" alt="encabezado" width="980" height="80"></div>
<div id="nav">
<?php include "menu.php"; ?>
</div>
<div id="main">
<h1><?php echo $titulo ; ?></h1>
<!-- inicio del desarrollo -->
<form action = "baja-usuario.php" method = "post" onsubmit = "return confirmarBaja()">
<table id="paneles">
<tr>
<th colspan ="5">Se eliminara el siguiente usuario</th>
</tr>
<tr>
<th>Id</th>
<th>Login</th>
<th>Clave</th>
<th>Nombre</th>
<th>Email</th>
</tr>
<?php while($fila = mysqli_fetch_assoc($resultado)){ ?>
<tr>
<td class = "lista"><?php echo $fila["usu_id"] ;?></td>
<td class = "lista"><?php echo $fila["usu_login"]; ?></td>
<td class = "lista"><?php echo $fila["usu_clave"] ;?></td>
<td class = "lista"><?php echo $fila["usu_nombre"] ;?></td>
<td class = "lista"><?php echo $fila["usu_email"] ;?></td>
</tr>
<?php } ?>
<tr>
<td><input type= "hidden" name = "usu_id" value = "<?php echo $fila["usu_id"]; ?>"></td>
<td><input type= "hidden" name = "usu_nombre" value = "<?php echo $fila["usu_nombre"]; ?>"></td> <!-- el input type hidden no renderiza el valor pero si sirve para pasarlo como parametro en el FROM -->
</tr>
<tr>
<td colspan = "2" class ="centrar"><input type = "submit" value = "Eliminar"></td>
</tr>
</table>
</form>
and the usu_id from the : <td class = "lista"><?php echo $fila["usu_id"] ;?></td> displays correctly, showing the ID
The error was that i was using <?php while($fila = mysqli_fetch_assoc($resultado)){ ?> and so the usu_id the form send to the POST, was empty beacuse of the msqli_fetch_assoc

PHP my math doesnt work and my vairable shows 0 but it is something else

So my problem is i`ve set Variables at the beginning og my Script and later in the script i need that variable to do some math so it knows if it has money to buy something and if it has no money to buy the items. so heres my script
The error shows up all the way on the bottom of the script.
$user = 'Ramon';
// get integer data from url
$removeslash = "/xampp/";
$actual_link3 = "$_SERVER[REQUEST_URI]";
$actual_link2 = str_replace($removeslash,"",$actual_link3);
$actual_link = str_replace(".php","",$actual_link2);
echo $actual_link;
// connect to mysql database
$conn = mysqli_connect($host,$username,$password, $database);
if (!$conn) {
die('Not connected : ' . mysqli_error());
}
$result = mysqli_query($conn, "SELECT * FROM Bedrijf WHERE ID='".$actual_link."'");
$row = mysqli_fetch_array($result);
$NaamBedrijf = $row['Name'];
$WorthNow = $row['WorthNow'];
$result2 = mysqli_query($conn, "SELECT * FROM Users WHERE Username='".$user."'");
$row2 = mysqli_fetch_array($result2);
$Aandelen = $row2['Shares'.$actual_link];
$Money = $row2['Money'];
echo "IK HRB NU".$Aandelen;
//Waarde aandelen berkenen
$WaardePort = $Aandelen * $WorthNow;
//Geld formateren van 1293384 naar $1,293,384.00
setlocale(LC_MONETARY, 'en_US');
$MoneyFOR = money_format('%(#10n', $Money) . "\n";
$WaardePort = money_format('%(#10n', $WaardePort) . "\n";
$WaardeNU = money_format('%(#10n', $WorthNow) . "\n";
echo "AANDELEN:".$Aandelen;
echo "<html>
<head>
<title>Beurs</title>
<link rel='stylesheet' type='text/css' href='index.css'/>
</head>
<body>
<center>
<table>
<tr>
<td width='992px'>
<p class='ingelogd'>Je bent ingelogd Als ".$user."</p>
</td>
</tr>
<tr>
<td width='992px'>
<p>Er staat ".$MoneyFOR." Dollar op je bank.</p>
</td>
</tr>
</table><br/>
<table>
<tr>
<td id='Title' width='992px'>Je Kunt Informatie zien over je aandelen en aandelen verkopen/kopen.</td>
</tr>
</table>
<table width='1000px'>
<tr>
<td>".$NaamBedrijf."</td>
<td>".$WaardeNu."</td>
<td>".$Aandelen."</td>
</tr>
<tr>
<form>
<td>Kopen of Verkopen?</td>
<td>
<input type='radio' name='1' value='1'>Verkopen</input>
<input type='radio' name='2' value='2'>Kopen</input><br/>
</td>
<td>Aantal andelen:<input style='width:85px;' type='text' name='Totaal'/><input type='submit' name='submit' value='Koop/Verkoop'/></td>
</form>
</tr>
</table>
<table>
<tr>
<td width='992px'><label>Je aandelen zijn ".$WaardePort." Dollar Waard.</label><input type='submit' name='back' value='Ga Terug naar overzicht'/></td>
</tr>
</table>
</center>
</body>
</html>";
echo "AANDELEN:".$Aandelen;
if($_GET){
if(isset($_GET['submit'])){
if(isset($_GET['1'])){
echo "Aandelen totaal:".$_GET['Totaal'];
echo "Hoeveel aandelen heb ik: ".$Aandelen;
if (!$_GET['Totaal'] > $Aandelen) { //ERROR IS HERE AND BELOW
echo "<center><p style='color:red; font-weight:bold;'>je hebt niet zoveel andelen!</p></center>";
}else{
$jekrijgt = $WorthNow * $_GET['Totaal'];
$Aandelen = $Aandelen - $_GET['Totaal'];
$Money = $jekrijgt + $Money;
echo "Je hebt ".$_GET['Totaal']." Aandelen Verkocht Voor: ".$Money;
echo $Aandelen;
}
}else{
echo "BUY";
}
}
}
?>
EXPLAINATION !
When echo the Variable aandelen before the If statements it Shows up perfectly fine but when i try to do some math to mae it when it doesnt have that much Shares(aandelen) then it will echo You dont have that much Shares. But it always echo That you have sold shares even if you dont have that much shares.
To see whats going wrong check http://wirechat.net16.net/xampp/5.php
!$_GET['Totall'] is processed before the > operator.
This means that it will only ever (numerically) be zero (if Totall is truthy), or one (if Totall is empty or zero).
The correct way to negate > is by using <= instead.
if( $_GET['Totaal'] <= $Aandelen)

Session not working as it has to be, auto session lost or content loss upon refresh page

I am new is PHP, doing my final year project in Student Result Online System.
In my system, I have an error in session, Once the user/student logs in using their user name and password, the dashboard displays his details properly.
But, as soon as the page reloads or you click to view other contents or just simply click on the student's tool bar within dashboard, the page loses all of its relevant contents and becomes idle or blank.
I want to prevent auto session destroy or loss while the user remains on the same page until he/she logs-out. any help would be grateful. Interesting thing is that, this codes works really well in Localhost (Wamp Server), but it loses its session in Online (cpanel).
My codes pages are:
login.php
<?php
include('dbcon.php');
if (isset($_POST['login'])){
session_start();
$student_no = $_POST['student_no'];
$password = $_POST['password'];
$query = "SELECT * FROM students WHERE student_no='$student_no' AND password='$password' and status = 'active' ";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
$row=mysql_fetch_array($result);
if( $num_row > 0 ) {
header('location:dasboard.php');
$_SESSION['id']=$row['student_id'];
}
elae{
header('location:access_denied.php');
}
}
?>
session.php
<?php
session_start();
if (!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) {
header("location: index.php");
exit();
}
$session_id=$_SESSION['id'];
?>
dasboard.php
<?php include('session.php'); ?>
<?php include('header.php'); ?>
<?php include('navbar.php'); ?>
<?php
$query=mysql_query("select * from students where student_id='$session_id'")or die(mysql_error());
$row=mysql_fetch_array($query);
$year_level = $row['year_level'];
$term = $row['term'];
$status = $row['student_status'];
$school_year = $row['year_level'];?>
<div class="container">
<div class="margin-top">
<div class="row">
<?php include('head.php'); ?>
<div class="span12">
<div class="grade">
<?php include('grade_option.php'); ?>
</div>
</div>
<div class="span2">
<?php include('user_sidebar.php'); ?>
</div>
<div class="span10">
<table cellpadding="0" cellspacing="0" border="0" class="table table-bordered" id="example">
<thead>
<tr>
<th width="100">Code</th>
<th width="300">Subject</th>
<th width="50">Units</th>
<th>Gen Ave.</th>
<th>Term</th>
<th>Year Level</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<?php $user_query=mysql_query("select * from grade where student_id = '$session_id' and school_year = '$year_level'
and semester = '$term'
")or die(mysql_error());
while($row=mysql_fetch_array($user_query)){
$id=$row['grade_id'];
$remarks = $row['remarks'];
$subject_id = $row['subject_id'];
$subject_query = mysql_query("select * from subject where subject_id = '$subject_id'")or die(mysql_error());
while($subject_row=mysql_fetch_array($subject_query)){
?>
<tr>
<td>
<?php echo $subject_row['code']; ?></td>
<td><?php echo $subject_row['title']; ?></td>
<td><?php echo $subject_row['unit']; ?></td>
<td><?php echo $row['gen_ave']; ?></td>
<td><?php echo $row['semester']; ?></td>
<td><?php echo $row['school_year']; ?></td>
<?php if ($remarks == 'Very Good'){ ?>
<td><span class="very_good"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'Excellent'){ ?>
<td><span class="Excellent"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'Satisfactory'){ ?>
<td><span class="sat"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'Fair'){ ?>
<td><span class="fair"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'Failed'){ ?>
<td><span class="failed"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'Incomplete'){ ?>
<td><span class="failed"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'Officially Dropped'){ ?>
<td><span class="drop"><?php echo $row['remarks']; ?></span></td>
<?php }else if($remarks == 'PASS'){ ?>
<td><span class="Excellent"><?php echo $row['remarks']; ?></span></td>
<?php }else if ($remarks == ''){ ?>
<td><?php echo $row['remarks']; ?></td>
<?php } ?>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
<?php include('units_table.php'); ?>
<?php include('gwa_table.php'); ?>
<?php include('cwa_table.php'); ?>
</div>
<?php include('grading_system.php') ?>
</div>
</div>
</div>
<?php include('footer.php') ?>
In your following code:
if( $num_row > 0 ) {
header('location:dasboard.php');
$_SESSION['id']=$row['student_id'];
}
You do
header('location:dasboard.php');
Before you set the session:
$_SESSION['id']=$row['student_id'];
Meaning you redirect first, and session is NEVER set.
By the way header.php, includes header.php?
And
elae{
header('location:access_denied.php');
}
Should be else of course.

Dropped by every time I click ctrl + F5

When I log into the site I come over to blabla.com/login/
HTML:
<?php
if(isset($_POST["login"]))
{
$logind = $mebe->logind();
}
?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>Brugernavn</td>
<td><input type="text" name="brugernavn" maxlength="300"></td>
</tr>
<tr>
<td>Adgangskode</td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="login" value="Log ind"></td>
</tr>
</table>
</form>
PHP: (login function is here:)
function logind()
{
if($_POST["brugernavn"] == "")
{
$error = 1;
}
if($_POST["pass"] == "")
{
$error = 1;
}
if($error != 1)
{
if ($stmt = $this->mysqli->prepare("SELECT id, brugernavn, rank, ranknavn FROM bruger WHERE brugernavn = ? AND adgangskode = ?"))
{
$stmt->bind_param('ss', $brugernavn, $adgangskode);
$brugernavn = $_POST["brugernavn"];
$adgangskode = sha1($_POST["pass"]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $brugernavn, $rank, $ranknavn);
$stmt->fetch();
$count = $stmt->num_rows;
$stmt->close();
if($count > 0)
{
$_SESSION["logged_in"] = true;
$_SESSION["id"] = $id;
$_SESSION["brugernavn"] = $brugernavn;
$_SESSION["rank"] = $rank;
$_SESSION["ranknavn"] = $ranknavn;
if($_SESSION["logged_in"] == true and $_SESSION["rank"] >= 1)
{
?>
<script language="javascript" type="text/javascript">
window.location.href = "/wall/";
</script>
<?php
}
else
{
echo "Fejl..";
}
}
else
{
?>
<div class="alert error fade in">
<p>Forkert Brugernavn / Password.</p>
<a class="close" data-dismiss="alert" href="#" aria-hidden="true"><i class="fa fa-times-circle"></i></a>
</div>
<?php
}
}
//fejl
else
{
echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
}
}
else
{
?>
<div class="alert error fade in">
<p>Forkert, Prøv igen!</p>
<a class="close" data-dismiss="alert" href="#" aria-hidden="true"><i class="fa fa-times-circle"></i></a>
</div>
<?php
}
}
If I use header('Location: /wall/'); then it will be just on the login page and did not show that one is log into the site in some way.
EIDT
it close site - only for users;
<?php
session_start();
include("phpFiler/fun.php");
$mebe = new mebe;
$db = $mebe->db_c();
error_reporting(E_ERROR);
if($_SESSION["logged_in"] == true)
{
?>
and open for alle users
<?php
session_start();
include("phpFiler/fun.php");
$mebe = new mebe;
$db = $mebe->db_c();
error_reporting(E_ERROR);
?>

Categories