I'm currently developing a website where users can upload their music. You can set various genres to display. Now, the problem is that sometimes (no idea why) the upload fails for certain files. An error doesnt get displayed. It's definitely not a permission error, since the uploading works for most files.
I've looked around a lot here already and tried many things, but nothing worked for me.
Here's my code:
HTML
<form method="post" action="musicupload.php" enctype="multipart/form-data">
Choose an MP3 or WAV file<file></file>
<br /><br />
<input type="file" name="fileToUpload" id="fileToUpload" required>
<br /><br />
<fieldset>
Genre
<br />
<input type="radio" id="db" name="Genre" value="Dubstep" required checked>
<label for="db"> Dubstep</label>
<input type="radio" id="trap" name="Genre" value="Trap" required>
<label for="trap"> Trap</label>
<input type="radio" id="BB" name="Genre" value="Bass Boosted" required>
<label for="bb"> Bass Boosted</label>
<input type="radio" id="other" name="Genre" value="Other" required>
<label for="other"> Other</label>
</fieldset>
<br />
<input type="submit" value="Upload Song" name="submit">
</form>
PHP
<?php
/**
* Created by IntelliJ IDEA.
* User: Marc
* Date: 04.12.2017
* Time: 20:07
*/
require 'db.php';
$target_dir = "uploadedmusic/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$filename=$_FILES["fileToUpload"]['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$genre = $_POST["Genre"];
$successfull = false;
if(isset($_POST["submit"])) {
// Check extensions
if ($ext != "mp3" && $ext != "wav") {
echo "Sorry, only MP3 & WAV files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$hash = md5_file("uploadedmusic/".$filename);
//echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
$sql = "INSERT INTO `music` (`id`, `filename`, `genre`, `uploaded`, `hash`) VALUES (NULL, '$filename', '$genre', CURRENT_TIMESTAMP, '$hash')";
$conn->query($sql);
$successfull = true;
} else {
$successfull = false;
}
}
}
?>
<html>
<head>
<title>Upload Music</title>
</head>
<body>
<div style="text-align: center;">
<img src="logo.png">
<h1>Please wait...</h1>
<p style="font-size: 35px;">
<?php
if ($successfull == true) {
echo "Successfully uploaded ". basename($_FILES["fileToUpload"]["name"])."! Use the search to find it!";
}
else {
echo "Sorry, there was an error uploading your file. Check for potential invalid characters like () or - in your filename!";
}
?>
</p>
<a style="font-size: 35px" href="main.php">Start listening!</a>
</div>
</body>
</html>
You need to see file upload errors to find the exact issue.
echo $_FILES["fileToUpload"]["error"] // this will give you the error code.
Possible errors are. check this link http://php.net/manual/en/features.file-upload.errors.php
$phpFileUploadErrors = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
Also in your code apart from checking extension, you need add condition to check upload errors
if ($uploadOk == 0 || $_FILES["fileToUpload"]["error"]!== UPLOAD_ERR_OK) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
Related
i try to make a form where users can upload a resource with a thumbnail, 3 preview images and a .rar, .zip file.
The form works and creates me a post in my custom post type.
The image so far gets uploaded too in my uploads folder.
but im not able to set the uploaded image as the featured image of the new created post.
i found alot of solutions that should work, but i cant get it to work.
Maybe someone can tell me how to do it properly :)
Below is my code that creates me the new post and saves the image in my uploads folder.
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_resource") {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'community-resources' //'post',page' or use a custom post type if you want to
);
//save the new post
$pid = wp_insert_post($new_post);
wp_redirect(get_permalink($pid)); exit;
//insert taxonomies
$target_dir = "uploads/community/";
$target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["thumbnail"]["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.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["thumbnail"]["size"] > 10000000) {
echo "Sorry, your file is too large.";
$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["thumbnail"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["thumbnail"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
add_post_meta($pid, '_thumbnail_id', $attach_id);
}
} ?>
and here is my form:
<div id="upload_resource_wrapper" class="container">
<form method="post" enctype="multipart/form-data" id="new_resource" name="new_resource">
<label for="title">Title:
<input id="title" tabindex="1" name="title" size="20" type="text" value="" placeholder="Name of resource">
</label>
<label for="description">Description:<br>
<textarea id="description" tabindex="3" cols="50" name="description" rows="6" placeholder="Some text about the resource"></textarea>
</label>
<label for="Category">Category:<br>
<?php wp_dropdown_categories( 'tab_index=3&taxonomy=category' ); ?>
</label>
<label for="model_file">Upload the file here:<br>
<input accept="zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" name="model_file" size="50" type="file">
</label>
<label for="thumbnail">Upload the main thumbnail<br>
<input accept=".png, .jpg, .gif, .jpeg. ,webp" name="thumbnail" size="50" type="file">
</label>
<label for="first_preview">Upload the first preview<br>
<input accept=".png, .jpg, .gif, .jpeg. ,webp" name="first_preview" size="50" type="file" />
</label>
<label for="second_preview">Upload the second preview<br>
<input accept=".png, .jpg, .gif, .jpeg. ,webp" name="second_preview" size="50" type="file" />
</label>
<label for="third_preview">Upload the third preview<br>
<input accept=".png, .jpg, .gif, .jpeg. ,webp" name="third_preview" size="50" type="file" />
</label>
<label for="post_tags">Tags<br>
<input id="post_tags" tabindex="5" name="post_tags" size="16" type="text" value="">
</label>
<p>
<input action="new_resource" id="submit" tabindex="6" name="submit" type="submit" value="Publish" />
</p>
<input name="action" type="hidden" value="new_resource" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
I tryd to use
"add_post_meta($post_id, '_thumbnail_id', $attach_id);"
but dont know how to get the thumbnail id.
i also tried:
"wp_insert_attachment( $attachment(dont get this),
$_FILES["thumbnail"]["tmp_name"], 209 );
i got nothing to work :(
I've created a basic upload form and everything works fine to upload, but I'm unable to find a way to add the file description to the page. I'd like it to go here under "Description":
uploads page
HTML Form:
<form action="/scripts/upload.php" method="POST" enctype="multipart/form-data">
Select a file to upload:
<input type="file" name="fileToUpload" id="fileToUpload"><br />
<textarea id="FileDescription" name="FileDescription" rows="1" placeholder="*File description" required></textarea> <br />
<input type="submit" value="Upload File" name="submit">
Script:
<?php
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$df = disk_free_space("../uploads/");
if (isset($_POST["submit"])) {
$check = filesize($_FILES["fileToUpload"]["tmp_name"]);
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > $df) {
echo "Sorry, your file is too large.";
$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["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has
been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The <textarea> tag must be linked to the form.
Use it this way:
<form action="/scripts/upload.php" id="myForm" method="POST" enctype="multipart/form-data">
Select a file to upload:
<input type="file" name="fileToUpload" id="fileToUpload"><br />
<textarea id="FileDescription" form="myForm" name="FileDescription" rows="1" placeholder="*File description" required></textarea> <br />
<input type="submit" value="Upload File" name="submit">
</form>
Only then, the content of the texarea is transferred. You can access the description then with $_POST["FileDescription"]. To use it as the Apache description, see http://httpd.apache.org/docs/2.2/mod/mod_autoindex.html#adddescription
I am trying to upload files to the directory but I keep getting error or console
GET http://localhost:9999/store/uploads/.jgp
Whilst my html is
<form action="" method="POST" id="formSettingStoreLogo" enctype="multipart/form-data">
<div>
<p>Put a logo </p>
<br />
<input type="file" name="logo" />
<input type="submit" name="submitLogo" id="submitLogo" value="Upload" />
</div>
</form>
And code of php is
$target_dir = "../uploads/store/logo/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["logo"]["name"], $target_file)) {
echo "\n"."The file ". basename( $_FILES["logo"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
For further information
My script for uploading images is at
C:/wamp64/www/store/settingstore.php
And the location I want to upload photos are
C:/wamp64/www/uploads/store/logo
This question already has an answer here:
PHP file uploads doesnot read $_FILES['image'] [duplicate]
(1 answer)
Closed 7 years ago.
Hello I'm trying to create a form which includes an upload file input.
My form is sending data to my database while the file uploaded is stored in the img folder.
Now the form without the upload input works fine. The upload script without the form works fine too. But I can't manage to make them work together. I tried to include the "upload script" in my main form script but it didn't worked. I actually don't khow how this procedure should be done.
What I would like to do is that when I submit the form the data goes in the database and the upload file in my img folder. I think the problem comes somehow from the submit button.
Sorry for posting all my code but I think it's necessary to understand...
This is my addOutfit.php (which sends the data of my form to my database)
require("ajax/db.php");
$message = " ";
if ( $_POST ) {
if (!empty($_POST['type'])){
$title = htmlspecialchars($_POST['title']);
$description = htmlspecialchars($_POST['description']);
$brand = htmlspecialchars($_POST['brand']);
$material = htmlspecialchars($_POST['material']);
$type = htmlspecialchars($_POST['type']);
$color = htmlspecialchars($_POST['color']);
$sql = "INSERT INTO outfit (title, description, brand, material, type, color) VALUES('$title', '$description', '$brand', '$material', '$type', '$color')";
$statement = $pdo->prepare($sql);
$statement->execute(['title' => $title, 'description' => $description, 'brand' => $brand, 'material' => $material, 'type' => $type, 'color' => $color]);
$message = "The item has been added";
} else {
$message = "The type field is compulsory";
}
}
?>
<!--AddOutfit form-->
<div class="container-fluid" id="addOutfitForm" >
<div class="col-xs-12 col-md-10">
<form action ="addOutfit.php" method="post" novalidate>
<?php if ( $message ) { ?>
<h3 style="color: red;"><?=$message?></h3>
<?php } ?>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
<div class="form-group">
<label for="type">Type</label>
<input type="text" class="form-control" name="type">
</div>
<div class="form-group">
<label for="brand">Brand</label>
<input type="text" class="form-control" name="brand">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color">
</div>
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material">
</div>
<div class="form-group" action="upload.php" method="post" enctype="multipart/form-data">
<label for="fileToUpload">Picture</label>
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<button type="submit" class="btn btn-default" name="submit" value="Upload Image">Send</button>
</form>
</div>
This is my upload.php (my uploading documents script)
<?php
$target_dir = "img/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
Your approach is confusing a bit. You need to check if you have POST request to store the data inside db and check also if you have a file to upload it
if(isset($_POST)) {
// validate and insert the data into db
// if isset $_FILES["fileToUpload"] update the file
if(isset($_FILES) && isset($_FILES["fileToUpload"]['name'])) {
}
}
Also don't forget to add the enctype="multipart/form-data" attribute to the form
<form action ="addOutfit.php" enctype="multipart/form-data" method="post" novalidate>
I think that you just need to add the enctype="multipart/form-data" attribute to your <form> tag.
See http://www.w3schools.com/tags/att_form_enctype.asp
Submitting files only works when the form data is submitted as multipart.
Instead of
<div class="form-group" action="upload.php" method="post" enctype="multipart/form-data"> <label for="fileToUpload">Picture</label>
Have you tried:
<form action ="addOutfit.php" method="post" enctype="multipart/form-data" novalidate>
I'm currently coding the most basic file upload to go to our server from an input type="file" attribute. This is my HTML:
<form enctype="multipart/form-data" action="register-complete.php" method="post">
<h5>Register Now</h5>
<input type="text" class="form-control" name="Username" placeholder="Login Name"/><br />
<input type="text" class="form-control" name="Displayname" placeholder="Display Name"/><br />
<input type="text" class="form-control" name="Email" placeholder="Email" /><br />
<input type="radio" name="Paypal" value="1" /> This is my Paypal email.<br />
<input type="radio" name="Paypal" value="0" /> I do not want payment. I wish to preserve anonymity.<br /><br />
Avatar Picture: <br /><input type="file" name="AvatarPicture" id="AvatarPicture" />*500kb max file size.<br />*Accepted filetypes: .jpg, .png<br /><br />
<input type="text" class="form-control" name="Description" placeholder="Account Description"/><br />
<input type="password" class="form-control" name="Password" placeholder="Password"/><br />
<input type="password" class="form-control" name="PasswordConfirm" placeholder="Confirm Password"/><br />
<p class="text-center"><input type="submit" class="btn btn-primary" value="Register" name="submit" /></p>
</form>
Basically I'm just concerned with the AvatarPicture input, and just get it to upload a file to my server. Here is the PHP code I have to do that.
$username = $_REQUEST["Username"];
$displayname = $_REQUEST["Displayname"];
$email = $_REQUEST["Email"];
$paypal = $_REQUEST["Paypal"];
$target_dir = "images/avipictures/";
$target_file = $target_dir . basename($_FILES["AvatarPicture"]["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["AvatarPicture"]["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.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["AvatarPicture"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG 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["AvatarPicture"]["tmp_name"],$target_file)) {
echo "The file has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
This is literally the same exact thing as the w3schools code to the tee. However I am receiving an internal server 500 error unless I change the "tmp_name" in the move_uploaded_file() to "name", which just leads to the else statement. I've been messing around with this all day and I have just been tearing my hair out at just how simple this bit of code should be but doesnt seem to be at all. Any ideas? (Also, the file_uploads is set to on and the default largest file size is set to 50mb.)
I can't tell what the problem is without a decent log file, but it could be that the directory you're trying to write to doesn't exist or you don't have permission to write to it. Are you sure that the images/avipictures/ directory that you're trying to write to exists, and that the webserver has permission to write to it? If not, you'll need to create the directory and set the permissions on it such that the webserver can write to it.