Checking if file is larger than 1 MB - php

I would like to ask your help. I wrote a code which checks if all the fields are filled in and if the file is not larger than 1 MB. If everything is correct the file successfuly uploads to MySQL database. But if the file size is larger than 1 MB the code stops working. The error doesnt show up and all the fields become empty. Here`s the code (some of it is in Lithuanian, sorry):
<?php
error_reporting(E_ERROR);
session_start();
if (isset($_SESSION['login'])){
include 'config.php';
$username = $_SESSION['login'];
$result = mysqli_query($db,"SELECT * FROM users WHERE username='$username'");
$rws = mysqli_fetch_array($result);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$autorius = mysqli_real_escape_string($db,$_POST['autorius']);$pavadinimas = mysqli_real_escape_string($db,$_POST['pavadinimas']);$puslapiai = mysqli_real_escape_string($db,$_POST['puslapiai']);$tema = mysqli_real_escape_string($db,$_POST['tema']);$pmintis = mysqli_real_escape_string($db,$_POST['pmintis']);$pveikejai = mysqli_real_escape_string($db,$_POST['pveikejai']);$aveikejai = mysqli_real_escape_string($db,$_POST['aveikejai']);$epizodas = mysqli_real_escape_string($db,$_POST['epizodas']);$nuomone = mysqli_real_escape_string($db,$_POST['nuomone']);$apie = mysqli_real_escape_string($db,$_POST['apie']);$foto = mysqli_real_escape_string($db,$_POST['foto']);$user_id = $rws['id'];
if (!empty($autorius) && !empty($pavadinimas) && !empty($puslapiai) && !empty($tema) && !empty($pmintis) && !empty($pveikejai) && !empty($aveikejai) && !empty($epizodas) && !empty($nuomone) && !empty($apie) && isset($foto) && $_FILES['foto']['size'] > 0 && $_FILES['foto']['size'] < 1000001) {
$fileName = $_FILES['foto']['name'];$tmpName = $_FILES['foto']['tmp_name'];$fileSize = $_FILES['foto']['size'];$fileType = $_FILES['foto']['type'];
$fp = fopen($tmpName, 'r');
$foto = fread($fp, filesize($tmpName));
$foto = addslashes($foto);
fclose($fp);
$query = "INSERT INTO books (id_user, autorius, pavadinimas, puslapiai, tema, pmintis, pveikejai, aveikejai, epizodas, nuomone, apie, foto, name, type, size) ".
"VALUES ('$user_id', '$autorius', '$pavadinimas', '$puslapiai', '$tema', '$pmintis', '$pveikejai', '$aveikejai', '$epizodas', '$nuomone', '$apie', '$foto', '$fileName', '$fileType', '$fileSize')";
$result = mysqli_query($db,$query);
$success = "Knygos aprašymas įkeltas";
echo $_FILES['foto']['size'];
}
else if (empty($autorius) || empty($pavadinimas) || empty($puslapiai) || empty($tema) || empty($pmintis) || empty($pveikejai) || empty($aveikejai) || empty($epizodas) || empty($nuomone) || empty($apie)) {
$error = "Užpildykite visus laukelius!";
}
else if (empty($foto)){
$error = "Pasirinkite viršelio nuotrauką!";
}
else if ($_FILES['foto']['size'] > 1000001){
$error = "Viršelio nuotraukos dydid neturi viršyti 1 MB!";
}
}
?>
<?php include 'bin/includes/header.html'; ?>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Įkelti knygos aprašymą
<small>Ikelkite savo knygos aprašymą</small>
</h1>
<ol class="breadcrumb">
<li>Pagrindinis
</li>
<li class="active">Įkelti knygos aprašymą</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-md-8">
<form name="upload" id="upload" method="post" enctype="multipart/form-data">
<div class="control-group form-group">
<?php
if(isset($success)) {
echo '<label style="color: #44FF00;">';
echo $success;
echo '</label>';
}
else {
echo '<label style="color: #FF3700;">';
echo $error;
echo '</label>';
} ?>
<div class="controls">
<input type="text" class="form-control" name="autorius" maxlength="60" placeholder="Autorius" value="<?php if(!empty($_POST['autorius'])) echo $_POST['autorius'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="pavadinimas" maxlength="255" placeholder="Pavadinimas" value="<?php if(!empty($_POST['pavadinimas'])) echo $_POST['pavadinimas'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="puslapiai" placeholder="Puslapių skaičius" value="<?php if(!empty($_POST['puslapiai'])) echo $_POST['puslapiai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="pveikejai" maxlength="999" placeholder="Pagrindiniai veikėjai" value="<?php if(!empty($_POST['pveikejai'])) echo $_POST['pveikejai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<input type="text" class="form-control" name="aveikejai" maxlength="999" placeholder="Antraeiliai veikėjai" value="<?php if(!empty($_POST['aveikejai'])) echo $_POST['aveikejai'];?>">
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Tema" rows="2" class="form-control" name="tema" maxlength="999" style="resize:none"><?php if(!empty($_POST['tema'])) echo $_POST['tema'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Pagrindinė mintis" rows="2" class="form-control" name="pmintis" maxlength="999" style="resize:none"><?php if(!empty($_POST['pmintis'])) echo $_POST['pmintis'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Siužetas" rows="5" class="form-control" name="apie" maxlength="2999" style="resize:none"><?php if(!empty($_POST['apie'])) echo $_POST['apie'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Įsimintiniausias epizodas" rows="3" class="form-control" name="epizodas" maxlength="2999" style="resize:none"><?php if(!empty($_POST['epizodas'])) echo $_POST['epizodas'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<textarea placeholder="Nuomonė apie knygą" rows="3" class="form-control" name="nuomone" maxlength="999" style="resize:none"><?php if(!empty($_POST['nuomone'])) echo $_POST['nuomone'];?></textarea>
<p class="help-block"></p>
</div>
<div class="controls">
<label>Įkelti viršelį (max 1MB)</label>
<input name="foto" type="file" id="foto">
<p class="help-block"></p>
</div>
<button type="submit" class="btn btn-primary">Įkelti</button>
</div>
</form>
</div>
</div>
<?php include 'bin/includes/footer.html'; ?>
<?php } else {
header("location: index.php");
}
Thanks for your help!

You should use this to get the file size:
$size = filesize($_FILES['foto']['tmp_name']);
This returns the filesize in byte. One MB are 1048576 bytes. You should check for the function not returning false.
In general: You should use exceptions for this purpose, it is much simplier to check for a condition and then check again. If you just want to use if-else-statements, you should rearrange it (check for errors first and then upload the thing in the else-case).
Why are you not saving the files in filesystem? This is a lot easier...

Related

Problem with showing image from the database

I need a help regarding my source code on uploading and displaying the profile picture of my users on their profile.
The upload went smooth, but the display is not. The display of the user's picture is only shown in picture icon and not the real picture. Like this:
the file where the picture is stored is here
and here is my source code
edit-profile.php
<div class="author">
<a href="#">
<img class="avatar border-gray" src="../uploads/candidate/<?php echo $row['photo']; ?>" alt="..."/>
<h4 class="title"><?php echo $_SESSION['name']; ?><br /> </h4>
</a>
</div>
EDIT:
I'll provide the full source code for both userindex.php and edit-profile.php here so maybe any of you can point me where I do wrong.
userindex.php
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="header">
<h4 class="title">Edit Profile</h4>
</div>
<div class="content">
<form action="update-profile.php" method="post" enctype="multipart/form-data">
<?php
//Sql to get logged in user details.
$sql = "SELECT * FROM users WHERE id_user='$_SESSION[id_user]'";
$result = $conn->query($sql);
//If user exists then show his details.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="user_name" type="text" id="user_name"> Full Name</label>
<input name="user_name" class="form-control" type="text" maxlength="100" value="<?php echo $row['user_name'] ?>" required=""/>
</div>
</div>
</div>
<!-- section 1-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ic_no" type="text" id="ic_no" maxlength="12">NRIC</label>
<input name="ic_no"type="text" class="form-control" value="<?php echo $row['ic_no'] ?>" readonly>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="nationality" type="text" id="nationality">Nationality</label>
<input name="nationality" class="form-control" type="text" id="nationality" value="<?php echo $row['nationality'] ?>"/>
</div>
</div>
</div>
<!--first section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="gender" type="text" id="gender">Gender</label>
<input name="gender" class="form-control" type="text" id="gender" value="<?php echo $row['gender'] ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="race" type="text" id="race">Race</label>
<input type="text" class="form-control" name="race" id="race" value="<?php echo $row['race'] ?>"/>
</div>
</div>
</div>
<!-- second section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="contactno" type="text" id="contact_no">Contact No</label>
<input name="contactno" class="form-control" type="text" id="contact_no" value="<?php echo $row['contactno'] ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="email" type="text" id="email">Email</label>
<input type="text" class="form-control" type="text" id="email" value="<?php echo $row['email'] ?>" readonly>
</div>
</div>
</div>
<!--other add -->
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="address" type="text" id="address">Current Address</label>
<textarea id="address" name="address" class="form-control" rows="5" placeholder="Address"><?php echo $row['address']; ?></textarea>
</div>
</div>
</div>
<!-- third section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="highest_qualification" type="text" id="highest_qualification">Highest Qualification</label>
<input name="highest_qualification" class="form-control" type="text" maxlength="100" value="<?php echo $row['highest_qualification'] ?>"/>
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="university" type="text" id="university">University</label>
<input name="university" class="form-control" type="text" maxlength="100" value="<?php echo $row['university'] ?>"/>
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="major" type="text" id="major">Major</label>
<input name="major" class="form-control" type="text" maxlength="100" value="<?php echo $row['major'] ?>"/>
</div>
</div>
</div>
<!-- another section-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="current_position" type="text" id="current_position">Current Position</label>
<input type="text" class="form-control" name="current_position" value="<?php echo $row['current_position'] ?>"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="position_appled" type="text" id="position_applied">Position Applied</label>
<input type="text" class="form-control" name="position_applied" value="<?php echo $row['position_applied'] ?>">
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="current_monthly_salary" type="text" id="current_monthly_salary">Current Monthly Salary</label>
<input type="text" class="form-control" name="current_position" value="<?php echo $row['current_monthly_salary'] ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="expected_monthly_salary" type="text" id="expected_monthly_salary">Expected Monthly Salary</label>
<input type="text" class="form-control" name="position_applied" value="<?php echo $row['expected_monthly_salary'] ?>">
</div>
</div>
</div>
<!--another section -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="prefered_working_location" type="text" id="prefered_working_location">Prefered Working Location</label>
<input name="prefered_working_location" class="form-control" type="text" maxlength="100" value="<?php echo $row['prefered_working_location'] ?>" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="avaibility" type="text" id="avaibility">Avaibility</label>
<select name = "avaibility" class="form-control " type="text" id="avaibility" value="<?php echo $row['avaibility'] ?>">
<option value="">-- select one --</option>
<option value="Immediately">Immediately</option>
<option value="One Month">One Month</option>
<option value="Two Month">Two Month</option>
<option value="Three Month">Three Month</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="language" type="text" id="language">Language Proficiency</label><br />
&nbsp&nbsp&nbsp<p>Proficiency level 0-poor; 10-excellent</p>
<table border="2" bordercolor="gray" align="center">
<tr>
<td>
<label for="malay" type="text" id="malay" placeholder="Malay" style="color:black; width:200px"><b>Malay</b></label><br />
</td>
<td>
<input name="malay" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['malay'] ?>"/>
</td>
</tr>
<tr>
<td>
<label for="english" type="text" id="english" placeholder="English" style="color:black; width:200px"><b>English</b></label><br />
</td>
<td>
<input name="english" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['english'] ?>"/>
</td>
</tr>
<tr>
<td>
<label for="mandarin" type="text" id="mandarin" placeholder="Mandarin" style="color:black; width:200px"><b>Mandarin</b></label><br />
</td>
<td>
<input name="mandarin" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['mandarin'] ?>"/>
</td>
</tr>
<tr>
<td>
<label for="other" type="text" id="other" placeholder="Other" style="color:black; width:200px"><b>Others</b></label><br />
</td>
<td>
<input name="other" type="text" class="form-control" maxlength="100" style="width: 200px" value="<?php echo $row['other'] ?>"/>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="aboutme" type="text" id="aboutme"><b>About Me</b></label><br />
<p>Summarize your employement history (Not more than 100 words)</p>
<textarea class="form-control" rows="6" id="aboutme" name="aboutme" maxlength="400" style="width: 560px"value="<?php echo $row['aboutme'] ?>"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label style="color:black;">Latest passport photo</label>
<input class="btn btn-danger" type="file" name="image" id="profile-img" /><br>
<img src="../uploads/candidate/<?php echo $row['photo']; ?>" id="profile-img-tag" width="200px" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label style="color:black;">File format PDF and doc only!</label>
<input type="file" name="resume" class="btn btn-danger" />
</div>
</div>
</div>
<button type="submit" class="btn btn-info btn-fill pull-right">Update Profile</button>
<div class="clearfix"></div>
<?php
}
}
?>
</form>
<?php if(isset($_SESSION['uploadError'])) { ?>
<div class="row">
<div class="col-md-12 text-center">
<?php echo $_SESSION['uploadError']; ?>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<!--second part of picture and resume -->
<div class="col-md-4">
<div class="card card-user">
<div class="image">
<img src="https://ununsplash.imgix.net/photo-1431578500526-4d9613015464?fit=crop&fm=jpg&h=300&q=75&w=400" alt="..."/>
</div>
<div class="content">
<div class="author">
<a href="#">
<img class="avatar border-gray" src="../uploads/candidate/<?php echo $row['photo']; ?>" alt="..."/>
<h4 class="title"><?php echo $_SESSION['name']; ?><br /> </h4>
</a>
</div>
</div>
<hr>
<div class="text-center">
<button href="#" class="btn btn-simple"><i class="fa fa-facebook-square"></i></button>
<button href="#" class="btn btn-simple"><i class="fa fa-twitter"></i></button>
<button href="#" class="btn btn-simple"><i class="fa fa-google-plus-square"></i></button>
</div>
</div>
</div>
</div>
</div>
and this is update-profile.php
<?php
//To Handle Session Variables on This Page
session_start();
if(empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("../db.php");
//if user Actually clicked update profile button
if(isset($_POST)) {
//Escape Special Characters
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$uploadOk = true;
if(isset($_FILES)) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf") {
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
header("Location: edit-profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$sql= "UPDATE users set user_name='$user_name', ic_no='$ic_no', gender='$gender', nationality='$nationality', race='$race', email='$email', contactno='$contactno', highest_qualification='$$highest_qualification',
university='$university', major='$major', current_position='$current_position', position_applied='$position_applied', current_monthly_salary='$current_monthly_salary',
expected_monthly_salary='$expected_monthly_salary', prefered_working_location='$prefered_working_location', avaibility='$avaibility', malay='$malay', english='$english',
mandarin='$mandarin', other='$other', photo='$file', resume='$file', aboutme='$aboutme'";
if($uploadOk == true) {
$sql .= ", resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE) {
$_SESSION['user_name'] = $user_name;
//If data Updated successfully then redirect to dashboard
header("Location: index.php");
exit();
} else {
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit-profile.php");
exit();
}};
Check your update-profile.php
There's confusion happened there because you put the same 'file name' for both your file type for image and resume. You should do it like this instead
<?php
//To Handle Session Variables on This Page
session_start();
if(empty($_SESSION['id_user'])) {
header("Location: ../index.php");
exit();
}
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("../db.php");
//if user Actually clicked update profile button
if(isset($_POST)) {
//Escape Special Characters
if(isset($_POST)) {
$user_name = mysqli_real_escape_string($conn, $_POST['user_name']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$nationality = mysqli_real_escape_string($conn, $_POST['nationality']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$race = mysqli_real_escape_string($conn, $_POST['race']);
$ic_no = mysqli_real_escape_string($conn, $_POST['ic_no']);
$contactno = mysqli_real_escape_string($conn, $_POST['contactno']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$highest_qualification = mysqli_real_escape_string($conn, $_POST['highest_qualification']);
$university = mysqli_real_escape_string($conn, $_POST['university']);
$major = mysqli_real_escape_string($conn, $_POST['major']);
$current_position = mysqli_real_escape_string($conn, $_POST['current_position']);
$position_applied = mysqli_real_escape_string($conn, $_POST['position_applied']);
$current_monthly_salary = mysqli_real_escape_string($conn, $_POST['current_monthly_salary']);
$expected_monthly_salary = mysqli_real_escape_string($conn, $_POST['expected_monthly_salary']);
$prefered_working_location = mysqli_real_escape_string($conn, $_POST['prefered_working_location']);
$avaibility = mysqli_real_escape_string($conn, $_POST['avaibility']);
$malay = mysqli_real_escape_string($conn, $_POST['malay']);
$english = mysqli_real_escape_string($conn, $_POST['english']);
$mandarin = mysqli_real_escape_string($conn, $_POST['mandarin']);
$other = mysqli_real_escape_string($conn, $_POST['other']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$uploadOk = true;
if(isset($_FILES)) {
$folder_dir = "../uploads/resume/";
$base = basename($_FILES['resume']['name']);
$resumeFileType = pathinfo($base, PATHINFO_EXTENSION);
//notice that I changed your file name from $file to $file1
$file1 = uniqid() . "." . $resumeFileType;
$filename = $folder_dir .$file1;
if(file_exists($_FILES['resume']['tmp_name'])) {
if($resumeFileType == "pdf") {
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
header("Location: edit-profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//image update edit
if(is_uploaded_file ( $_FILES['image']['tmp_name'] )) {
$folder_dir = "../uploads/logo/";
$base = basename($_FILES['image']['name']);
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
$file = uniqid() . "." . $imageFileType;
$filename = $folder_dir .$file;
if(file_exists($_FILES['image']['tmp_name'])) {
if($imageFileType == "jpg" || $imageFileType == "png") {
if($_FILES['image']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);
} else {
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
header("Location: edit-profile.php");
exit();
}
} else {
$_SESSION['uploadError'] = "Wrong Format. Only jpg & png Allowed";
header("Location: edit-profile.php");
exit();
}
}
} else {
$uploadOk = false;
}
//Update User Details Query
$sql= "UPDATE users set user_name='$user_name', ic_no='$ic_no', gender='$gender', nationality='$nationality', race='$race', email='$email', contactno='$contactno', highest_qualification='$$highest_qualification',
university='$university', major='$major', current_position='$current_position', position_applied='$position_applied', current_monthly_salary='$current_monthly_salary',
expected_monthly_salary='$expected_monthly_salary', prefered_working_location='$prefered_working_location', avaibility='$avaibility', malay='$malay', english='$english',
mandarin='$mandarin', other='$other', logo='$file', resume='$file1', aboutme='$aboutme'";
if($uploadOk == true) {
$sql .= ", resume='$file'";
}
$sql .= " WHERE id_user='$_SESSION[id_user]'";
if($conn->query($sql) === TRUE) {
$_SESSION['user_name'] = $user_name;
//If data Updated successfully then redirect to dashboard
header("Location: edit-profile.php");
exit();
} else {
echo "Error ". $sql . "<br>" . $conn->error;
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to dashboard page if they didn't click update button
header("Location: edit-profile.php");
exit();
}};
I have tried your previous code, that cause the image to be stored as pdf and that's why when you call for the image to be displayed, it's appears as broken image icon instead. I hope this can help you well and good luck!
Try this code
<img src="uploads/candidate/.'<?php echo row['photo']; ?>'"/>
You need to make sure the $row value actually got value.
try this and see if you got any result:
die(var_dump("../uploads/candidate/".$row['photo'] ));
You will get the path the code is refering to, if that doesn't give a result check your query again ( check if the row got value )
You can do this introducing an external php file e.g get.php, then request the photo from this get.php.
See sample of both files below.
display.php file
<?php
$id = row['id'];
<img class="avatar" src=get.php?id=$id alt="profile photo" />
?>
get.php file
<?php
// make connections with database here
$id = $_REQUEST['id'];
$image = ("SELECT * FROM table WHERE id = '$id'");
$image = $image->fetch_assoc();
$image = $image['photo'];
echo $image;
?>
You have problem in your $_SESSION array userindex.php file. You have missed the quites ' for session key
$sql = "SELECT * FROM users WHERE id_user='$_SESSION[id_user]'";
So assign it to a variable first and then put that variable inside sql query
$id_user = $_SESSION['id_user'];// single quotes for session key
$sql = "SELECT * FROM users WHERE id_user='$id_user'";
Note:
Your code is open to sql injections. Try use PDO or prepared statements

For loop showing only the final result

I have the following PHP query:
<?php
$row='';
$access = 0;
$user = (isset($_POST['nume']) && !empty($_POST['nume'])) ? $_POST['nume'] : "" ;
$email = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : "" ;
$telefon = (isset($_POST['telefon']) && !empty($_POST['telefon'])) ? $_POST['telefon'] : "" ;
$cnp = (isset($_POST['cnp']) && !empty($_POST['cnp'])) ? $_POST['cnp'] : "" ;
$serieci = (isset($_POST['serieci']) && !empty($_POST['serieci'])) ? $_POST['serieci'] : "" ;
$mesaj = (isset($_POST['mesaj']) && !empty($_POST['mesaj'])) ? $_POST['mesaj'] : "" ;
$email_status=1;
$db = pg_connect("host=local port=5432 dbname=login_robinson user=robinson password=123");
$query = "INSERT INTO tcheckin(nume,email,telefon,cnp,serieci,mesaj) VALUES ('$user','$email','$telefon','$cnp','$serieci','$mesaj')";
$result = pg_query($query);
$test=$_SESSION[PRE.'nume'];
$test1=$_SESSION[PRE.'uid'];
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,700,900|Rubik:300,400,700" rel="stylesheet">
<title>Efectueaza check-in</title>
<?php
include('include/links.php');
include('include/scripts.php');
?>
</head>
<?php
$i=1;
$conn = pg_connect("host=local port=5432 dbname=login_robinson user=robinson password=123");
$test1=$_SESSION[PRE.'uid'];
$result = pg_query($conn, "SELECT nume FROM tregister WHERE id = '$test1'");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$row = pg_fetch_row($result);
$result1 = pg_query($conn, "SELECT nr_camere FROM tregister WHERE nume = '$user'");
if (!$result1) {
echo "An error occurred.\n";
exit;
}
$camere = pg_fetch_row($result1);
echo $row[0];
for($i=1; $i<$camere[0]; $i++){
if(isset($_POST['submit'])){
echo "<script>
alert('Check-in efectuat cu success! Daca ai rezervat mai multe camere te rog sa completezi si check-in-ul pentru celelalte camere.');
window.location.href='acasa';
</script>";
echo "<script>
alert('S-a produs o eroare! Te rog mai verifica odata formularul!');
</script>";
}
}
?>
<body style="display: block !important;" ng-cloak="" ng-class="{ 'layout-fixed' : app.layout.isFixed, 'layout-boxed' : app.layout.isBoxed, 'layout-dock' : app.layout.isDocked, 'layout-material': app.layout.isMaterial, 'aside-offscreen' : app.sidebar.isOffscreen, 'aside-mini' : app.sidebar.isMini, 'aside-right' : app.sidebar.isRight, 'footer-hidden': app.footer.hidden, 'in-app': !$state.includes('page')}">
<div class="animated fadeOutZoom">
<div class="container container-sm animated fadeInDown">
<div class="app-view-header">Bine ai venit, <?php echo $row[0]; ?>!</div>
<div class="center-block mt-xl">
<div class="panel">
<div class="panel-body">
<p class="pv text-bold">Check-in pentru camera cu numarul <?php echo $i; ?></p>
<form action="#" method="post">
<div class="row">
<div class="col-md-12 form-group">
<label for="nume">Nume</label>
<input type="text" id="text " value=" <?php echo $row[0]; ?>" class="form-control " name="nume" disabled="disabled">
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="telefon">Telefon</label>
<input type="phone" id="telefon " class="form-control " name="telefon" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="email">Email</label>
<input type="email" id="email" class="form-control " name="email" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="cnp">CNP</label>
<input type="text" id="text " class="form-control "name="cnp" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="serie">Serie de buletin</label>
<input type="text" id="text " class="form-control " name="serieci" required>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="message">Scrie un mesaj *Optional</label>
<textarea name="mesaj" id="message" class="form-control " cols="5" rows="4"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group">
<input type="submit" value="Rezerva acum" class="btn btn-primary" name="submit">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<script>
$('#arrival_date, #departure_date').datepicker({format: 'dd/mm/yyyy'});
</script>
</body>
</html>
<?php
ob_end_flush();
?>
What I want to do it's to see a page for a number of times. For example, if a user selected 4 rooms, I need make the check-in process 4 times, once for each room, I tried with a for loop but it's showing only the final result..what can I do? It's a little bit weird, I tried also with a while but still doesn't work..

how to validate html form in another php file and get back errors to the html form file

I've created a signup.php file for html form and signup_form_handler.php for validate the html form. Before create a separate file for validation I tried to validate the html form in the same file (signup.php) and I succeeded. After I separate the validation part into another file I have this problem. How can i get back the validation errors from signup_form_handler.php to the html form file (signup.php) .
signup.php
<div class="container-fluid calbox col-md-4" style="margin-right: 10px;margin-bottom: 10px;">
<h2 style="text-align: center;color:#0275d8;">Sign Up Form</h2>
<form method="POST" action="signup_form_handler.php">
<div class="form-group">
<label style="padding-top: 10px;" class="col-form-label">Name</label>
<input type="text" class="form-control" placeholder="Type your name here" value="<?php if(isset($_POST['name'])){echo $_POST['name'];}?>" name="name" id="name">
<div class="errBox" style="padding-top: 5px;">
<?php echo $nameErr;?>
</div>
</div>
<div class="form-group">
<label class="col-form-label">Email</label>
<input type="email" class="form-control" placeholder="Type your email here" value="<?php if(isset($_POST['email'])){echo $_POST['email'];}?>" name="email" id="email">
<div class="errBox" style="padding-top: 5px;">
<?php echo $emailErr;?>
</div>
</div>
<div class="form-group">
<label class="col-form-label">City</label>
<select class="form-control" id="city" name="city[]">
<option value="Kandy">Kandy</option>
<option value="Colombo">Colombo</option>
<option value="Galle">Galle</option>
</select>
</div>
<fieldset class="form-group row">
<label class="col-form-label col-xs-4">Gender</label>
<div class="col-xs-7 form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="gender" id="genMale" value="Male" checked>
Male
</label>
<label class="form-check-label">
<input type="radio" class="form-check-input" name="gender" id="genFemale" value="Female">
Female
</label>
</div>
</fieldset>
<div class="form-group">
<label class="col-form-label col-xs-4">Interested Areas</label>
<div class="col-xs-7 form-check">
<label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0 offset-xs-1">
<input type="checkbox" name="check[]" id="web" class="custom-control-input" value="Web Design">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Web Design</span>
</label>
<label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0">
<input type="checkbox" name="check[]" id="gd" class="custom-control-input" value="Graphic Design">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Graphic Design</span>
</label>
<label class="custom-control custom-checkbox mb-2 mr-sm-2 mb-sm-0">
<input type="checkbox" name="check[]" id="se" class="custom-control-input" value="Software Engineering">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Software Engineering</span>
</label>
</div>
</div>
<div class="errBox" style="padding-top: 5px;">
<?php echo $checkErr;?>
</div>
<div class="form-group">
<label class="col-form-label">Phone Number</label>
<input type="tel" class="form-control" placeholder="Type your phone number here" value="<?php if(isset($_POST['phone'])){echo $_POST['phone'];}?>" name="phone" id="phone">
</div>
<div class="form-group">
<label class="col-form-label">Password</label>
<input type="password" class="form-control" placeholder="Type a password here" name="pass" id="pass">
<div class="errBox" style="padding-top: 5px;">
<?php echo $passErr;?>
</div>
</div>
<div class="form-group">
<label class="col-form-label">Confirm Password</label>
<input type="password" class="form-control" placeholder="Retype the password here" name="cpass" id="cpass">
<div class="errBox" style="padding-top: 5px;">
<?php echo $cpassErr;?>
</div>
</div>
<div class="form-group row offset-sm-8" style="padding-left: 10px;">
<button type="submit" class="btn btn-outline-primary" name="btn" value="signup" id="signupbtn">Register</button>
</div>
</form>
</div>
signup_form_handler.php
<?php
$nameErr = $emailErr = $checkErr = $passErr = $cpassErr = "";
$name = $email = $pass = $check = $checklist = $value = $gender = $city = $phone = $dateTime = "";
if (isset($_POST['btn'])) {
if (empty($_POST["name"])) {
$nameErr = '<div class="alert alert-danger">Name is required !</div>';
} else{
$name = test_validate($_POST['name']);
}
if (empty($_POST["email"])) {
$emailErr = '<div class="alert alert-danger">Email is required !</div>';
}else{
$email = test_validate($_POST['email']);
}
if (isset($_POST['phone'])) {
$phone = test_validate($_POST['phone']);
}
if (empty($_POST["pass"])) {
$passErr = '<div class="alert alert-danger">Password is required !</div>';
} elseif (!empty($_POST["pass"]) < 6) {
$passErr = '<div class="alert alert-danger">Minimum 6 characters required !</div>';
}
if (empty($_POST["cpass"])) {
$cpassErr = '<div class="alert alert-danger">Confirm password is required !</div>';
} elseif ($_POST["pass"] != $_POST["cpass"]) {
$cpassErr = '<div class="alert alert-danger">Password fields do not match !</div>';
}else{
$pass = test_validate($_POST['pass']);
}
if (empty($_POST['check'])) {
$checkErr = '<div class="alert alert-danger">You should at least select 1 area that you are interested !</div>';
}
if (isset($_POST['gender'])) {
$gender = test_validate($_POST['gender']);
}
if (isset($_POST['city'])) {
foreach ($_POST['city'] as $citylist) {
$city = $citylist;
}
}
date_default_timezone_set("Asia/Colombo");
$dateTime = date("Y-m-d h:i:s a");
}
function test_validate($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
in signup_form_handler.php
SESSION_START();
SESSION['data'] = $data;
in signup.php
SESSION_START();
print SESSION['data'];
Well you can save the error message in a session variable. In case of error you can redirect the user back to the signup.php page. Try following code in signup_form_handler.php. It should go at the bottom of the first If clause
$error_message = "";
if ($nameErr != "") $error_message = $nameErr;
if ($emailErr != "") $error_message = $emailErr;
if ($checkErr != "") $error_message = $checkErr;
if ($passErr != "") $error_message = $passErr;
if ($cpassErr != "") $error_message = $cpassErr;
if ($error_message != "") {
$_SESSION['error_message'] = $error_message;
header("Location: " . $error_message);
exit;
}
Also add the line : session_start(); at the top of the signup_form_handler.php and signup.php.
In signup.php file, you have to add the lines:
if (isset($_SESSION['error_message']) && $_SESSION['error_message'] != "") {
echo $_SESSION['error_message'];
unset($_SESSION['error_message']);
}

using session data in PHP

I'm having a difficult time understanding the $_SESSION function in PHP. I'm building a multipage form and when it was a single form, everything worked as expected. Now I'm trying to figure out $_SESSION so that data from page1 carries to page2 for the submit.
So here is page 1:
<?php require_once("../tim/includes/validation_functions.php");
include("../tim/includes/session.php");
require_once("../tim/includes/variables.php");
include ("/testing/tim/obervation-upload.php");
?>
<?php
session_start(); // Session starts here.
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
<script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>
<title>Assessment Application</title>
</head>
<body>
<div>
<h2>3SP Assessment</h2>
<span id="error">
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
</span>
<form class="form-horizontal" role="form" name="assessment" action="application_form.php" method="post">
<div class="form-group" style="margin-bottom:10px;">
<label for="company_name" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Company name:</strong></label>
<div class="col-md-2"> <input type="text" id="company_name" name="company_name" class="form-control" required> </div>
<div class="clearfix"></div>
<label for="date" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Date:</strong></label>
<div class="col-md-2"><input type="date" name="date" id="date" class="form-control" required> </div>
<div class="clearfix"></div>
<label for="rsm" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Regional Sales Manager:</strong></label>
<div class="col-md-2"> <input type="text" name="rsm" id="rsm" class="form-control" required></div>
<div class="clearfix"></div>
<label for="agents" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Agents:</strong> </label>
<div class="col-md-2"> <input type="text" name="agents" id="agents" class="form-control" required></div>
<div class="clearfix"></div>
<label for="distributor" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Distributor:</strong> </label>
<div class="col-md-2"><input type="text" name="distributor" class="form-control" required></div>
</div>
<p style="margin-left:5px;"><input class="btn btn-danger" type="reset">
<input style="margin-left:10px;" class="btn btn-success" type="submit" value="Next" /></p>
</form>
<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>
</body>
</html>
page 2:
<?php require_once("../tim/includes/validation_functions.php");
include("../tim/includes/session.php");
require_once("../tim/includes/variables.php");
include ("/testing/tim/obervation-upload.php");
?>
<?php
session_start();
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
<link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
<script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>
<title>Assessment Application</title>
</head>
<body>
<div>
<h2>3SP Assessment</h2>
<form name="assessment" action="create_new_record.php" method="POST" enctype="multipart/form-data">
<p>Department name: <input type="text" name="department_name" /> </p>
<p>Participant name: <input type="text" name="participant_name" /> </p>
<p>Activity performed: <textarea cols="25" rows="3" name="activity" ></textarea> </p>
<p>Location: <input type="text" name="location" /> </p>
<p>Conditon: <select class="form-control" name="condition" style="width:20%;">
<option value="dry" id="dry">Dry</option>
<option value="heavy_oil" id="heavy_oil">Heavy Oil/Grease</option>
<option value="light_oil" id="light_oil">Light Oil</option>
<option value="sandy" id="sandy">Sandy/Grit</option>
<option value="wet" id="wet">Slightly Wet</option>
</select></p>
<div class="well">
<p>Avg Number of Recordable Injuries:
<input type="number" name="injuries" />
<select name="injury_time_frame">
<option value="last month">Last month</option>
<option value="last 6 months">Last 6 months</option>
<option value="last 12 months">Last 12 months</option>
</select>
</p>
<h4>Based on the number of Recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
<div class="form-group row">
<div class="col-md-3 col-sm-4"><input class="form-control" id="cuts" name="cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="burns" name="burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="infection" name="infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="dermatitis" name="dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
<div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="puncture" name="puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="sprain" name="sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" id="impact" name="impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" /> </div>
</div>
</div>
<p id="rec_injuries"></p>
<script>
function percentageTest() {
// Get the value of the input fields
a = document.getElementById("cuts").value;
b = document.getElementById("burns").value;
c = document.getElementById("infection").value;
d = document.getElementById("dermatitis").value;
e = document.getElementById("puncture").value;
f = document.getElementById("sprain").value;
g = document.getElementById("impact").value;
var x = (a + b + c + d + e + f + g);
// grouping together and doing the math
if (x = !100) {
text = "The total percentage must equal 100%";
} else {
text = "Congrats the total = 100%";
}
document.getElementById("rec_injuries").innerHTML = text;
}
</script>
</div>
<div class="well">
<p>Avg Number of Non-recordable Injuries: <input type="number" name="non_rec_injuries" />
<select name="non_rec_injury_timeframe">
<option value="last month">Last month</option>
<option value="last 6 months">Last 6 months</option>
<option value="last 12 months">Last 12 months</option>
</select>
</p>
<h4>Based on the number of Non-recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
<div class="form-group row">
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
<div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
<div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" />
</div>
</div>
</div>
</div>
<p>Estimated Cost of Productivity (Downtime)/minute: $ <input type="number" name="cost_of_productivity" /> </p>
<p>Percent of leakage related to uncontrolled dispensing: <input type="number" min="0" max="100" name="leakage" /> % </p>
<p>Which competitor is the participant using? <input type="text" name="competitor" /></p>
<p>Usage Rate per 12 months (pairs): <input type="number" min="0" name="usage_rate" /></p>
<p>Estimated cost per pair: $ <input type="number" min="0" name="cost_per_pair" /></p>
<br />
<div class="container" style="margin-left:0px; padding-left:0px;">
<div class="form-group row" style="margin-left:0px;">
<div class="col-md-3 col-sm-6">
<label for="safetyHazard1_notes"><strong>Safety observation 1:</strong></label> <input type="file" name="safetyHazard1" id="safetyHazard1" value=""><br /> <br />
<textarea cols="25" rows="3" id="safetyHazard1_notes" name="safetyHazard1_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="safetyHazard2_notes"><strong>Safety observation 2:</strong></label> <input type="file" name="safetyHazard2" id="safetyHazard2" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="safetyHazard3_notes"><strong>Safety observation 3:</strong></label> <input type="file" name="safetyHazard3" id="safetyHazard3" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>
<div class="col-md-3 col-sm-6">
<label for="other_notes"><strong>Other observations:</strong></label> <input type="file" name="otherObservation" id="otherObservation" value=""><br /><br />
<textarea cols="25" rows="3" id="other_notes" name="other_notes" placeholder="Enter notes for this observation" ></textarea> </div>
</div></div>
<br />
<p style="margin-left:5px;"><input class="btn btn-danger" type="reset">
<input style="margin-left:10px;" class="btn btn-primary" type="button" name="new_location" value="Add Additional Location" />
<input style="margin-left:10px;" class="btn btn-success" type="submit" name="submit" value="Create New Assessment" /></p>
</form>
<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>
</body>
</html>
And finally the processing page:
<?php
require_once("../tim/includes/session.php");
require_once ("../tim/includes/functions.php");
require_once("../tim/includes/validation_functions.php");
?>
<?php
if(isset($_POST["submit"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/testing/tim/uploads/';
$target_file = $target_dir . basename($_FILES["safetyHazard1"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["safetyHazard1"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["safetyHazard1"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["safetyHazard1"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["safetyHazard1"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']);
// Process the form
$department_name = ($_POST['department_name']);
$participant_name = ($_POST['participant_name']);
$activity = ($_POST['activity']);
$location = ($_POST['location']);
$rec_injuries = ($_POST['injuries']);
$rec_injuries_timeframe = ($_POST['injury_time_frame']);
$non_rec_injuries = ($_POST['non_rec_injuries']);
$non_rec_injuries_timeframe = ($_POST['non_rec_injury_timeframe']);
$rec_cuts = ($_POST['cuts']);
$rec_burns = ($_POST['burns']);
$rec_infection = ($_POST['infection']);
$rec_dermatitis = ($_POST['dermatitis']);
$rec_puncture = ($_POST['puncture']);
$rec_sprain = ($_POST['sprain']);
$rec_impact = ($_POST['impact']);
$non_rec_cuts = ($_POST['non_rec_cuts']);
$non_rec_burns = ($_POST['non_rec_burns']);
$non_rec_infection = ($_POST['non_rec_infection']);
$non_rec_dermatitis = ($_POST['non_rec_dermatitis']);
$non_rec_puncture = ($_POST['non_rec_puncture']);
$non_rec_sprain = ($_POST['non_rec_sprain']);
$non_rec_impact = ($_POST['non_rec_impact']);
$cost_of_productivity = ($_POST['cost_of_productivity']);
$leakage = (($_POST['leakage']) / 100);
$usage_rate = ($_POST['usage_rate']);
$cost_per_pair = ($_POST['cost_per_pair']);
$condition = ($_POST['condition']);
$safety_hazard_1 = basename( $_FILES["safetyHazard1"]["name"]);
$safety_hazard_2 = ($_POST['safetyHazard2']);
$safety_hazard_3 = ($_POST['safetyHazard3']);
$other_observation = ($_POST['otherObservation']);
$safetyHazard1_notes = ($_POST['safetyHazard1_notes']);
$safetyHazard2_notes = ($_POST['safetyHazard2_notes']);
$safetyHazard3_notes = ($_POST['safetyHazard3_notes']);
$otherNotes = ($_POST['otherNotes']);
$competitor = ($_POST['competitor']);
$company_name = ($_POST['company_name']);
$date = ($_POST['date']);
$rsm = ($_POST['rsm']);
$agents = ($_POST['agents']);
$distributor = ($_POST['distributor']);
print "distributor: " . $distributor;
exit;
// Perform first database insert
$query1 = "INSERT INTO location_info (";
$query1 .= "`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `safety_hazard_1`, `safety_hazard_2`, `safety_hazard_3`, `other_observation`,`safetyHazard1_notes`, `safetyHazard2_notes`, `safetyHazard3_notes`, `otherNotes`";
$query1 .= ") VALUES (";
$query1 .= " '{$department_name}', '{$participant_name}', '{$activity}', '{$location}', '{$rec_injuries}', '{$rec_injuries_timeframe}',
'{$non_rec_injuries}', '{$non_rec_injuries_timeframe}', '{$competitor}', '{$cost_per_pair}', '{$usage_rate}', '{$leakage}', '{$cost_of_productivity}', '{$non_rec_impact}', '{$non_rec_sprain}', '{$non_rec_puncture}', '{$non_rec_dermatitis}', '{$non_rec_infection}', '{$non_rec_burns}', '{$non_rec_cuts}', '{$rec_impact}', '{$rec_sprain}', '{$rec_puncture}', '{$rec_dermatitis}', '{$rec_infection}', '{$rec_burns}', '{$rec_cuts}', '{$condition}', '{$safety_hazard_1}', '{$safety_hazard_2}', '{$safety_hazard_3}', '{$other_observation}','{$safetyHazard1_notes}', '{$safetyHazard2_notes}', '{$safetyHazard3_notes}', '{$otherNotes}'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Assessment created.";
redirect_to("results.php");
} else {
// Failure
$_SESSION["message"] = "Assessment creation failed.";
redirect_to("errors.php");
}
// Perform second database insert
$query2 = "INSERT INTO general_assessment (";
$query2 .= "`company_name`, `date`, `rsm`, `agents`, `distributor`";
$query2 .= ") VALUES (";
$query2 .= " '{$company_name}', '{$date}', '{$rsm}', '{$agents}', '{$distributor}'";
$query2 .= ")";
$result2 = mysqli_query($connection, $query2);
if ($result2) {
// Success
$_SESSION["message"] = "Assessment created.";
redirect_to("results.php");
} else {
// Failure
$_SESSION["message"] = "Assessment creation failed.";
redirect_to("errors.php");
}
}
else {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/errors-inserting.php");
}
?>
<?php
if (isset($connection)) { mysqli_close($connection); }
?>
You'll see on the processing page my little test of
print "distributor: " . $distributor;
exit;
this would obviously be removed when working.
Ok I think I've figured this out. I needed to "recall" the session data when I move to page 2.
So on the top of page 2 the code became:
<?php
session_start();
//store the posted values in the session variables
$_SESSION['company_name'] = $_POST['company_name'];
$_SESSION['date'] = $_POST['date'];
$_SESSION['rsm'] = $_POST['rsm'];
$_SESSION['agents'] = $_POST['agents'];
$_SESSION['distributor'] = $_POST['distributor'];
?>
You have to use line session_start(); on every page that you want to use the session - as the first line on top of the file.
You can set variables:
$_SESSION['username'] = "user";
and then retrieve them:
echo $_SESSION['username'];
You can then use session_destroy() to remove the saved session
To use a session variables for PHP at the many files. Try like this :
page1.php
<?php
session_start();
$_SESSION['name'] = 'Example session';
?>
When you use the session variables at the another page :
page2.php
<?php
include 'page1.php';
echo $_SESSION['name']; //Example session
?>
And to destroy session. Use session_destroy(); unset($_SESSION);

Submit button won't work in PHP

PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
header('location: no_acces.php');
exit();
} else {
$id_user = $_SESSION['userid'];
$q_user = mysqli_query($conn, "SELECT * FROM users WHERE id = $id_user");
if (mysqli_num_rows($q_user) === 1) {
$r_user = mysqli_fetch_assoc($q_user);
} else {
unset($_SESSION['login']);
unset($_SESSION['userid']);
header('location: no_acces.php');
exit();
}
}
$error = "";
$userQuery = mysqli_query($conn, "SELECT username FROM users");
$user = mysqli_fetch_assoc($userQuery);
$id = $_GET['id'];
if (isset($_POST['edit_contact'])) {
$roepnaam = $_POST['roepnaam'];
$naam = $_POST['naam'];
$land = $_POST['land'];
$bedrijf = $_POST['bedrijf'];
$adres1 = $_POST['adres1'];
$adres2 = $_POST['adres2'];
$stad = $_POST['stad'];
$postcode = $_POST['postcode'];
$provincie = $_POST['provincie'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$captcha= $_POST['g-recaptcha-response'];
if(!$captcha){
$error = "Er is een fout opgetreden";
}
if ($error == "") {
$insertUser = ("UPDATE address SET
roepnaam = '$roepnaam', naam = '$naam', bedrijf = '$bedrijf', telefoon = '$telefoon', email = '$email', adres1 = '$adres1', adres2 = '$adres2', stad = '$stad', postcode = '$postcode', provincie = '$provincie', land = '$land' WHERE id = $id");
if (mysqli_query($conn, $insertUser)) {
$_SESSION['edit_contact'] = true;
header('location: address_book.php');
} else {
$error = "Er is een fout opgetreden";
}
}
}
?>
HTML Code
<!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post">
<?php if ($error !== "") { ?>
<div class="row">
<div class="col-md-12 error">
<?php echo $error; ?>
</div>
</div>
<?php } ?>
<label for="firstName" class="control-label">Naam:</label>
<div class="row ">
<div class="col-md-6">
<input type="text" class="form-control" id="firstName" placeholder="Roepnaam" name="roepnaam" value="<?php if (isset($_POST['roepnaam'])) { echo $_POST['roepnaam']; } ?>" required/>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="lastName" placeholder="Naam" name="naam" value="<?php if (isset($_POST['naam'])) { echo $_POST['naam']; } ?>" required/>
</div>
</div>
<label for="username" class="control-label">Bedrijf:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="username" placeholder="Bedrijf" name="bedrijf" value="<?php if (isset($_POST['bedrijf'])) { echo $_POST['bedrijf']; } ?>" required/>
</div>
</div>
<label for="password" class="control-label">Telefoonnummer:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Telefoonnummer" name="telefoon" value="<?php if (isset($_POST['telefoon'])) { echo $_POST['telefoon']; } ?>" required/>
</div>
</div>
<label for="email" class="control-label">Email:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="email" placeholder="E-mailadres" name="email" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>" required/>
</div>
</div>
<label for="adres1" class="control-label">Adres:</label>
<div class="row">
<div class="col-md-12">
<input type="text" class="form-control" id="adres1" placeholder="Adres 1" name="adres1" value="<?php if (isset($_POST['adres1'])) { echo $_POST['adres1']; } ?>" required/>
</div>
</div>
<div class="row padding-top-10">
<div class="col-md-12">
<input type="text" class="form-control" id="adres2" placeholder="Adres 2" name="adres2" value="<?php if (isset($_POST['adres2'])) { echo $_POST['adres2']; } ?>"/>
</div>
</div>
<div class="row">
<div class="col-md-3">
<label for="postcode" class="control-label">Postcode:</label>
</div>
<div class="col-md-5">
<label for="city" class="control-label">Stad:</label>
</div>
<div class="col-md-4">
<label for="regio" class="control-label">Regio:</label>
</div>
</div>
<div class="row ">
<div class="col-md-3">
<input type="text" class="form-control" id="postcode" placeholder="Postcode" name="postcode" value="<?php if (isset($_POST['postcode'])) { echo $_POST['postcode']; } ?>" required/>
</div>
<div class="col-md-5">
<input type="text" class="form-control" id="city" placeholder="Stad" name="stad" value="<?php if (isset($_POST['stad'])) { echo $_POST['stad']; } ?>" required/>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="regio" placeholder="Provincie" name="provincie" value="<?php if (isset($_POST['provincie'])) { echo $_POST['provincie']; } ?>" required/>
</div>
</div>
<label for="land" class="control-label">Land:</label>
<div class="row ">
<div class="col-md-12">
<input type="text" class="form-control" id="password" placeholder="Land" name="land" value="<?php if (isset($_POST['land'])) { echo $_POST['land']; } ?>" required/>
</div>
</div>
<div class="row">
<div class="col-md-8 padding-top-10 ">
<div class="g-recaptcha " data-sitekey="6LcCsBoTAAAAAK72uzyJSrgWwD8xuF6jFIfgFaHX"></div>
</div>
</div>
<div class="row">
<div class="col-md-2 padding-top-10">
<input type="submit" name="edit_contact" class="btn btn-succes" value="Wijzigen">
</div>
<div class="col-md-2 padding-top-10">
<input type="text" name="delete_contact" action="delete_contact.php" class="btn btn-succes" value="Contact verwijderen">
</div>
</div>
</form>
</body>
</html>
PHP Code
<?php
if (!isset($_SESSION)) { session_start(); }
include "connect.php";
include "functions.php";
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true || !isset($_SESSION['userid']) || $_SESSION['userid'] == "") {
header('location: login.php');
exit();
} else {
session_regenerate_id();
}
$id = $_GET['id'];
$query = "DELETE FROM address WHERE id= $id";
mysqli_query ($query);
if (mysql_affected_rows() == 1) {
header('location: addressbook.php');
} else {
echo "Verwijderen mislukt";
}
?>
I'm trying to make a delete button for my contacts within the addressbook. but everytime I click "Contact verwijderen" the webpage resets it self and the contact won't be deleted. Could anyone help me to fix this?
You input is a text input and you don't have a form asociated with it,create one and change the type of submit to submit
<form action="delete_contact.php" method="post">
//other inputs
<input type="submit" name="delete_contact" class="btn btn-succes" value="Contact verwijderen">
</form>
You are mixing MySQL and MySQLi functions:
mysqli_query ($query);
if (mysql_affected_rows() == 1)
You cannot mix MySQL with MySQLi, your code should be:
mysqli_query ($query);
if (mysqli_affected_rows($conn) == 1)
Add a normal link to delete the contact, you don't need a form.
<a href="delete_contact.php?id=<?php echo $id ?>">
Contact verwijderen
</a>

Categories