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.
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'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
}
AddStdRecord.php
this is the AddStd record form that i need to get to the addoutput.php the insert it on database
Add Student Information
<form action="AddOutput.php" method="POST" enctype="multipart/form-data"
style="border:1px solid #ccc">
<div class="container">
<b>Select file to upload:</b></br></br>
<input type="file" name="UploadImage" id="UploadImage">
</br></br>
<label><b>Student ID</b></label>
<input type="text" placeholder="Enter Student Number" name="txtID" required>
<label><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="txtLname" required>
<label><b>First name</b></label>
<input type="text" placeholder="Enter First Name" name="txtFname" required>
<label><b>Middle Name</b></label>
<input type="text" placeholder="Enter Middle Name" name="txtMname" required>
<label><b>Birthday</b></label>
<input type="text" placeholder="Enter Birthday" name="txtBday" required>
<label><b>Gender</b></label><br><br>
<input type="radio" name="rbgender" value="Male" checked="checked"><b>Male</b>
<input type="radio" name="rbgender" value="Female"><b>Female </b><br><br>
<label><b>Address</b></label>
<input type="text" placeholder="Enter Address" name="txtAdd" required>
<label><b>Father's Name</b></label>
<input type="text" placeholder="Enter Father's Name" name="txtfather" required>
<label><b>Mother's Name</b></label>
<input type="text" placeholder="Enter Mother's Name" name="txtmother" required>
<label><b>Contact</b></label>
<input type="text" placeholder="Enter Contact Number" name="txtcontact" required>
<label><b>Previous School</b></label>
<input type="text" placeholder="Enter Previous School Attended" name="txtPrev" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" name="submit" class="signupbtn">Add Student</button>
</form></br></br>
</div>
</div>
</form>
AddOutput.php
code to input to the database, whats wrong with this?
include_once('connection.php');
$StdID = $_REQUEST['txtID'];
$Lname = $_REQUEST['txtLname'];
$Fname = $_REQUEST['txtFname'];
$Mname = $_REQUEST['txtMname'];
$Bday = $_REQUEST['txtBday'];
$Gender = $_REQUEST['rbgender'];
$Add = $_REQUEST['txtAdd'];
$Father = $_REQUEST['txtfather'];
$Mother = $_REQUEST['txtmother'];
$Contact = $_REQUEST['txtcontact'];
$PrevSch = $_REQUEST['txtPrev'];
$target_dir = "StdImg/";
$target_file = $target_dir . basename($_FILES["UploadImage"]["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["fileToUpload"]["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["UploadImage"]["size"] > 500000) {
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["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.";
}
}
$sql = "INSERT INTO tblstdpro VALUES ('".$_SERVER['DOCUMENT_ROOT']."\\StdImg\\".$fileToUpload."', '$StdID', '$Lname', '$Fname', '$Mname', '$Bday', '$Gender', '$Add', '$Father', '$Mother', '$Contact', '$PrevSch')";
if ($conn->query($sql) === TRUE) {
header("Location: AddStdRec.php?");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
is there any mistake that i input? it goes to the main folder but doesn't go to the database, i have been searching for days about this function, but cant seem to find one, please comment my mistakes thank you in advance
I have this weird problem with my code:
There are three input file tags. These are upload scenarios and their results:
All three files simultaneously - success
Only picture - Success
Only audio - Failure
Only video - Failure
One picture and one audio - picture succeeds, audio fails
One picture and one video - picture succeeds, video fails
One audio and one video - one of them succeeds
<?php
session_start();
if(!isset($_SESSION["username"])){
header('Location: index.php');
}
if(isset($_POST["year"])){
ini_set('display_errors',1);
error_reporting(E_ALL);
var_dump($_FILES);
$year = $_POST["year"];
$height = $_POST["height"];
$weight = $_POST["weight"];
$school = $_POST["school"];
$class = $_POST["class"];
$target_dir_img = "./pictures/";
$target_dir_aud = "./audios/";
$target_dir_vid = "./videos/";
$uploadOk = 1;
$target_files = array();
$target_img = basename($_FILES['uploadedFiles']['name'][0]);
var_dump($target_img);
if(strcmp($target_img,'')){
$imageFileType = pathinfo($target_img,PATHINFO_EXTENSION);
$newImageName = $target_dir_img . $_SESSION['username']."_".$_POST['year'].".". $imageFileType;
if($imageFileType != "jpg" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
else {
$target_files[] = $newImageName;
}
}
// Allow certain file formats
$target_aud = basename($_FILES['uploadedFiles']['name'][1]);
var_dump($target_aud);
if(strcmp($target_aud,'')) {
$audioFileType = pathinfo($target_aud, PATHINFO_EXTENSION);
$newAudioName = $target_dir_aud . $_SESSION['username']."_".$_POST['year'].".". $audioFileType;
if($audioFileType != "mp3") {
echo "Sorry, only MP3 files are allowed.";
$uploadOk = 0;
}
else {
$target_files[] = $newAudioName;
}
}
$target_vid = basename($_FILES['uploadedFiles']['name'][2]);
var_dump($target_vid);
if(strcmp($target_vid,'')){
$videoFileType = pathinfo($target_vid, PATHINFO_EXTENSION);
$newVideoName = $target_dir_vid . $_SESSION['username']."_".$_POST['year'].".". $videoFileType;
if($videoFileType != "mp4") {
echo "Sorry, only MP4 files are allowed.";
$uploadOk = 0;
}
else {
$target_files[] = $newVideoName;
}
}
var_dump($target_files);
// 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 {
for($i=0; $i<sizeof($target_files); $i++){
if (move_uploaded_file($_FILES['uploadedFiles']['tmp_name'][$i], $target_files[$i])) {
echo "The file ". basename( $_FILES['uploadedFiles']['name'][$i]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
<h1>Welcome <?php echo $_SESSION["username"]; ?>!</h1>
<h2>Data</h2>
<form action="" method="POST" enctype="multipart/form-data">
<p><label>Select Year : </label>
<select id="year" name="year">
<?php
for($i=1901; $i<=2020; $i++){
echo '<option value="'.$i.'">'.$i.'</option>';
}
?>
</select></p>
<p><label>Height : </label>
<input type="text" id="height" name="height" placeholder="Height" /></p>
<p><label>Weight : </label>
<input type="text" id="weight" name="weight" placeholder="Weight" /></p>
<p><label>School : </label>
<input type="text" id="school" name="school" placeholder="School" /></p>
<p><label>Class : </label>
<input type="text" id="class" name="class" placeholder="Class" /></p>
<p><label>Choose picture : </label>
<input type="file" id="picture" name="uploadedFiles[]" accept="image/jpeg, image/jpg" /></p>
<p><label>Choose Audio : </label>
<input type="file" id="audio" name="uploadedFiles[]" accept="audio/mp3" /></p>
<p><label>Choose Video : </label>
<input type="file" id="video" name="uploadedFiles[]" accept="video/mp4" /></p>
<input type="submit" id="submit" name="submit" value="submit" /></p>
</form>
Any inputs on how it may be happening?