I'm making an uploader for a website which is designed to upload videos. As of now, it doesn't check if they're videos, it's simply uploads them. I do this through a simple form that selects a file and submits it to upload.php. Here is the HTML which I do this with:
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();">
Video Name: <input type="text" name="name" class="maininput" style="width:300px;" maxlength="80"><br>
File: <input name="myfile" type="file" class="mainbutton"/ style="clear:both;"><br>
Description: <br><textarea cols="43" rows="10"></textarea><br>
<input type="submit" name="submitBtn" value="Upload" class="mainbutton"/>
</form><br><br><br>
<p id="f1_upload_process">Loading...<br/><img src="/images/loader.gif" width="20" height="20" /></p>
<p id="result"></p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;">
<script language="javascript" type="text/javascript">
window.top.window.stopUpload(<?php echo $result; ?>);
</script> </iframe>
Here are my javascript functions which accompany this:
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
document.getElementById('result').innerHTML =
'<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
document.getElementById('result').innerHTML =
'<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
return true;
}
And finally, here is the contents of upload.php, which I use for actually uploading the file:
<?php
$result = 0;
$target_path = "videos/";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
I believe that the issue is with the upload.php. The problem is not with anything client side, it's the fact that in the client, it uploads the file, but I can't find the file in the videos folder, or any folder in the server directory.
Any help is greatly appreciated. Thanks!
This is what I use, you can customize it to suit your script:
Simply change the *path and *variables.
<?php
// Configuration - Your Options
$allowed_filetypes = array('.mov','.mp3','.mp4','.flv'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './files/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
?>
Related
I try to upload a file with PHP and I use the function "move_uploaded_file()" for it. Everything works well, until I try to upload a zipped CSV file. The file itself is 50MB, but once it is zipped, it's just 3MB. I can upload files until 5MB to the server, so in the case of the zip file, I thought this would work, but it doesn't.
* Uploading a zipped CSV file of 100kb does work,
* I did delete 1/3 of the lines from the CSV file, the CSV file is 28MB, and this I could upload (zipped it was 1.6MB),
* The zipped file of 3MB doesn't appear in the folder on the server. The zipped files of 100KB and 1.6MB do appear there,
* I didn't get an error message, but it does echo "Error uploading!".
Did someone face the same problems, or does someone knows a solution? Let me know! This is basicly my code;
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_POST["submit"])) {
$file = $_FILES["file"];
$filename = $file["name"];
$target_dir = "data/";
$target_file = $target_dir . basename($filename);
$file_type = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (move_uploaded_file($file["tmp_name"], $target_file)) {
echo "Done uploading!";
} else {
echo "Error uploading!";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="file" name="file" required accept=".csv,.zip" />
</div>
<p class="text-right">
<button class="btn btn-primary" name="submit" type="submit">Upload!</button>
</p>
</form>
Let me know if you need something. All the help and ideas are appericiated. Thanks!
Edit;
I did got an error in $_FILES['file']['error'];
I got error "1", which reffers to: 'The uploaded file exceeds the upload_max_filesize directive in php.ini'
https://www.php.net/manual/en/features.file-upload.errors.php
I did "echo phpinfo();", and found out that upload_max_filesize is only 2MB instead of the 5MB that I thought I configurated.
The footer is included in the index file with the include code leading to this page like this
<?php include "footer.php" ?>
<center><div id="content"><br>
<form method="post" enctype="multipart/form-data">
<input type="file" class="file" name="userfile"/><br>
<br>
<button name="upload" type="submit" value="Submit" class="upload">Upload</button>
</form>
<?php
if(isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg','.jpeg','.png','.gif');
$max_filesize = 10485760;
$upload_path = 'useruploads/';
$description = $_POST['imgdesc'];
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('<h4>The file you attempted to upload is not allowed.');
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('<h4>The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('<h4>You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
$query = "INSERT INTO uploads (name, description) VALUES ($filename, $description)";
mysql_query($query);
echo '<h5>Your file upload was successful!';
} else {
echo '<h4>There was an error during the file upload. Please try again.';
}
}
?>
</div>
If you want to see for you're self i have temporary uploaded this script to my site so you can see the error for you're self try and upload something that is not a image file and you will see the error, and i was seeing if it was possilbe to add a button after the upload is complete to link it to the image
Website Link
Here is also the footer code
<center><div id="footer">
<p>Copyright © OSPICTUREVAU 2014</p>
</div>
You are using die to output your errors which will stop execution of all code after the die statement. This means that your footer code is never executed.
Redirecton error:
if (!in_array($ext, $allowed_filetypes))
{
header("Location: errorpage.php");
exit;
}
You could pass error codes to the errorpage.php to give the user a meaningful error message.
I am trying to upload a video and save it in a folder as well as savings its path in the database, but the videos are not inserting into the specific folder.
I have searched a lot and found some code. The code is working for images. I have done some modifications from images to videos, but that didn't work.
Here is the parts of my code.
<form action="" method="post" enctype="multipart/form-data">
<div class="form_search">
<label>Upload Video Profile:</label>
<span class="form_input">
<input type="file" name="uploadvideo" />
</span>
</div>
<div class="form_search">
<label> </label>
<span class="form_input">
<input type="submit" name="submitdetails" value="Upload" class="button"/>
</span>
</div>
</form>
and my php code to upload video is
<?php
if(isset($_POST['submitdetails']))
{
$name=$_FILES['uploadvideo']['name'];
$type=$_FILES['uploadvideo']['type'];
//$size=$_FILES['uploadvideo']['size'];
$cname=str_replace(" ","_",$name);
$tmp_name=$_FILES['uploadvideo']['tmp_name'];
$target_path="company_profile/";
$target_path=$target_path.basename($cname);
if(move_uploaded_file($_FILES['uploadvideo']['tmp_name'],$target_path))
{
echo "hi";
echo $sql="UPDATE employer_logindetails SET (video) VALUES('".$cname."')";
$result=mysql_query($sql);
echo "Your video ".$cname." has been successfully uploaded";
}
}
?>
Please help me where I am going wrong.
All my php.ini modifications are done, and video size is only 7mb.
Step-1
This script will allow you to upload files from your browser to your hosting, using PHP. The first thing we need to do is create an HTML form that allows people to choose the file they want to upload.
<form enctype="multipart/form-data" action="upload.php" method="POST">
Please choose a file: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
This form sends data to the file "upload.php", which is what we will be creating next to actually upload the file.
Step-2
The actual file upload is very simple:
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
?>
This very small piece of code will upload files sent to it by your HTML form.
The first line $target = "upload/"; is where we assign the folder that files will be uploaded to. As you can see in the second line, this folder is relative to the upload.php file. So for example, if your file was at www.yours.com/files/upload.php then it would
upload files to www.yours.com/files/upload/yourfile.gif. Be sure you remember to create
this folder! with 777 rights
Step-3
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
Assuming that you didn't change the form field in our HTML form (so it is still named uploaded), this will check to see the size of the file. If the file is larger than 350k, they are given a file too large error, and we set $ok to equal 0.
You can change this line to be a larger or smaller size if you wish by changing 350000 to a different number. Or if you don't care about file size, just leave these lines out
We are not using $ok=1; at the moment but we will later in the tutorial.
We then move the uploaded file to where it belongs using move_uploaded_file (). This places it in the directory we specified at the beginning of our script. If this fails the user is given an error message, otherwise they are told that the file has been uploaded.
Putting All Together
<?php
$target = "upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
//This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Obviously if you are allowing file uploads you are leaving yourself open to people uploading lots of undesirable things. One precaution is not allowing them to upload any php, html, cgi, etc. files that could contain malicious code. This provides more safety but is not sure fire protection.
Try this: $_FILES['userfile'] in place of $_FILES['uploadvideo'] everywhere.
I don'e see any name with uploadvideo in your form.
But in php you are using $_FILES['uploadvideo']
Try giving the exact name of the file input
e.g.:
<input type="file" name="uploadvideo">
I am writing an app from which user will upload files on the server. I have found a php script from internet but I don't know how am I going to tell the script where to upload the data. This might be a silly question but I am no PHP programmer. I am using this php script in my java code.
Here is the script.
<?php
$filename="abc.xyz";
$fileData=file_get_contents('php://input');
echo("Done uploading");
?>
Regards
This is a terrible way of uploading files, you are much better off using a form and the $_FILES superglobal.
Take a look at the W3Schools PHP File Upload Tutorial; please read all of it. For further reading take a look at the PHP Manual pages on file upload.
The file input type will create the upload box in the html form:
<form action="upload_file.php" 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>
After error checking and validating that the file is what you are expecting (very important: allowing users to upload anything to your server is a huge security risk), you can move the uploaded file to your final destination on the server in PHP.
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/abc.xyz");
The filename is actualy the file path along with the name of the new file, set the path there and a file will be created with write permissions.
Make sure you give the servers full path not the relative one and that you have the required permission to create a file there.
Always refer to the PHP Manual
Here's a basic example to get you started:
HTML:
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
Choose a file to upload: <input name="uploaded_file" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
PHP:
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 350000)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
?>
Refer to the documention for more information.
Hope this helps!
I was working on a simple file upload exercise i've gotten from my WebDev Class - We actually only had to copy the code and integrate it to fit our needs.
I tried to do so for my project, sadly it will keep on echoing out the same error.
<?php
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg');
$max_filesize = 524288;
$upload_path = 'uploads/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
var_export($_FILES, $ext);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
if(move_uploaded_file($_FILES['usrfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file here';
else
echo 'There was an error during the file upload. Please try again.';
?>
It keeps on giving me the 'wrong filetype' error, with all of defined types in the array.
<form id='upload' action="uploadfile.php" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td >Choose a File to Upload</td>
</tr>
<tr>
<td >Select File</td>
<td ><input type="file" name="userfile"></td>
</tr>
<tr>
<td colspan=2 id="sub"><input type="submit" name="submit" value="submit" ></td>
</tr>
</Table>
</form>
$filename = $_FILES['usrfile']['name'];
The 'tmp_name' index contains a temporary file name, not the one the file really had. That's stored in 'name'. See this page for information.
Additionally, you should:
check for errors in the 'error' index.
use pathinfo to get the extension,
lowercase it before searching the array,
add some randomness to the uploaded file name to avoid overwriting existing files.
You can use this as firstly you have to always echo the $_FILES array then start debuging.
change this line from
$allowed_filetypes = array('.jpg','.gif','.bmp','.png', '.jpeg');
to
$allowed_filetypes = array('jpg','gif','bmp','png', 'jpeg');
change the follwing line
if(filesize($_FILES['usrfile']['tmp_name']) > $max_filesize)
to
if(filesize($_FILES['usrfile']['size']) > $max_filesize)
and remove the line
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
and change this line
if(!in_array($ext,$allowed_filetypes))
to
if(!in_array($_FILES['usrfile']['type'],$allowed_filetypes))