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
Related
Let me explain my problem briefly.I have image names in MYSQL database.
I need to change the image name when user uploads a new image using file input field.Otherwise the image name in database remain same.But My problem is when user doesn't upload any images the image name becomes empty in database.
My HTML code for changing a image
<form method="post" action="edit_store_img.php?id=<?php echo (int)$store['id'] ?>" class="clearfix" enctype="multipart/form-data">
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a store image</label>
<input type="file" name="storepic" value="<?php echo $store['pic']; ?>"/>
</div>
</div>
<hr>
<br>
<h3>Change Map Image For Store <?php echo remove_junk($store['name']);?></h3>
<hr>
<!-- below code is for map image -->
<?php if($store['pic'] === '0'): ?>
<img class="img-avatar img-circle" src="uploads/mapimg/no_image.jpg" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php else: ?>
<img class="img-avatar img-circle" src="uploads/mapimg/<?php echo $store['map']; ?>" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php endif;
?>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a Store map location image</label>
<input type="file" name="mappic" value="<?php echo $store['map']; ?>"/>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="edit_store_img" class="add-btn">Update Store image</button>
</div>
</form>
This is my PHP file for getting ID for that particular image
<?php
$store = find_by_id('store',(int)$_GET['id']);
if(!$store)
{
$session->msg("d","Missing store id.");
redirect('store.php');
}
?>
This is my PHP code for Storing image name in database
<?php
if(isset($_POST['edit_store_img']))
{
if(empty($errors))
{
/*below queries is for image upload */
$msg = "";
$map = $_FILES["mappic"]["name"];
$tempname = $_FILES["mappic"]["tmp_name"];
$mapfolder = "uploads/mapimg/".$map;
// Now let's move the uploaded image into the mapfolder: image
if (move_uploaded_file($tempname, $mapfolder)) {
$msg = "map Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$message = "";
$pic = $_FILES["storepic"]["name"];
$tempname = $_FILES["storepic"]["tmp_name"];
$picfolder = "uploads/storeimg/".$pic;
// Now let's move the uploaded image into the folder image
if (move_uploaded_file($tempname, $picfolder)) {
$message = "Image uploaded successfully";
}else{
$message = "Failed to upload image";
}
$query = "UPDATE store SET";
$query .=" map ='{$map}', pic ='{$pic}'";
$query .=" WHERE id ='{$store['id']}'";
$result = $db->query($query);
if($result && $db->affected_rows() === 1){
$session->msg('s',"store updated ");
redirect('store.php', false);
} else {
$session->msg('d',' Sorry failed to updated!');
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
else
{
$session->msg("d", $errors);
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
?>
I Need to store image name when user doesn't upload image.I need to avoid the image name db field becomes empty.
Below quirky will somehow fix your problem; however, this is not the correct way I think;
$query .=" map = IF('{$map}' != '', '{$map}', map), pic = IF('{$pic}' != '', '{$pic}', pic)";
We are just asking the database to update with the exiting column value if the passed value is empty.
The correct way should be not to take it for granted that the user have uploaded a file; as you are doing with these below lines in your code;
$map = $_FILES["mappic"]["name"];
...
$pic = $_FILES["storepic"]["name"];
You should be actually using IF conditions to check if some viable value has been set for those _FILES variables so you know what to process for and what not, and prepare your SQL UPDATE statement accordingly.
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
Basically, the whole thought here is changing profile pictures and it will be uploaded in the database.
I want to show a default icon first when the database is still empty but my codes just displays a broken image thumbnail. What could have gone wrong?
<form method="post" enctype="multipart/form-data">
<div class="row form-group">
<div class="col col-md-3">
<label for="text-input" class="form-control-label">Profile Picture</label>
</div>
<div class="col-9 col-md-9">
<div class="input-group">
<?php
$query = "SELECT image FROM member WHERE member_id = '$ID'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result))
{
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'">';
}
} else{
echo "<img src='images/icon.jpg' style='height:200px'draggable='false'>";
}
?>
<div class="col-12">
<input type="file" name="image" id="image" style ='margin-left:-10px;margin-top:5px'>
</div>
<div class="col-12">
<input type="submit" name="insert" id="insert" value="Change Profile Picture" class="btn btn-primary" style ='margin-left:-10px;margin-top:5px'>
</div>
<?php
if(isset($_POST["insert"])){
$file = addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$query = "UPDATE member SET image = '$file' WHERE member_id='$ID'";
if(mysqli_query($con, $query)){
echo ("<script LANGUAGE='JavaScript'>
window.alert('Profile Picture has been successfully changed!');
window.location.href='edit.php';
</script>");
}
}
?>
</div>
</div>
</div>
</form>
if your database is empty upload query will not work. if your image row is empty then your code should be like if image row is not empty display image else display the default image.
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)) {
if (isset($row['image']) && !empty($row['image'])) {
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'">';
} else {
echo "<img src='images/icon.jpg' style='height:200px'draggable='false'>";
}
} // endwhile
} else{
echo "no result found";
}
While writing HTML or CSS code inside PHP you should put a \ before all double quotations and you need change all quotations to double quotation.like shown below:
echo "<img src=\"images/icon.jpg\" style=\"height:200px;\" draggable=\"false\">";
I didn't check your PHP codes, If you've coded them properly the problem is obviously what I mentioned.
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.
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!