Actually while uploading a file I am creating folder with timestamp and also saving folder name along with filename to the database this is working fine. While editing I have input type hidden in this I am posting value if user do not change files and also if folder exits already it should not create folder and If user change files that time it should create a new folder.Only it is going to if condition. not else part.Please help me someone.
Below is PHP code,
if(isset($_FILES['event_image']['name'])&& $_FILES['event_image']['name']!="")
{
$folder_name =$_FILES['event_image']['name'];
echo $folder_name;
}
else
{
$folder_name =$_POST['image_exists'];
echo $folder_name;
}
//print_r($pathToUpload);die;
$old = umask(0);
if (!file_exists($folder_name))
{
//echo "djfgd";die;
$folderName = $_POST['event_name'].time();
$pathToUpload = 'images/events/' . $folderName;
$create = mkdir($pathToUpload, 0777,true);
//chmod($pathToUpload,0755,true);
if ( ! $create )
return;
}
else{
//echo "dqqqqqq";die;
//$folderName = $_POST['event_name'].time();
//$pathToUpload = 'images/events/' . $folderName;
//$create = mkdir($pathToUpload, 0777,true);
echo "already exits";die;
}
umask($old);
HTML code:
<div class="col-md-6">
<div class="form-group">
<label for="event_image">Event Banner</label>
<input type="file" value="<?php echo $event_image; ?>"
class="form-control" id="eventimage" name="event_image">
<input type="hidden" name="image_exists" value="<?php echo $event_image;?>"
class="form-control" id="eventimage" placeholder="Enter Image Text" aria-describedby="fileHelp">
<div><?php echo $event_image;?></div>
</div>
</div>
Alright I have simulated your case on my machine using Codeigniter and simple PHP is_dir function.
Here is my test view
Created with Following Markup
<div class="container" style="margin-top:100px; ">
<div class="col-md-6" style="border: 1px dotted red; ">
<?php if(isset($errors)){?>
<div class="alert alert-danger">
<?php print_r($errors);?>
</div>
<?php }?>
<?php if(isset($success)){?>
<div class="alert alert-success">
<?php print_r($success);?>
</div>
<?php }?>
<form action="" method="post" id="form1">
<div class="form-group">
<label > Directory Name</label>
<input type="text" name="name" class="form-control" >
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" >Create</button>
</div>
</form>
</div>
</div>
My Controller
public function index()
{
$data['title']='Multiple submit';
if($_POST)
{
$path='uploads/'.$_POST['name'];
if (!is_dir($path)) {
mkdir($path);
$data['success']='Directory Created Successfully';
$this->load->view('form',$data);
}
else
{
$data['errors']='Directory Already Exist';
$this->load->view('form',$data);
}
}
else
{
$this->load->view('form',$data);
}
}
I create a directory, which is success.
I try it again, get an error
The Directory created in my path is
I hope you can modify this code as per your requirements.
Related
I have a long-form with some images upload areas. I need to insert images with text data to MySQL database The form and query code as follows. If PHP codes are not correct, tell me how to do it correctly.?
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="form_main">
<h4 class="heading"><strong>Add</strong> Vehicle <span></span></h4>
<div class="form">
<form action="insert.php" method="POST" id="contactFrm" enctype="multipart/form-data" name="contactFrm">
<select class="form-control form-control-lg" name="brand">
<option value="TATA" >TATA</option>
<option value="TOYOTA">TOYOTA</option>
<option value="DAIHATSu">DAIHATSU</option>
</select>
<input type="text" required="" placeholder="Model" name="model" class="txt">
<div class="form-group">
<label for="exampleFormControlFile1">Front</label>
<input type="file" name="vehi_front" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Left</label>
<input type="file" name="vehi_left" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Right</label>
<input type="file" name="vehi_right" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">Rear</label>
<input type="file" name="vehi_back" class="form-control-file" id="exampleFormControlFile1">
</div>
<textarea placeholder="Other" name="other" type="text" class="txt_3"></textarea>
<input type="submit" value="submit" name="submit" class="txt2">
</form>
</div>
</div>
</div>
</div>
</div>
This is the insert query code.
<?php
include("../inc/conn.php");
$brand=$_POST['brand'];
$model=$_POST['model'];
$vehi_front=$_POST['vehi_front'];
$vehi_left=$_POST['vehi_left'];
$vehi_right=$_POST['vehi_right'];
$vehi_back=$_POST['vehi_back'];
$other=$_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if(mysqli_query($con,$sql))
{
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
you must create image uploader function
in php $_POST['image_input_name'] return you null
you must use $_FILE
function uploadPic($file_input_name, $path)
{
if (isset($_FILES[$file_input_name])) {
$file = $_FILES[$file_input_name];
// for bin2hex and random_bytes you must use php > 7
$new_name = (string)bin2hex(random_bytes(32));
$extension = ".jpg";
$final_name = $new_name . $extension;
move_uploaded_file($file['tmp_name'], $path . $final_name);
return $path . $final_name;
}
}
first line check for image
2 get the file and put in into $file
3 change the name for security
4 change the extension for more security
// user upload a shel.php. in function we change the name and extension
// for exp shel.php converted to hs7f4w8r5c1f4s5d9t6g3s149748654asdasd.jpg
5 add name and extension in var
6 we move uploaded pic to path
7 we return the address and name of pic
and in your new code here
<?php
include("../inc/conn.php");
$brand = $_POST['brand'];
$model = $_POST['model'];
// in if we check for image exist
if ($_FILES['vehi_front']['tmp_name'] != "") {
$vehi_front = $this->uploadPic("vehi_front", "/path/to/save/image");
}
if ($_FILES['vehi_left']['tmp_name'] != "") {
$vehi_left = $this->uploadPic("vehi_left", "/path/to/save/image");
}
if ($_FILES['vehi_right']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_right", "/path/to/save/image");
}
if ($_FILES['vehi_back']['tmp_name'] != "") {
$vehi_right = $this->uploadPic("vehi_back", "/path/to/save/image");
}
$other = $_POST['other'];
{
$sql = "INSERT INTO vehicle(brand,model,vehi_front,vehi_left,vehi_right,vehi_back,other) VALUES ('{$brand}','{$model}','{$vehi_front}','{$vehi_left}','{$vehi_right}','{$vehi_back}','{$other}')";
if (mysqli_query($con, $sql)) {
header("location:add_vehicle.php?msg=Successfully Saved !");
}
}
?>
You can do this using $_FILES variable
see reference here: https://www.php.net/manual/en/reserved.variables.files.php
I'm having difficulties to insert the value as blob type always empty and the other method can't insert the images in a folder. Please you can show the way out. Thanks! This code is to save the image in a folder and then access it with the name to display, but is not saving the photos to the folder. I edited and include the form here, containing JavaScript and css .It looks some how messy but i'm a beginner. Thanks.
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div><title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
I was having permission issues, the images folder permission was changed. That solves everything. Thanks!
I'm getting this error trying to upload image to a folder, move_uploaded_file permission denied on line 23. What should be the problem? I have the form below, the logic and the page to display it. Thanks!
<?php
include("../views/post_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
if ($_SERVER["REQUEST_METHOD"]== "POST")
{
$usertext = $_POST["usertext"];
$image = $_FILES['image']['name'];
$talent =$_POST["talenttype"];
if(empty($usertext) || empty($image)|| empty($talent))
{
die();
}
$id = $_SESSION["id"];
$folder ="images/".basename($_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'],$folder) ;
$query = mysqli_query($link,"SELECT * FROM `upload` WHERE id = '$id'");
$upload = mysqli_query($link,"INSERT INTO `upload` (description,image,talent,folder) VALUES('$usertext','$image','$talent','$folder ')");
}
?>
To display, I want the photos to be save to the folder, not saving. I used blob method not inserting into the database.
<?php
include("../views/feeds_form.php");
require("../includes/include.php");
require("../includes/sess_n.php");
$query = mysqli_query($link,"SELECT * FROM `upload` ");
if ($query === false)
{
die();
}
echo '<table>';
while ($run = mysqli_fetch_assoc($query))
{
echo '<tr>';
echo '<td>';?> <img src =" <?php echo $run["image"]; ?>" height=100 width=100> <?php echo '<td>';
echo '<td>'; echo $run["description"]; echo '<td>'; echo $run["folder"];echo '<td>';
echo '</tr>';
}
echo '</table>';
?>
The form here.
<?php
include("../public/header.php");
?>
<div> <title>post</title></div>
<style>
.form-inline
{
text-align: center;
margin-bottom: 50px;
}
</style>
<script type="text/javascript">
function validate(){
var usertext = document.getElementById("usertext");
var talent = document.getElementById("talenttype");
var image = document.getElementById("image");
if (usertext.value === "" && talent.value === "" && image.value ==="")
{
alert("Field Must Not be Empty");
}
}
</script>
<form class="form-inline" method ="POST" action ="post.php" enctype="multipart/form-data" onsubmit= "return validate();">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3"> </label>
<textarea class="form-control" id = "usertext" name ="usertext" rows="5" placeholder="Describe Person Here"></textarea> <br><hr>
<label class="sr-only" for="exampleInputEmail3"></label><br>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="file" class="form-control" id = "image" id="exampleInputPassword1" name="image" placeholder="image">
</div> <br><br><br> <hr>
<div class="form-group">
<label for="exampleInputPassword1"></label>
<input type="text" class="form-control" id = "talenttype" id="exampleInputPassword1" name = "talenttype" placeholder="Talent-Type"><br><br>
</div> <hr>
<div>
<button type="submit" name ="post" class="btn btn-default">Post</button><br>
</div>
</div>
</form>
<?php
include("../public/footer.php");
?>
Issue is that httpd process owner doesn't have write permission for images folder. You can either:
chown the folder to PHP's user and set write permission for owner; or
You make it 777: everybody has Read, Write & Execute permission
Also it is not a good idea to do write permission globally
I'd say,
Open your terminal
cd to the document root directory
type this command with super user privileges
chmod 775 -R /
Hope it Helps
i have a problem with a form in codeigniter. i have tried different things but i can not find a solution.
this is the form:
<form method="post" action="<?php echo base_url(); ?>cms/cms/newUser">
<div class="row">
<div class="col-md-3">
Naam:
</div>
<div class="col-md-9">
<input type="text" id="naam" name="username" />
</div>
</div>
<div class="row">
<div class="col-md-3">
E-mail:
</div>
<div class="col-md-9">
<input type="email" name="mail" id="email" />
</div>
</div>
<div class="row">
<div class="col-md-3">
Passwoord:
</div>
<div class="col-md-9">
<input type="password" name="pass" id="password" />
</div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<input type="submit" name="aanmaken" class="btn btn-block btn-info" value="aanmaken" />
</div>
</div>
in my controller i process the data coming from the form.
the controller is located at controllers/cms/cms.php
class Cms extends MY_Controller
{
public function newUser()
{
if(isset($_POST))
{
echo "verwerk deze data <br>";
if(isset($_POST['username']))
{
echo 'naam is set!';
}
else {
echo 'naam is not set!';
}
$naam = $_POST['username'];
$mail = $_POST['email'];
$pass = $_POST['password'];
echo "naam: " . $naam . "<br>";
echo "mail: " . $mail . "<br>";
echo "pass: " . $pass . "<br>";
$time = new DateTime();
$time->setTimezone(new DateTimeZone ('Europe/Brussels'));
$tijd = $time->format('Y-m-d H:i:s');
include_once('application/libraries/PasswordHash.php');
$hasher = new PasswordHash(12,false);
$passwoord = $hasher->HashPassword($pass);
$gebruiker = new Gebruiker();
$gebruiker->naam = $naam;
$gebruiker->email = $mail;
$gebruiker->paswoord = $passwoord;
$gebruiker->laatsteLogin = $tijd;
$gebruiker->active = 0;
echo "coded pas" . $passwoord . "<br>";
}
else
{
echo "no post";
}
}
when i check my website and fill in the form i get 3 php error that the values that i put in the variable from the post does not exist. also the if(isset) function says that the variable is not set. i don't know why the form action doesn't work.
i even tried the codeigniter way but it gave the same result.
$name = $this->input->post('username');
thanks for the help.
HTML:
enter code here
<form method="post" action="<?php echo site_url(); ?>/cms/cms/newUser">
<div class="row">
<div class="col-md-3">
Naam:
</div>
<div class="col-md-9">
<input type="text" id="naam" name="username" />
</div>
E-mail:
<div class="row">
<div class="col-md-3">
Passwoord:
</div>
<div class="col-md-9">
<input type="password" name="pass" id="password" />
</div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<input type="submit" name="aanmaken" class="btn btn-block btn-info" value="aanmaken" />
</div>
</div>
PHP:
class Cms extends MY_Controller
{
public function newUser()
{
if(isset($_POST))
{
echo "verwerk deze data <br>";
if($this->input->post('username'))
{
echo 'naam is set!';
}
else {
echo 'naam is not set!';
}
$naam = $this->input->post('username');
$mail = $this->input->post('mail');
$pass = $this->input->post('pass');
echo "naam: " . $naam . "<br>";
echo "mail: " . $mail . "<br>";
echo "pass: " . $pass . "<br>";
$time = new DateTime();
$time->setTimezone(new DateTimeZone ('Europe/Brussels'));
$tijd = $time->format('Y-m-d H:i:s');
include_once('application/libraries/PasswordHash.php');
$hasher = new PasswordHash(12,false);
$passwoord = $hasher->HashPassword($pass);
$gebruiker = new Gebruiker();
$gebruiker->naam = $naam;
$gebruiker->email = $mail;
$gebruiker->paswoord = $passwoord;
$gebruiker->laatsteLogin = $tijd;
$gebruiker->active = 0;
echo "coded pas" . $passwoord . "<br>";
}
else
{
echo "no post";
}
}
$this->input->post('') will check automatically not need of isset().
$this->input->post('') will take name not id
In the form tag
<form method="post" action="<?php echo base_url(); ?>cms/cms/newUser">
cms is the name of the controller and you have used it twice. Try with
<form method="post" action="<?php echo base_url(); ?>cms/newUser">
you need to pass only controllername/func_name and keep your controller file in controller dir
then try in CI way
<?php echo form_open("cms/newUser");?>
<?php echo form_close();?>
or
<form method="post" action="<?php echo base_url(); ?>cms/newUser">
Else you need to use routing for this and tell to pick this controller on that route
for this go to config/routes.php and add route like:-
$route['cms'] = "cms/cms";
try to load form helper and use this code
controller:
$this->viewContent['form_action'] = base_url()."cms/cms/newUser";
$this->load->view('your_view_page',$this->viewContent);
view:
echo form_open($form_action);
I try to upload an image, but it is not working. Other variables I have set are inserted into database, but image file is not... I was trying to check submit with isset, but it is not working. Where is my error?
Thanks for your help.
PHP file:
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno) {
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)) {
$i1 = strrpos($upload,".");
if (!$i1) {
return "";
}
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = copy($_FILES['upload']['tmp_name'], $newname1);
} else {
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>
This is my HTML file:
<form class="cmxform form-horizontal tasi-form" name="form2" id="form2" method="post" action="">
<div class="form-group ">
<label for="icode" class="control-label col-lg-2">Item Code</label>
<div class="col-lg-10">
<input class=" form-control" id="icode" name="icode" type="text" />
</div>
</div>
<div class="form-group ">
<label for="iname" class="control-label col-lg-2">Item Name</label>
<div class="col-lg-10">
<input class=" form-control" id="iname" name="iname" type="text" />
</div>
</div>
<div class="form-group ">
<label for="brandname" class="control-label col-lg-2">Brand Name</label>
<div class="col-lg-10">
<input class=" form-control" id="brandname" name="brandname" type="text" />
</div>
</div>
<fieldset style="width:48%; float:left;"> <!-- to make two field float next to one another, adjust values accordingly -->
<label>Doc 2</label>
<input style="margin: 0 10px;" type="file" name="upload" size="50">
</fieldset>
Add 'enctype="multipart/form-data"' to your form tag attributes, you can read more about file uploading here.
Also consider checking the values of the post, because your current method can get you sql injections
add form attribute enctype="multipart/form-data"
You have not proper syntax used and also use 'enctype="multipart/form-data"'.
I have implemented your code
<?php
include ('includes/config.php');
$mysqli = new mysqli(DB_SERVER,DB_UNAME,DB_PASSWD,DB_NAME);
if($mysqli->connect_errno){
echo "MYSQLI connect error no {$mysqli->connect_errno} : {$mysqli->connect_error}";
die();
}
$itemcode = $_POST['icode'];
$itemname = $_POST['iname'];
$brandname = $_POST['brandname'];
$upload = basename ($_FILES['upload']['name']);
$path = "img/";
if(!empty($upload)){
$i1 = strrpos($upload,".");
if (!$i1) { return ""; }
$l1 = strlen($upload) - $i1;
$ext1 = substr($upload,$i1+1,$l1);
$ext1 = strtolower($ext1);
$news_name1=time()+(1).'.'.$ext1;
$newname1 = $path.$news_name1;
$copied1 = $_FILES['upload']['tmp_name'], $newname1;
}else{
$news_name1 = '';
}
$iadd = $mysqli->prepare("INSERT INTO table_item (`itemcode`,`itemname`,`brandname`,`upload`) VALUES ('".$itemcode."', '".$itemname."','".$brandname."','".$news_name1."') ");
$iadd->execute();
$iadd->close();
$mysqli->close();
?>