PHP does not upload image file to folder - 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.

Related

Users can't upload files using mobile phones

I have a form where parents can upload files (their child's completed homework) to be received by teachers.
However, I have been getting a lot of complaints that they can't upload files when they use their mobile phones. When they click on the save button, nothing happens.
Thing is when I (superadmin) and teachers upload from our pages using either pc or mobile phones, it uploads without hitches.
Why can't parents upload files, especially with their mobile phones.
I don't know if this is a coding issue or a server issue.
For now, I use a shared cloud hosting with 4 CPU Cores, 4GB DDR4 RAM, Unlimited Bandwidth and Unlimited SSD Space.
model
public function upload_docs($data)
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$q = $this->db->get('submit_assignment');
if ( $q->num_rows() > 0 )
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$this->db->update('submit_assignment',$data);
} else {
$this->db->insert('submit_assignment',$data);
}
}
// public function upload_docs($data)
// {
// if (isset($data['id']) && $data['id'] != null) {
// $this->db->where("id", $data["id"])->update("submit_assignment", $data);
// return $data['id'];
// } else {
// $this->db->insert("submit_assignment", $data);
// return $this->db->insert_id();
// }
// }
controller
public function upload_docs()
{
$homework_id = $_REQUEST['homework_id'];
$student_id =$_REQUEST['student_id'];
$data['homework_id'] = $homework_id;
$data['student_id'] = $student_id;
$data['message'] = $_REQUEST['message'];
// $data['id']=$_POST['assigment_id'];
$is_required=$this->homework_model->check_assignment($homework_id,$student_id);
$this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required|xss_clean');
$this->form_validation->set_rules('file', $this->lang->line('attach_document'), 'trim|xss_clean|callback_handle_upload['.$is_required.']');
if ($this->form_validation->run() == FALSE) {
$msg=array(
'message'=>form_error('message'),
'file'=>form_error('file'),
);
$array = array('status' => 'fail', 'error' => $msg, 'message' => '');
}else{
if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {
$time = md5($_FILES["file"]['name'] . microtime());
$fileInfo = pathinfo($_FILES["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($_FILES["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$_FILES["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
public function handle_upload($str,$is_required)
{
$image_validate = $this->config->item('file_validate');
if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {
$file_type = $_FILES["file"]['type'];
$file_size = $_FILES["file"]["size"];
$file_name = $_FILES["file"]["name"];
$allowed_extension = $image_validate['allowed_extension'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$allowed_mime_type = $image_validate['allowed_mime_type'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mtype = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
if (!in_array($mtype, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'File Type Not Allowed');
return false;
}
if (!in_array($ext, $allowed_extension) || !in_array($file_type, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'Extension Not Allowed');
return false;
}
if ($file_size > $image_validate['upload_size']) {
$this->form_validation->set_message('handle_upload', $this->lang->line('file_size_shoud_be_less_than') . number_format($image_validate['upload_size'] / 1048576, 2) . " MB");
return false;
}
return true;
} else {
if($is_required==0){
$this->form_validation->set_message('handle_upload', 'Please choose a file to upload.');
return false;
}else{
return true;
}
}
}
view
<td class="mailbox-date pull-right">
<a onclick="upload_docs('<?php echo $homework['id']; ?>', '<?php echo $upload_docsButton; ?>');" class="btn btn-default btn-xs" data-toggle="tooltip" data-original-title="<?php echo $this->lang->line('homework') . " " . $this->lang->line('assignments'); ?>">
<i class="fa fa-upload"></i></a>
<a class="btn btn-default btn-xs" onclick="evaluation('<?php echo $homework['id']; ?>','<?php echo $hw;?>');" title="" data-target="#evaluation" data-toggle="modal" data-original-title="Evaluation">
<i class="fa fa-reorder"></i></a>
</td>
<div class="modal fade" id="upload_docs" tabindex="-1" role="dialog" aria-labelledby="evaluation" style="padding-left: 0 !important">
<div class="modal-dialog" role="document">
<div class="modal-content modal-media-content">
<div class="modal-header modal-media-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="box-title"><?php echo $this->lang->line('homework'); ?> <?php echo $this->lang->line('assignments'); ?></h4>
</div>
<form id="upload" method="post" class="ptt10" enctype="multipart/form-data">
<div class="modal-body pt0">
<div class="row">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" id="homework_id" name="homework_id">
<input type="hidden" id="assigment_id" name="assigment_id">
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('message'); ?></label>
<textarea type="text" id="assigment_message" name="message" class="form-control "></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('attach_document'); ?></label>
<input type="file" id="file" name="file" class="form-control filestyle">
</div>
</div>
<p id="uploaded_docs"></p>
</div>
</div>
<div class="box-footer">
<div class="" id="footer_area">
<button type="submit" class="btn btn-info pull-right" id="submit" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Please wait"><?php echo $this->lang->line('save'); ?></button>
</div>
Your view is mess.
First add form action then add button form attribute like this:
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text='SOME TEXT'> Please wait<?php echo $this->lang->line('save'); ?></button>
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="upload_docs">

Photo Gallery: Adding Photos

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'];

PHP FileUpload is not working

I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.

Submitting a bootstrap form not working

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

Upload video or picture with 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'); ?>

Categories