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'); ?>
Related
I'm trying to submit a simple form with video files in it, a title and a description. My code works on my laptop that has a 8.1.9 php version and not working on my desktop that has 8.1.0 php version.
I checked this page : Form submit is not sending any POST data but I didn't find any solutions.
I checked php.ini but everything was set normaly... I checked for overlappings tags but didn't find any...
I hope that this is not to obvious...:/
Here is my code :
add-videos.php
<?php
require_once './partials/header.php';
include_once './fetch-videos.php';
?>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<?php if (isset($_SESSION['user_is_admin'])) : ?>
<button id="myBtn">Ajouter une vidéo</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form action="add-videos-logic.php" method="POST" enctype="multipart/form-data">
<label for="video">Fichier vidéo</label>
<input type="file" name="video" /> <br><br>
<label for="title">Titre de la vidéo</label>
<input type="text" name="title" /> <br><br>
<label for="description">Description</label>
<input type="text" name="description" /> <br><br>
<input type="submit" name="submit" value="envoyer">
</form>
</div>
</div>
<?php endif ?>
<?php while ($fetch = mysqli_fetch_array($query)) { ?>
<h2> <?= $fetch['title'] ?> </h2>
<p><?= $fetch['description'] ?></p>
<video width="320" height="240" cont rols>
<source src="<?= $fetch['source'] ?>" data-id="<?= $fetch['id'] ?>">
</video>
<?php if (isset($_SESSION['user_is_admin'])) : ?>
<button><a href="delete-video.php?video_id=<?= $fetch['id'] ?>&source=<?= $fetch['source'] ?>">Supprimer</button>
<button type="submit" name="update" value="modifier"> </button>
<?php endif ?>
<?php } ?>
<?php
require_once './partials/footer.php';
?>
add-videos-logic.php
<?php
require './config/database.php';
date_default_timezone_set('Asia/Manila');
var_dump($_POST);
var_dump(isset($_POST["submit"]));
if (isset($_POST["submit"])) {
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
extract($post);
$file_name = $_FILES['video']['name'];
$file_temp = $_FILES['video']['tmp_name'];
$file_size = $_FILES['video']['size'];
if ($file_size < 50000000) {
$file = explode('.', $file_name);
$end = end($file);
$allowed_ext = array('avi', 'flv', 'wmv', 'mov', 'mp4');
if (in_array($end, $allowed_ext)) {
$name = date("Ymd") . time();
$location = 'video/' . $name . "." . $end;
if (move_uploaded_file($file_temp, $location)) {
mysqli_query($connection, "INSERT INTO `videos` VALUES('', '$name', '$location', '$description', '$title')");
header('location: ' . ROOT_URL . '/admin/add-videos.php');
}
} else {
echo "<script>alert('Wrong video format')</script>";
echo "<script>window.location = 'index.php'</script>";
}
} else {
echo "<script>alert('File too large to upload')</script>";
echo "<script>window.location = 'index.php'</script>";
}
}
file size configuration to modify in php.ini post_max_size was too small.
Sorry for this question.
Adios stackoverflow
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'];
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 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