Image upload form inside larger form? - php

I have a form that allows users to create events. Inside this form I have a form for an image upload. The HTML looks like this:
<form id="upload_event" method="post" action="system/upload_event.php">
<input type="text" name="title">
<textarea name="description"></textarea>
<form id="upload_image" method="post" action="system/upload_image.php">
<!-- code -->
</form>
Upload event
<input style="display:none" type="submit" id="submit_upload_event" name="submit_upload_event">
</form>
This is what my upload_image.php, which processes the image upload, looks like:
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
As I found out, it is not possible to nest a form into another one. What would be the solution here?

If you're using Ajax you could return a value from your upload form to your main form. Like putvande said you can't have a form inside a form.

Related

Unable to bring uploaded images into uploads file using php

After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.
Here is the HTML
<form action="" class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Find Art Here">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
and here's the php
<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allow = array('jpg', 'jpeg', 'png', 'pdf');
if (in_array($fileActualExt, $allow)) {
if($fileError === 0){
if($fileSize < 5000000) {
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uplaods/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: index.php?uploadsucess");
} else{
echo "Your file is too big";
}
} else {
echo "There was an error uplaoding your file!";
}
} else{
echo "You cannot upload files of this type!";
}
}
Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk
Any help would be much appreciated!
in your form add this
enctype="multipart/form-data"
example
<form method="post" class="login-form" enctype="multipart/form-data"
action="my.php">
1) Add enctype="multipart/form-data" in your form tag.
2) fileDestination = 'uplaods/'.$fileNameNew;spelling mistake on file name. (If it is intentional, then my bad).
3) <input type='file'> type should be file.
how did you communicate with $_FILES? You need to use
type="file" in your input
The first thing you have to do is adding enctype="multipart/form-data" and method="post" to your form-tag:
<form action="" method="post" enctype="multipart/form-data">
If it then still doesn't work, check the upload_max_filesize and the post_max_size settings in your php.ini. If your file is too big, only move_uploaded_file() will return false, so check that function as well.
Your <form> misses an attribute to send files:
enctype="multipart/form-data"
And to be sure the upload is done, put the move_uploaded_file() in a condition because the function returns a boolean :
if (move_uploaded_file($fileTmpName, $fileDestination)) {
header("Location: index.php?uploadsucess");
} else {
header("Location: index.php?uploadfail");
}
Also, a better way to get your file extension is using pathinfo() :
pathinfo($fileName, PATHINFO_EXTENSION);
you don't have any <input type="file"> in your form
you maybe mispelled your upload directory : uplaods
php.net - move_uploaded_file()
php.net - pathinfo()

"Undefined index: data" error in php

I have the following form that allows user to upload the image:
<form name='form1' method="POST" action="" id="registration_form">
<input type="file" name="data" id="data">
<input type="Submit" name="Upload1" value="Upload1">
</form>
And following php code that does the actual upload:
<?php if(isset($_POST['Upload1']))
{
$errors=array();
$allowed_ext= array('pdf','jpg','jpeg');
$file_name =$_FILES['data']['name']; //error shows in this line
$file_ext = strtolower( end(explode('.',$file_name)));
$file_size=$_FILES['data']['size'];
$file_tmp= $_FILES['data']['tmp_name'];
$type = pathinfo($file_tmp, PATHINFO_EXTENSION);
$data = file_get_contents($file_tmp);
if(in_array($file_ext,$allowed_ext) === false){
$errors[]='Extension not allowed';
}
if($file_size > 2097152){
$errors[]= 'File size must be under 2mb';
}
if(empty($errors))
{
if( move_uploaded_file($file_tmp, 'images/'.$file_name));
{
$ct='application/' .$file_ext.'<br/>' ;
$base64 = base64_encode($data);
//json part is here
}
}
else {
foreach($errors as $error) {
echo $error , '<br/>';
}
}
}
When I select the file and hit "UPLOAD", it shows error as "Undefined index: data". But what is interesting to note is that 1 out of 10 times, it works! Where am I doing wrong?
According to your form you are not using multiparty/form-data in form tag.
You just need to use
enctype="multipart/form-data" 
Inside the form tag for input type file.
Example:
<form enctype="multipart/form-data">
Why it's needed? Why is form enctype=multipart/form-data required when uploading a file?
If you are using JavaScript for submit the form than you can use formData for getting data from input either post or file.
var formData = new FormData(formId);

Issue with uploading multiple files on a single html page using php

I am trying to build a web page where users can edit images portrayed on their public pages. There are 3 images that display on their public page and I've set up 3 HTML forms in order to handle the 3 separate files.
I only have 1 listed below because once I figure out the fix to 1 I'll be able to duplicate the fix to the other 2,
I have other upload pages on my website and they work fine, but for some reason this page is giving me trouble. I can select a file but when I want to upload it my php code doesn't read that there is anything being posted.
*I've commented out the function call (I know it works) I just need to know why my php code won't read that there is a file there.
If I had to guess it'd be something with how it's named or how it's being tossed to the php code.
The code looks like this:
<div class="academic" style="width:250px;">
<br>
<?php
if(isset($_FILES['aca']) === true)
{
echo 'please print'; //It doesn't
if(empty($_FILES['aca']['name']) === true)
{
echo 'Please choose a file! <br>';
}
else
{
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['aca']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['aca']['tmp_name'];
echo '<br>';
echo '<br>';
print_r($_FILES['aca']['tmp_name']);
echo '<br>';
echo '<br>';
if(in_array($file_extn, $allowed) === true) {
//upload_image($file_temp,$file_extn);
echo 'You have uploaded a picture!';
echo '<b><h3>Press submit again to finish the upload</h3></b>';
//echo "<script>window.top.location='../hidden/viewPNM.php?id=$permi'</script>";
}
else
{
echo 'Incorrect File Type!! <br> Allowed: ';
echo implode(', ', $allowed);
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="aca" id="aca">
<input type="submit" value="Upload">
</form>
</div>
</span>
Okay...here is what you can try to do:
Move the whole PHP code UNDER the form code. I remember that sometimes wierd bugs with that were happening, and the code didnt run
If that doesnt work, do following:
Change <input type="file" name="aca" id="aca"> to <input multiple="true" type="file" name="aca[]" />
Add this code above the submit button: <input type="hidden" name="sendfiles" value="Send Files" />
Replace if(isset($_FILES['aca']) === true) with if(isset($_POST['sendfiles']))
If this doesn't work, I can offer you a way to allow multiple files being uploaded from one button. (Took the code from my website I made before)

PHP-Jquery image upload not working

I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot

uploading a file server side

Below is my code where the user can upload a file. What I want to know is that is there a way so that via server side is there a way to first of all restrict the file formats of the files to jpeg and png only and then when the user clicks on the submit button, if the file format is correct then display an alert on the same page stating "File is correct" else display an alert stating "File is incorrect".
Can somebody please provide coding if they know how to do this. Thank you and any help will be much appreciated :)
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
A code for a total check of file uploads, you'll have to change $allowedtypes though. (Copied instead of linking because it was from a non-English site)
<?php
if(isset($_POST["submit"])){
$allowedtypes=array("jpg"=>true,"png"=>true,"gif"=>true,"txt"=>true);
$filename = $_FILES['file1']['name'];
$source = $_FILES['file1']['tmp_name'];
$file_size=$_FILES['file1']['size'];
$saveloc = "uploads/" . $filename;
$maxfilesize=1024*1024*10;
$nameext=explode(".",$filename);
if(preg_match('/^[A-Za-z0-9\-\_]{1,}\.[a-zA-Z0-9]{0,4}$/',$filename)){
if(!empty($allowedtypes[strtolower($nameext[1])]) && $allowedtypes[strtolower($nameext[1])]===true){
if($file_size<=$maxfilesize){
if(!file_exists($saveloc)){
if(move_uploaded_file($source, $saveloc)) {
chmod($saveloc,644);
echo "Successful upload. <a href='".$saveloc."'>Fájl megtekintése</a>";
}
else echo "Cannot move";
}
else echo "Existing file";
}
else echo "Too big file";
}
else echo "Not allowed extension";
}
else echo "Only alphanumeric files allowed";
}
else echo "<form method='post' enctype='multipart/form-data' action='secureupload.php'> File: <input type='file' name='file1' /><br /><input
name='MAX_FILE_SIZE' type='hidden' value='10485760' /> <input type='submit' value='Upload' name='submit' /></form>";
?>
You are talking about server side handler and write 'alert'...khm...
If u want to do stuff via server-side, then use php handler
http://php.net/manual/en/features.file-upload.post-method.php
If u want to do stuff via client-side, use javascript events, e.g on change event
<script>
function check() {
var file = document.getElementById('file').value;
var temp = file.split(/\.+/).pop();
alert(temp);
}
</script>
<input type="file" name="file" id="file" onchange="check();" />
You have file extension in temp var.
There are PHP functions to do this. You want to look at mime_content_type and finfo_file. These are built-in PHP commands that allow you to interpret that actual file type of a file being uploaded. You can then filter the mime types to only .gif/.jpg/etc. You want to check the mime types over the file name because the file name can be changed to mask the actual file type. If you want code samples, there are plenty on those pages as well as some excellent user-provided alternatives.
Something like this at the top of your file should work:
<?php
foreach ($_FILES as $file)
{
$tmp = explode(".", $file["tmp_name"]);
if (!in_array($tmp[count($tmp)-1], array("jpeg", "png"), true))
die("<script>alert('File is incorrect');</script>");
}
echo "<script>alert('File is correct');</script>";
?>

Categories