Ok so I’m working on a photo gallery project and I’m trying to add a photo. I have a page that allows the user to browse for a picture and another input field for adding a title for their picture. The added picture path and title should be added to a xml file where the images are being pulled from.
Also if it helps, I'm using Materialize css. I’m not sure why it’s not working but this is what I currently have:
Form
<form action="../models/addPicture.php" method="POST" enctype="multipart/form-data">
<div class="row center">
<h5>Choose a Photo to Upload</h5>
</div>
<div class="file-field input-field">
<div class="btn-large black">
<span>Browse</span>
<input type="file" />
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload file" name="picFile" />
</div>
</div>
<div class="row">
<div class="input-field">
<input type="text" name="picTitle" class="validate" placeholder="Enter a title for your picture.">
</div>
</div>
<div class="row center">
<button class="btn-large black" type="submit">Add Pic!</button>
</div>
Method:
<?php
if (($_FILES['picFile']['name']!="")){
$target_dir = "../images/";
$file = $_FILES['picFile']['name'];
$path = pathinfo($file);
$filename = $path['basename'];
$ext = $path['extension'];
$temp_name = $_FILES['picFile']['temp_name'];
$path_filename_ext = $target_dir.$filename.".".$ext;
if (file_exists($path_filename_ext))
{
$message = "Added Picture Failed please try again.";
$color = "red-text";
header("Location: ../index.php?Message=".$message."&color=".$color);
}
else
{
move_uploaded_file($temp_name,$path_filename_ext);
$message = "Added Picture Successfully. Please Click Reset to View.";
$color = "green-text";
header("Location: ../index.php?Message=".$message."&color=".$color);
}
}
else
{
$message = "Please enter a picture to submit.";
$color = "red-text";
header("Location: ../index.php?Message=".$message."&color=".$color);
}
?>
I have found a small mistake in your code at line no. 9.
$temp_name = $_FILES['picFile']['temp_name'];
Change the ['temp_name]; to ['tmp_name];
Use this code.
$temp_name = $_FILES['picFile']['tmp_name'];
Related
Update query from the database:
<?php
include 'dpconnection.php';
$uid=$_REQUEST['upid'];
if (isset($_POST['update'])) {
$category= $_POST['category'];
$pname= $_POST['pname'];
$parea= $_POST['parea'];
$pPrices= $_POST['pPrices'];
$pAddress= $_POST['pAddress'];
$filename = $_FILES['new_image']['name'] ;
$tempname = $_FILES['new_image']['tmp_name'] ;
$filesize = $_FILES['new_image']['size'] ;
$fileextension = explode('.', $filename) ;
$fileextension = strtolower(end($fileextension));
$newfilename = uniqid().'images'.'.'.$fileextension ;
$path = "media/".$newfilename ;
$sql = mysqli_query($conn,"UPDATE product SET c_id='$category', p_name='$pname', p_area='$parea', p_prices='$pPrices',p_address='$pAddress', p_thumb_image='$path' WHERE p_id='$uid'");
if (move_uploaded_file($tempname, $path) && $sql) {
echo "<script>alert('Record Updated successfully');</script>";
echo "<script>location.href = 'adminViewProduct.php';</script>";
} else {
echo "Error updating record: " . $conn->error;
}
}
?>
Image not deleting from folder, i have two if statement but just one else statement so it looks like i am missing something but i really don't know what i am missing.
This is form:
<div class="form-group">
<label>Address</label>
<input class="form-control" type="text" name="pAddress" value="<?php echo $row1['p_address'];?>">
</div>
<div class="form-group">
<label>Thumb Image</label>
<input type="file" name="new_image" class="form-control">
<input class="form-control" type="hidden" name="pimage" value="<?php echo $row1['p_thumb_image'];?>">
<img class="float-left" src="<?php echo $row1['p_thumb_image'];?>" width="100px;"><br><br>
</div>
<div class="form-group text-center">
<input class="btn btn-primary" type="submit" name="update" value="Update">
</div>
</form>
You don't have a code that delete the files in php there's a function called unlink where you can delete a files but first you need fetch the path or filename and delete it before updating your data.
Here is the link of unlink.
https://www.php.net/manual/en/function.unlink.php
I made a function to upload an image to my database and upload the image to a folder.
The url in the database changes to the url of the image but the file does not upload to the folder.
I get the error: Undefined index: user_image in image.php
Here is my code:
Image.php
<?php
$edit_row['opzoekImage'] = $_POST["user_image"];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = 'user_images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['opzoekImage']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else
{
$userpic = $edit_row['opzoekImage']; // old image from database
}
?>
New.php
<?php
if(isset($_POST["submit"]) && isset($_GET['website_naam']) && isset($_GET['tbl_name']) && $_GET['tbl_name'] == "tblOpzoek") {
include('config.php');
$website_naam = $_GET['website_naam'];
$sqlWebsiteId = "SELECT websiteId FROM tblWebsite WHERE websiteNaam = '$website_naam'";
if($db->query($sqlWebsiteId) != "") {
$resultWebsiteId = $db->query($sqlWebsiteId);
if ($resultWebsiteId->num_rows > 0) {
// output data of each row
while($row = $resultWebsiteId->fetch_assoc()) {
$websiteId = $row["websiteId"];
}
include('image.php');
$sqlToevoegenType = "INSERT INTO tblOpzoek (websiteId, opzoekName, opzoekValue, opzoekImage) VALUES ('".$websiteId."', '".$_POST["typeNaamToevoegen"]."', '".$_POST["typeWaardeToevoegen"]."', '".$userpic."')";
if($db->query($sqlToevoegenType) === TRUE) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sqlToevoegenType . "<br>" . $db->error."');</script>";
}
} else {
echo "0 results";
}
}
}
?>
My form:
Good to notice I do have more forms with file input name="user_image"
<!-- Type toevoegen-->
<div class="modal fade" id="addType" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="php/new.php?website_naam=<?php echo $websiteNaam ?>&tbl_name=tblOpzoek" method="post" id="formTypeToevoegen">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Type toevoegen</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Type Naam</label>
<input type="text" id="typeNaamToevoegen" name="typeNaamToevoegen" class="form-control" >
</div>
<div class="form-group">
<label>Type Waarde</label>
<input type="text" id="typeWaardeToevoegen" name="typeWaardeToevoegen" class="form-control" >
</div>
<div class="form-group">
<label>Type Afbeelding</label>
<input class="input-group" type="file" id="videoUploadFile" name="user_image" accept="image/*" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>
<button type="submit" name="submit" class="btn btn-primary">Gegevens opslaan</button>
</div>
</form>
</div>
</div>
</div>
Thanks for your time!
You need to add the enctype attribute to your <form> tag
<form enctype="multipart/form-data">
As per your error first check what name you define in input tag because if you define different name in input tag and define different name in $_FILES then it shows error.
So define same name in input tag and $_FILES e.g.
$_FILES['user_image']['name'];
If above are correct then check whether you add enctype="multipart/form-data" in form or not.
I'm trying to submit my Bootstrap form using php so that the data entered into the form is emailed to me from the page. Something somewhere is not working though, and unfortunately my php knowledge is lacking (and web searches have so far brought up nothing of use).
When you click submit the modal which the form is in instantly closes (a default HTML thing?). Re-opening the modal displays the the form error messages if you have left forms blank. If you submit the form with all the content present, nothing happens.
So my question is this: What have I done wrong, and how do I fix it to get the email to send? Also, can I stop the modal from closing when content is submitted but not complete?
EDIT: I have implemented the "correct" php for uploading an image, but it gives me an invalid file type even when they are valid. echo $target_file only returns the file_dir suggesting it is failing to ge the name of the file. What have I done wrong?
Here is the php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$location = $_POST['location'];
$desc = $_POST['desc'];
//Image upload
$target_dir = "/img/gallery/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["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. Please rename your image.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large. Google how to reduce an image size or contact us if you need help with this.";
$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["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$from = 'Gallery Upload Form';
$to = 'email#example.com'; //I've only changed this for stackoverflow
$subject = 'New Gallery Image';
$body = "Name: $name\n Location: $location\n Description: $desc\n \n $file";
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
if (!$_POST['location']) {
$errLocation = 'Please enter where your image was taken';
}
if (!$_POST['desc']) {
$errDesc = 'Please enter a description of your image';
}
if (!$_POST['file']) {
$errFile = 'Please upload your image file';
}
// If there are no errors, send the email
if (!$errName && !$errName && !$errLocation && !$errDesc && $errFile) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! Your image has been submitted.</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later or report this to us.</div>';
}
}
}
?>
And here is the HTML:
<div class="box">
<h2>Upload your picture</h2>
<p>Upload your picture and we'll upload it to the gallery. The best picture each month will be featured as the page background. You can also upload your pictures to our Facebook page with
<font color="darkcyan">#gallery</font>.</p>
<br>
<!-- model content -->
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModalNorm">Upload a Picture</button>
<!-- Modal -->
<div class="modal fade" id="myModalNorm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h3 class="modal-title" id="myModalLabel">Upload Image</h3>
</div>
<!-- Modal Body -->
<div class="modal-body">
<form role="form" method="post" action="index.php">
<div class="form-group">
<label for="name">Your Name</label>
<input class="form-control" placeholder="John Smith" type="text" name="name" required value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" placeholder="South-west bank of Trout Pool." type="text" name="location" value="<?php echo htmlspecialchars($_POST['location']); ?>">
<?php echo "<p class='text-danger'>$errLocation</p>";?>
</div>
<div class="form-group">
<label for="desc">Picture Description</label>
<textarea class="form-control" name="desc" rows="3" placeholder="A picture of a 6lbs trout, my biggest all season."><?php echo htmlspecialchars($_POST['desc']); ?></textarea>
<?php echo "<p class='text-danger'>$errDesc</p>";?>
</div>
<div class="form-group">
<label for="btn-upload">Upload Image File</label>
<input type="file" id="exampleInputFile" name="file" value="<?php echo htmlspecialchars($_POST['file']); ?>">
<?php echo "<p class='text-danger'>$errFile</p>";?>
</div>
<input id="submit" name="submit" type="submit" value="Upload" class="btn btn-primary">
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo $result; ?>
</div>
EDIT: A stupid question - Do you have to configure anything server-side for the email to be sent?
Your uploading a file your html form must have the enctype="multipart/form-data"
attribute.Use $_FILES variable to access information regarding uploaded file.
check these link for more information on $_FILES
http://php.net/manual/en/reserved.variables.files.php
http://www.tutorialsscripts.com/php-tutorials/php-files-variable.php
I am trying to upload video or pictures to my server using php. However I keep getting an error it seems like the file name is empty and I don't understand why, the code keeps executing the script showing an error and nothing is uploaded to my folder
Here is my code:
<div class="container" id="step2-video" style="display:none; margin-top:100px" >
<div class="row">
<div class="col-lg-4 col-md-offset-4">
<form id="video_uploader" action="ad_creator.php" method="post" enctype="multipart/form-data">
<div id="btn-upload-video">
<span class="file-wrapper btn ad-choice">
<input type="file" id="video-file-upload" name="video-file-upload" accept="video/mp4"/>
<span class="button">Choose a video</span>
</span>
</div>
<div id="video-preview" style="display:none" >
<span class="file-wrapper btn ad-choice">
<?php
?>
<input type="submit" name="upload_video" value="Submit" style="margin-left:auto" />
<span class="button">Comfirm</span>
</span>
</div>
</form>
</div>
</div>
</div>
<!--
Step 2 for pictures of the editor
-->
<div class="container" id="step2-picture" style="display:none; margin-top:100px" >
<div class="row">
<div class="col-lg-4 col-md-offset-4">
<form id="picture_uploader" action="ad_creator.php" method="post" enctype="multipart/form-data">
<div id="btn-upload-picture">
<span class="file-wrapper btn ad-choice">
<input type="file" id="picture-file-upload" name="picture-file-upload" accept="image/gif, image/jpeg, image/jpg, image/png"/>
<span class="button">Choose a picture</span>
</span>
</div>
<div id="picture-preview" style="display:none" >
<div id="imagePreview"></div>
<br>
<span class="file-wrapper btn ad-choice">
<input type="submit" name="upload_picture" value="Submit" style="margin-left:auto" />
<span class="button">Comfirm</span>
</span>
</div>
</form>
</div>
</div>
</div>
<?php
if (isset($_POST['upload_picture'])){
$image_name = isset ($_FILES['image']['name']) ? $_FILES['image']['name'] : '' ;
$image_type = isset($_FILES['image']['type']) ? $_FILES['image']['type'] : '';
$image_size = isset($_FILES['image']['size']) ? $_FILES['image']['size'] : '';
$image_tmp_name = isset ($_FILES['image']['tmp_name']) ? $_FILES['image']['tmp_name'] : '';
if($image_name == ''){
echo "<script> alert ('Error occured for picture upload')</script>";
exit();
} else {
move_uploaded_file ($image_tmp_name, "uploads/picture/$image_name");
echo "<script> alert ('sucess for puciture upload')</script>";
}
}
if (isset($_POST['upload_video'])){
$video_name = isset ($_FILES['video']['name']) ? $_FILES['video']['name'] : '' ;
$video_type = isset($_FILES['video']['type']) ? $_FILES['video']['type'] : '';
$video_size = isset($_FILES['video']['size']) ? $_FILES['video']['size'] : '';
$video_tmp_name = isset ($_FILES['video']['tmp_name']) ? $_FILES['video']['tmp_name'] : '';
if($video_name == ''){
echo "<script> alert ('Error occured for video upload')</script>";
exit();
} else {
move_uploaded_file ($video_tmp_name, "uploads/video/$video_name");
echo "<script> alert ('Sucess for video upload')</script>";
}
}
?>
SOLUTION
From Rescaltt, thank you.
I was checking for the wrong file input,
I was checking for $_FILES['image']['name'] instead of $_FILES['picture-file-upload']['name']
Try using a function to do both. Things to note, you should probably do a couple checks and balances:
Sanitize the file name for good measure.
Include your document root for an absolute path or make sure you have the proper relative path.
You may want to check that the upload folder exists and make it if not.
Check success on upload if(move_uploaded_file(...etc.
<?php
function MyUploader($uploadtype = 'picture',$savedir = '/uploads/')
{
$name = (isset($_FILES[$uploadtype.'-file-upload']['name']))? $_FILES[$uploadtype.'-file-upload']['name'] : '' ;
$type = (isset($_FILES[$uploadtype.'-file-upload']['type']))? $_FILES[$uploadtype.'-file-upload']['type'] : '';
$size = (isset($_FILES[$uploadtype.'-file-upload']['size']))? $_FILES[$uploadtype.'-file-upload']['size'] : '';
$tmp_name = (isset($_FILES[$uploadtype.'-file-upload']['tmp_name']))? $_FILES[$uploadtype.'-file-upload']['tmp_name'] : '';
if(empty($name))
return "<script> alert ('Invalid file name.')</script>";
else {
// Make sure you include your ROOT DIRECTORY / correct local path
$upload_dir = $_SERVER['DOCUMENT_ROOT'].$savedir.$uploadtype."/";
// May want to make the directory if not exists
if(!is_dir($upload_dir))
mkdir($upload_dir,0755,true);
// You should check that it worked with if(move_upload_file(...etc
if(move_uploaded_file($tmp_name, $upload_dir.$name))
return "<script> alert ('$uploadtype uploaded successfully')</script>";
else
return "<script> alert ('Could not save file to server.')</script>";
}
}
if(isset($_POST['upload_picture']))
echo MyUploader('picture');
if(isset($_POST['upload_video']))
echo MyUploader('video'); ?>
I have a problem with the function for upload video and images. I can upload images but not video I don' know why. In the and more code for controller and form.
Code in user_models php:
function newp($title,$post,$image,$video,$cat){
$id=$this->session->userdata('userid');
if($video!="")
{
$data=array(
'userid'=>$id,
'title'=>$title,
'forumpost'=>$post,
'categoryid'=>$cat,
'videourl'=>$video
);
}
Image:
else if($image!=""){
$data=array(
'userid'=>$id,
'title'=>$title,
'forumpost'=>$post,
'categoryid'=>$cat,
'imageurl'=>$image
);
}else{
$data=array(
'userid'=>$id,
'title'=>$title,
'forumpost'=>$post,
'categoryid'=>$cat,
);}
$this->db->insert('forum',$data);
}
}
Form:
<form method="post" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/forum/newpk">
<div style="float:left;width: 95%;margin-top:5px;margin-left: 15px">
<h3> Add A Post</h3>
<div class="list-group" >
<input type="text" required name="title" id="title" class="form-control" placeholder="Title of the Post">
</div>
<div class="list-group">
<textarea name="post" class="form-control" style="min-height: 150px;" placeholder="Post">
</textarea>
</div>
<div class="list-group">
<span style="float:left;display:inline-block;"><p style="font-size:15px">Video File</p> <input type="file" name="video" accept="video/*" /></span>
<p style="font-size:15px;margin-left:10%;width: 32px;display:inline-block;">OR</p>
Image File
</div>
<div class="listgroup">
To which category it belongs
<select name="cat"><?php foreach($cato as $cat){ ?><option name="cat" value="<?php echo $cat->categoryid;?>"><?php echo $cat->categoryname;?></option><?php }?></select>
</div>
<div class="list-group" style="margin-top: 70px;margin-left: 35%;">
<button type="submit" style="width: 159px;height: 47px;line-height: 2.3;font-size: 17px;" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
Controller:
public function newpk(){
if($this->session->userdata('userid')){
$title=$this->security->xss_clean($this->input->post('title'));
$post=$this->security->xss_clean($this->input->post('post'));
$cat=$this->security->xss_clean($this->input->post('cat'));
if($cat=="" || $post=="" || $title=="")
{
echo "Required field cannot be empty";
die();
}
$themepicid="";
$this->load->model('forum_model');
Video part:
if(isset($_FILES['video']) && $_FILES['video']['size']>0){
$pktid=$this->idGenerator();
$pathh='assets/video/';
$themepicid=$this->session->userdata('userid');
$type= pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
$pic=$themepicid;
$themepicid=$themepicid.$pktid.".".$type;
move_uploaded_file($_FILES['video']['tmp_name'], $pathh.$themepicid);
$image="";
$this->forum_model->newp($title,$post,$image,$themepicid,$cat); // How the forum likes
Image part:
}
else if(isset($_FILES['image']) && $_FILES['image']['size']>0){
$pathh='assets/images/';
$themepicid=$this->session->userdata('userid');
$type= pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$pktid=$this->idGenerator();
$pic=$themepicid;
$themepicid=$themepicid.$pktid.".".$type;
move_uploaded_file($_FILES['image']['tmp_name'], $pathh.$themepicid);
$image="";
$this->forum_model->newp($title,$post,$themepicid,$image,$cat);
}
else{
$image="";
$this->forum_model->newp($title,$post,$image,$image,$cat);
}
redirect('index.php/forum','refresh');
}
else{
redirect('index.php/user','refresh');
}
}
}
Maybe your video size larger than max size upload config in php.ini
You can use upload library from CI, it's easy to use and help you prevent error
http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
If you using upload lib of CI, dont forget config allowed types