Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFredrik strand
17,207 PointsPHP Video Upload Application - Error message display problems.
Hi Treehouse Community. I am attempting to build a simple application with PHP where people can upload their videos to a directory on the server called "uploads". I built a simple HTML site and PHP upload script, but the problem occurs when running the site on localhost. Several of the error messages in the IF blocks are displayed.
Problem 1: When site is launched on localhost, the error message: "Sorry, this file already exists" AND "Could not upload file" displays on the top of the page before the content, before any action is taken.
Problem 2: When a file is uploaded, the upload works, but the browser displays: "File is ok to upload" AND "Only files of the type 'mp4', 'avi' or 'mov' are allowed to upload." AND "Congratulations, your file: fonna sw front prenose 2.MOV has been uploaded"
Any help would be appreciated.
HTML:
<fieldset>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input id="upfile" type="file" name="fileToUpload" id="fileToUpload">
<br/>
<input class="submit" type="submit" value="Send" name="submit">
</form>
</fieldset>
PHP:
<?php
error_reporting(0);
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$allowed = array("mov", "mp4", "MP4", "MOV", "avi", "AVI");
$ext = pathinfo($target_file,PATHINFO_EXTENSION);
$filename = $_FILES["video_file"]["name"];
// Check if file is video file
if (isset($_POST["submit"])) {
if(!in_array($ext, $allowed) ) {
echo "File is not a movie";
$uploadOk = 0;
} else {
echo "File is ok to upload";
$uploadOk = 1;
}
}
// CHECK IF FILE EXISTS
if (file_exists($target_file)) {
echo "Sorry, this file already exists";
$uploadOk = 0;
}
//ALLOW CERTAIN FORMATS
if ($filename != in_array($ext, $allowed)) {
echo "Only files of the type 'mp4', 'avi' or 'mov' are allowed to upload.";
}
// CHECK IF UPLOAD OK IS SET TO 0 BY ERROR
if ($uploadOk == 0) {
echo "Could not upload file";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "Congratulations, your file: " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded";
} else {
echo "An error occurred while trying to upload your file.";
}
}
?>