Image not saving to a folder in PHP - php

I'm trying to upload a picture to my server and save the image name to my database. But if I fill in my form it just refreshes and does nothing. Does someone know why it doesn't save to the folder?
If my submit button is clicked I run this PHP code:
<?php
if(isset($_POST['btn_save_updates'])) {
$id = $_GET['id'];
$email = $_POST['email'];
$signature = $_POST['signature'];
//if they DID upload a file...
if($_FILES['avatar']['name'])
{
//if no errors...
if(!$_FILES['avatar']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['avatar']['tmp_name']); //rename file
if($_FILES['avatar']['size'] > (2048000)) //can't be larger than 1 MB
{
$valid_file = false;
$error = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatar/'.$new_file_name);
$filename = $_FILES['avatar']['name'];
// run update statement here ...
$error = 'Settings have been updated.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$error = 'Oops! Error: '.$_FILES['avatar']['error'];
}
}
}
?>
HTML Form:
<form method="post" role="form" autocomplete="off">
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" tabindex="1" class="form-control" value="<?php userProfile("email"); ?>" autocomplete="off">
</div>
<div class="form-group">
<label for="signature">Signature <i id="sign_tooltip" class="fa fa-exclamation-circle" aria-hidden="true" ata-toggle="tooltip" data-placement="right" title="You can add images to your signature!"></i></label>
<script>
$("#sign_tooltip").hover(function(){
$('#sign_tooltip').tooltip('show')
});
</script>
<textarea rows="4" name="signature" id="signature" tabindex="3" class="form-control" autocomplete="off"><?php userProfile("signature"); ?></textarea>
</div>
<br /><br />
<div class="form-group">
<label for="email">Avatar</label><br /><br />
<img src="avatars/<?php userInfo('avatar'); ?>" alt="Default Avatar" class="img-circle" width="140" height="140"><br /><br />
<input name="avatar" id="avatar" tabindex="4" class="input-group" type="file" accept="image/*" />
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-7">
</div>
<div class="col-xs-5 pull-right">
<button type="submit" name="btn_save_updates" id="btn_save_updates" tabindex="5" class="form-control btn btn-success"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save </button>
</div>
</div>
</div>
</form>

You forgot to add enctype="multipart/form-data" to your form.

Related

file upload error messages are not displaying in codeigniter

I'm trying to insert data into database through a form. I'm uploading 2 image files, in database path of the files will be stored. I'm trying to do server side validation. when user does not upload a file or when user is uploading wrong file type, an error messages should display and page should return to same page with no data inserted into database.
This is my view:
<div class="main-panel">
<div class="content-wrapper">
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Add News & Event</h4>
<p class="card-description"> </p>
<?php echo validation_errors("<div class='alert alert-danger'>","</div>");?>
<?php if($failed = $this->session->flashdata('addNewsFailed')){
echo '<div class="alert alert-danger">' ;
echo $failed;
echo '</div>';
}?>
<form class="forms-sample" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputName1">Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo
set_value("title");?>" name="title">
</div>
<div class="form-group">
<label for="exampleInputName1">Sub Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo set_value("sub");?>" name="sub_title">
</div>
<div class="form-group">
<label for="exampleInputName1">Event Date</label>
<input type="text" class="form-control" id="exampleInputName1" name="date" value="<?php echo date('d - M - y ');//echo set_value("date");?>">
</div>
<div class="container">
<div class="row">
<div class="col-md">
<div class="form-group">
<label>Feature Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="img" style="z-index: 9999; opacity: 0;" id="image">
<div id="imageName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute; left: 0; padding: 6px 23px;border-radius:3px;">Upload</button> </span>
</div>
<?php if(isset($upload_error)){
echo $upload_error;
}?>
</div>
</div>
<div class="col-md">
<div class="form-group">
<label> Banner Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="banner" id="banner" style="opacity: 0; z-index: 9999;">
<div id="bannerName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute;left: 0;padding: 6px 23px;border-radius: 3px;">Upload</button></span>
</div>
<?php if(isset($upload_error1)){
echo $upload_error1;
}?>
</div>
</div>
</div>
</div>
<span class="input-group-append">-->
<div class="form-group">
<label for="exampleTextarea1">Text</label>
<textarea class="form-control" id="exampleTextarea1" rows="2" name="para" value=""><?php echo set_value("para");?></textarea>
</div>
<button type="submit" class="btn btn-success mr-2">Add</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
This is my controller:
public function addEvent()
{
//load library
$this->load->library('form_validation');
$this->load->helper('form');
//set rules for validation
$this->form_validation->set_rules("title", "Title", "required");
$this->form_validation->set_rules("date", "Event Date", "required");
$this->form_validation->set_rules("para", "Text", "required");
//template
$this->output->set_template('admin_layout');
//image upload
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
];
$this->load->library('upload', $config);
//validation
if ($this->form_validation->run()) {
$post = $this->input->post();
if (!$this->upload->do_upload('img')) {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
} else {
$Feature1 = $this->upload->data();
$image_path = base_url('uploads/' . $Feature1['raw_name'] . $Feature1['file_ext']);
$post['image_path'] = $image_path;
}
if (!$this->upload->do_upload('banner')) {
$upload_error1 = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error1'));
} else {
$carsousel = $this->upload->data();
$banner = base_url('uploads/' . $carsousel['raw_name'] . $carsousel['file_ext']);
$post['banner'] = $banner;
}
$this->load->model('loginmodel', 'addNews');
$insert_id = $this->addNews->addNews($post);
if ($insert_id) {
$this->session->set_flashdata("addNewsSuccess", 'News & Event Added Successfully');
redirect('dashboard/update_news/' . $insert_id);
} else {
$this->session->set_flashdata("addNewsFailed", 'Failed');
$this->load->view('dashboard/pages/forms/addEvent');
}
} else {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
}
}
This is my model:
public function addNews($array)
{
$this->db->insert('news', $array);
return $this->db->insert_id();
}
My form validation are working perfectly but when user is uploading wrong file type or does not upload any file then file upload error message is not displaying and data is inserting into database the with both image field empty.

I want to add multiple images into MySQL database

I'm working on this feature in my project where I want to add three(3) images along side other details into my database row and I want this images to be in separate columns in one row.... So far below is my code. the code is not working yet... The images and texts are not uploading to the database....
Please help me out guys. What am I doing wrong. Thanks.
Below is my code sample:
//THE PHP SECTION//
<?php
session_start();
include 'includes/config.php';
if (isset($_POST['post']) && isset($_POST['itemtype'])) {
$title = mysqli_real_escape_string($link, $_POST['title']);
$itemtype = mysqli_real_escape_string($link, $_POST['itemtype']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$image1 = $_FILES['image1']['name'];
$image1_tmp_name = $_FILES['image1']['tmp_name'];
$image2 = $_FILES['image2']['name'];
$image2_tmp_name = $_FILES['image2']['tmp_name'];
$image3 = $_FILES['image3']['name'];
$image3_tmp_name = $_FILES['image3']['tmp_name'];
$price = mysqli_real_escape_string($link, $_POST['price']);
$category = mysqli_real_escape_string($link, $_POST['category']);
$name = mysqli_real_escape_string($link, $_POST['name']);
//image file directory
$target1 = 'images/user_ads/'.basename($image1);
$target2 = 'images/user_ads/'.basename($image2);
$target3 = 'images/user_ads/'.basename($image3);
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
//insert into ost database
$insert = "INSERT INTO products(Title,Product_Type,Description,Image1,Image2,Image3,Price,Category,Name,PostedDate)VALUES('$title','$itemtype','$description','$target1','$target2','$target3','$price','$category','$name',NOW())";
$insertKwary = mysqli_query($link, $insert);
if ($insertKwary) {
$msg = "<div class='alert alert-danger alert-success'>Product Submitted</div>";
}else{
$msg = "<div class='alert alert-danger alert-success'>Product Not Submitted...Try again</div>";
}
}
?>
//THE HTML SECTION//
<div class="col-md-8 col-md-offset-2">
<?php if(isset($msg)) { echo $msg; } ?>
<form action="" method="POST" enctype="multipart/form-data" class="postAdForm" id="postAdForm">
<div class="form-group">
<label for="Ad_title">Item Title</label>
<input type="text" name="title" class="form-control title" id="title" required=""/>
</div>
<div class="form-group">
<label for="itemtype">Item Type</label>
<select class="form-control" name="itemtype" id="itemtype">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="description">Item Description</label>
<textarea name="description" class="form-control description" id="description" rows="7" required=""></textarea>
</div>
<div class="form-group">
<label for="price">First Image</label>
<input type="file" name="image1" class="form-control image1" id="image1" required="" />
</div>
<div class="form-group">
<label for="price">Second Image</label>
<input type="file" name="image2" class="form-control image2" id="image2" required="" />
</div>
<div class="form-group">
<label for="price">Third Image</label>
<input type="file" name="image3" class="form-control image3" id="image3" required="" />
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" name="price" class="form-control price" id="price" required="" />
</div>
<div class="form-group">
<label for="category">Item Category</label>
<select class="form-control" name="category" id="category">
<option>Sale</option>
<option>Request</option>
</select>
</div>
<div class="form-group">
<label for="price">Name</label>
<input type="text" name="name" class="form-control name" id="name" required="" readonly="" />
</div>
<div class="form-group">
<input type="submit" name="post" class="btn btn-post post" id="post" value="POST AD" />
</div>
</form>
</div>
I've also attached an image of the error i'm getting..
image of web page showing thee errors i get..error gotten
The error is due to these lines:
if (move_uploaded_file($_FILES['image1_tmp_name'], $target1)) {
}
if (move_uploaded_file($_FILES['image2_tmp_name'], $target2)) {
}
if (move_uploaded_file($_FILES['image3_tmp_name'], $target3)) {
}
You're setting $image1_tmp_name, not $_FILES['image1_tmp_name'].
Try this:
if (move_uploaded_file($image1_tmp_name, $target1)) {
}
if (move_uploaded_file($image2_tmp_name, $target2)) {
}
if (move_uploaded_file($image3_tmp_name, $target3)) {
}
Edit: Using mysqli_error() to print the error helped solve additional issues (Mentioned in comments)

How to upload a image in codeigniter

I am unable to upload a image in the destination folder in codeigniter, I created one controller under the controller/admin folder with a name called site. And I added one model under the model folder with a name called model_view, and finally I created one view in the view folder with a name called view_addsite. And I created one table in the mysql with a name called sitesettings and 14 columns are added in that table. Problem hear is all fields are added in the table except image. please find the code.
controller(site)::
===========
public function add()
{
$datte = date('Y-m-d H:i:s');
if(!$this->input->post('buttonSubmit'))
{
$data['message'] = '';
$this->load->view('admin/view_addsite', $data);
}
else
{
//$this->load->library('form_validation');
if($this->form_validation->run('addsite'))
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_width'] = '2048';
$config['max_height'] = '2048';
$this->load->library('upload', $config);
$title = $this->input->post('title');
$name = $this->input->post('name');
$admin = $this->input->post('admin');
$mail = $this->input->post('mail');
$phone = $this->input->post('phone');
$contact=$this->input->post('contact');
$fb=$this->input->post('fb');
$tw=$this->input->post('tw');
$yt=$this->input->post('yt');
$in=$this->input->post('in');
$gp=$this->input->post('gp');
$ft=$this->input->post('ft');
$this->upload->do_upload('image');
$data = $this->upload->data('image');
$image= $data['file_name'];
$this>model_site>
insert($title,$image,$name,$admin,$mail,
$phone,$contact,$fb,$tw,$yt,$in,$gp,$ft);
$this->session->set_flashdata('message','site Successfully
Created.');
redirect(base_url('admin/site'));
}
else
{
$data['message'] = validation_errors();
$this->load->view('admin/view_addsite', $data);
}
}
}
Model(model_site)::
===================
public function
insert($title,$image,$name,$admin,$mail,$phone,$contact,
$fb,$tw,$yt,$in,$gp,$ft)
{
$data = array(
'admintitle' => $title,
'logo' => $image,
'fromname' => $name,
'adminemail'=> $admin,
'receivemail' => $mail,
'phonenumber' => $phone,
'contactaddress' => $contact,
'facebook' => $fb,
'twitter'=>$tw,
'youtube' => $yt,
'instagram' => $in,
'googleplus' => $gp,
'footer' => $ft,
);
$this->db->insert('sitesettings', $data);
}
view(view_addsite)::
===================
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>Sitesettings</h3>
</div>
</div><div class="clearfix"></div>
<hr>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Add a new Site</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-
chevron-up"></i></a></li>
<li><a class="close-link"><i class="fa fa-close">
</i></a></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<label><?php echo $message; ?></label>
<form method="post">
<fieldset>
<div class="form-group">
AdminPage Title : <input class="form-control"
placeholder="Admin Title" name="title" id="title"
type="text" ><span id="user-availability-status">
</span>
<div class="form-group">
Select image to upload:
<input type="file" name="fileToUpload"
id="fileToUpload">
</form>
<div class="form-group">
From Name : <input class="form-control"
placeholder="Form Title" name="name" id="name" type="text"
><span id="user-availability-status"></span>
<div class="form-group">
Admin Email Address : <input class="form-control"
placeholder="Admin Email" name="admin" id="admin"
type="text" onBlur="checkAvailability()" ><span
id="user-availability-status"></span>
<div class="form-group">
Receive Mail Address for Contact Us Form : <input
class="form-control" placeholder="Receive Email"
name="mail" id="mail" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Phone number: <input class="form-control"
placeholder="Phone Number" name="phone" id="phone"
type="text" onBlur="checkAvailability()" ><span id="user-
availability-status"></span>
</div>
<div class="form-group">
Contact Adress : <input class="form-control"
placeholder="Contact Address" name="contact" id="contact"
type="text" onBlur="checkAvailability()" ><span
id="user-availability-status"></span>
</div>
<div class="form-group">
Facebook : <input class="form-control" placeholder="Facebook"
name="fb" id="fb" type="text" onBlur="checkAvailability()" >
<span id="user-availability-status"></span>
</div>
<div class="form-group">
Twitter : <input class="form-control" placeholder="Twitter"
name="tw" id="tw" type="text" onBlur="checkAvailability()" >
<span id="user-availability-status"></span>
</div>
<div class="form-group">
Youtube : <input class="form-control"
placeholder="Youtube" name="yt" id="yt" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Instagram : <input class="form-control"
placeholder="Instagram" name="in" id="in" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Google Plus: <input class="form-control"
placeholder="Google Plus" name="gp" id="gp" type="text"
onBlur="checkAvailability()" ><span id="user-availability-
status"></span>
</div>
<div class="form-group">
Footer: <input class="form-control"
placeholder="Footer" name="ft" id="ft"
type="text" onBlur="checkAvailability()" ><span id="user-
availability-status"></span>
</div>
<input type="submit" name="buttonSubmit"
value="add" class="btn btn-success" />
</fieldset>
</form>
</div> <!-- /content -->
</div><!-- /x-panel -->
</div> <!-- /col -->
</div> <!-- /row -->
</div>
</div> <!-- /.col-right -->
<!-- /page content -->
<?php $this->load->view('admin/partials/admin_footer'); ?>
<?php if($this->session->flashdata('message') != NULL) : ?>
<script>
swal({
title: "Success",
text: "<?php echo $this->session->flashdata('message'); ?>",
type: "success",
timer: 1500,
showConfirmButton: false
});
</script>
<?php endif ?>
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
for more detail see:upload file with codeigniter
You are missing
enctype="multipart/form-data"
on your form tag and also remove the </form> just after the image input box.
Controller:
$doc_1 = "uploads/img_1/";
if (isset($_FILES['userfile_1']) && !empty($_FILES['userfile_1'])) {
$filename = pathinfo($_FILES['userfile_1']['name']);
if (move_uploaded_file($_FILES['userfile_1']['tmp_name'], $doc_1.$filename['basename'])) {
$attch_1 = base_url().$doc_1.$filename['basename'];
}
else {
$attch_1 = "na";
}
}
view:
<?php echo form_open_multipart("store_property", ['class'=>'form-horizontal']); ?>
<input type="file" name="userfile_1" />

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);

PHP - how to upload 3 images with 3 inputs in one form php

I'm trying to upload 3 images to my server
I have 3 file inputs in the same form.
so far, I receive the following parameters through post (3 images)
$license_img, $car_pic, $driver_pic
And here I try to upload thouse images to server.
if($license_img!= '') {
$license_decoded = base64_decode($license_img);
$license_pic_path = '....images/licenses/'.$email.'.jpg';
file_put_contents($license_pic_path, $license_decoded);
}
if($driver_pic != '') {
$driver_decoded = base64_decode($driver_pic);
$driver_pic_path ='....images/profiles/'.$email.'.jpg';
file_put_contents($driver_pic_path, $driver_decoded);
}
if($car_pic != '') {
$car_decoded = base64_decode($car_pic);
$car_pic_path = '....images/cars/'.$email.'.jpg';
file_put_contents($car_pic_path, $car_decoded);
}
In another script I upload one picture with file_put_content and it works just fine...
How is the right way to upload multiple images with one form?
Update
<script>
function getPicture(img) {
var file = document.getElementById(img);
file.click(); // open file
}
function onImgSelected(event) {
var pieces = event.target.value.split("\\\");
var filename = pieces[pieces.length-1];
if(event.target.id == "driver_img") {
document.getElementById("path_driver_img").value = filename;
} else if(event.target.id == "car_img"){
document.getElementById("path_car_img").value = filename;
} else {
document.getElementById("path_licenta_img").value = filename;
}
}
</script>
<!-- accept="jpeg,jpg,png,bmp" -->
<input type="file" style="display: none" accept="jpeg,jpg,png,bmp" name="driver_img" id="driver_img" onChange="onImgSelected(event)" />
<input type="file" style="display: none" accept="jpeg,jpg,png,bmp" name="car_img" id="car_img" onChange="onImgSelected(event)" />
<input type="file" style="display: none" accept="jpeg,jpg,png,bmp" name="license_img" id="license_img" onChange="onImgSelected(event)" />
<div class="form-group col-xs-12 space-bottom">
<label class="control-label">Driver Picture</label>
<div class="input-group">
<input type="text" class="form-control" id="path_driver_img" readonly>
<span class="input-group-btn">
<button class="btn btn-default" onClick="getPicture(\'driver_img\')" type="button">Up</button>
</span>
</div>
</div>
<div class="form-group col-xs-12 space-bottom">
<label class="control-label">Car Picture</label>
<div class="input-group">
<input type="text" class="form-control" id="path_car_img" readonly>
<span class="input-group-btn">
<button class="btn btn-default" onClick="getPicture(\'car_img\')" type="button">Up</button>
</span>
</div>
</div>
<div class="form-group col-xs-12 space-bottom">
<label class="control-label">Taxi License Image <font color="red">*</font></label>
<div class="input-group">
<input type="text" class="form-control" id="path_licenta_img" readonly>
<span class="input-group-btn">
<button class="btn btn-default" onClick="getPicture(\'license_img\')" type="button">Up</button>
</span>
</div>
</div>
</div>
<div class="col-xs-12"><br>
<div class="col-xs-12" align="center"> <input type="submit" value="Submit" class="btn btn-success btn-md"></div>
</div>
This is a very simple script for uploading images
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file01" /><br />
<input type="file" name="file02" /><br />
<input type="file" name="file03" /><br />
<input type="text" name="text" /><br />
<input type="submit" value="Upload images" />
</form>
<?php
echo '$_FILES:'."<br /><pre>";
var_dump($_FILES);
echo "</pre>";
echo '$_POST:'."<br /><pre>";
var_dump($_POST);
echo "</pre>";

Categories