I am currently developing a website where users can upload and share there websites.
I have tried to create a upload feature but failed every attempt.
I just want a file upload system, preferably created with PHP, that will upload a visitors HTML page and will automatically put the link of there page somewhere on the index.html page.
Here is the code for index.html:
<!DOCTYPE html>
<html>
<body>
<style>
* {
font-family: sans-serif;
}
</style>
<h1>File Upload</h1>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="html"> <br/> <br/>
<input type="submit" value="Upload">
</form>
</body>
<br/> <br/>
<body>
Example Link <!-- Link of Uploaded file -->
</body>
</html>
Here is the code for upload.php:
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_FILES["html"]) && $_FILES["html"]["error"] == 0){
$allowed = array("html", "htm");
$filename = $_FILES["html"]["name"];
$filetype = $_FILES["html"]["type"];
$filesize = $_FILES["html"]["size"];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Sorry, the file you selected is not supported");
$mazsize = 40MB;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
if(in_array($filetype, $allowed)){
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["html"]["tmp_name"], "upload/" . $filename);
echo "Success!";
}
} else{
echo "An error occured while uploading your file.";
}
} else{
echo "Error: " . $_FILES["html"]["error"];
}
}
?>
Please help.
You're asking a bit odd questions to say the least. Your code is not consistent with your questions or request either. Automatically upload HTML? And yet you have a form to store user website HTML?
Well user will have to provide you with their website HTML and also their website URL. Which means you need to adjust your script to handle both options. Yet I only see one option, to upload HTML. And there is nothing automatic about it either. It's just a simple upload text function. If you want a real automatic version? Then you should think outside the box. You could for example let users provide their URL and then where you make some sort of a bot to go and take screenshots of that website layout. Also using a simple JS you could add the option to write user website url. Then below an iframe will be undated loading user url. Then you could use https://html2canvas.hertzen.com/ version 1.0.0-rc.1 to make an approximate snapshot of user url layout.
Who otherwise in their right mind would upload their entire HMTL? For that you need a lot more work than what you've provided. A website is not only HMTL. Without JavaScript these days there is no website. Because almost every website layout will break down without JavaScript. Then there are images without the full url since images are usually loaded locally or even trough AWS or something.
Anyways, you need to go back to the drawing board and figure out what exactly you need. I would suggest that you need people to upload an archive with the entire website if that is what you need, an entire website?
But if you ask wrong questions, then you will receive wrong answers. There is no way in the world this code you've provided will be sufficient for anything useful other than some testing purposes.
I have Updated the code and now you can try it
You have used file size in in proper way
And it cause errors
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_FILES["html"]) && $_FILES["html"]["error"] == 0){
$allowed = array("html", "htm");
$filename = $_FILES["html"]["name"];
$filetype = $_FILES["html"]["type"];
$filesize = $_FILES["html"]["size"];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if(!in_array($ext, $allowed)) die("Sorry, the file you selected is not supported");
if($filesize > 4000000) die("Error: File size is larger than the allowed limit.");
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
if(move_uploaded_file($_FILES["html"]["tmp_name"], "upload/" . $filename)){
echo "Success!";
} else{
echo "An error occured while uploading your file.";
}
}
} else{
echo "Error: " . $_FILES["html"]["error"];
}
}
?>
<!DOCTYPE html>
<html>
<body>
<style>
* {
font-family: sans-serif;
}
</style>
<h1>File Upload</h1>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="html"> <br/> <br/>
<input type="submit" value="Upload">
</form>
</body>
<br/> <br/>
<body>
Example Link <!-- Link of Uploaded file -->
</body>
</html>
Related
I am new to HTML and PHP. I used html/php code from https://gist.github.com/taterbase/2688850 to implement a file upload page on my web server. Created "uploads/" folder in the server and gave chmod 777 permission to it.
It is working when I use name="uploaded_file", the original, I can see the file in the folder. However it is failing when I change the name="xxx" to something else, such as another name or the array form of it, no message on screen, file is not seen in the uploads folder.
Is the "uploaded_file" a fix or hard-coded kind of value? My aim is to use an array instead later, to make it for multiple files upload, however this name change restriction doesn't let me.
Please see below working and not-working samples:
upload.php (name="uploaded_file") Works
<!DOCTYPE html>
<html>
<head>
<title>Upload your files</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?PHP
if(!empty($_FILES['uploaded_file']))
{
$path = "uploads/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
upload.php (name="user_file") Doesn't work
<!DOCTYPE html>
<html>
<head>
<title>Upload your files</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<p>Upload your file</p>
<input type="file" name="user_file"></input><br />
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<?PHP
if(!empty($_FILES['user_file']))
{
$path = "uploads/";
$path = $path . basename( $_FILES['user_file']['name']);
if(move_user_file($_FILES['user_file']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['user_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
?>
This line has the problem move_user_file($_FILES['user_file']['tmp_name'], $path).
php's bool move_uploaded_file ( string $filename , string $destination ) moves the uploaded files to a desired location. It is a built in function in php's API.
Your code should be changed to
move_uploaded_file($_FILES['user_file']['tmp_name'], $path)
in order to get it to work.
Your misunderstanding I think has come from your naming. Previously your field name is uploaded_file and the function name is move_uploaded_file(). So you must have thought that, when your field name is user_file, you should call move_user_file() in php. That's kinda creative thinking.. :D
Is the "uploaded_file" a fix or hard-coded kind of value? Well, you need to read the link given.
You are changing the core function call to either undefined function or a user defined function.
If you have defined a function move_user_file(), then its ok.
But, if you are expecting a core PHP inbuilt function, then there is no function move_user_file().
The line seems to have problem:
if(move_user_file($_FILES['user_file']['tmp_name'], $path)) {
Should be:
if(move_uploaded_file($_FILES['user_file']['tmp_name'], $path)) {
You are ending up in calling a undefined function move_user_file().
The required function is: move_uploaded_file()
Its not move_user_file, its move_uploaded_file. Next time, learn how to use your editor's find and replace correctly ;o)
I am writing a code for uploading one excel file.And displaying its full content on a webpage.But whenever user clicks on the submit button it shows the error-
"Your File Type is:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
File type must be text(.txt) or msword(.doc)."
Below is my code.
<?php
if( isset($_POST['submit1'])) {
// $_FILES is the array auto filled when you upload a file and submit a form.
$userfile_name = $_FILES['file1']['name']; // file name
$userfile_tmp = $_FILES['file1']['tmp_name']; // actual location
$userfile_size = $_FILES['file1']['size']; // file size
$userfile_type = $_FILES['file1']['type'];
$userfile_error = $_FILES['file1']['error']; // any error!. get from here
// Content uploading.
$file_data = '';
if ( !empty($userfile_tmp))
{
$file_data=base64_encode(#fread(fopen($userfile_tmp,'r'), filesize($userfile_tmp)));
}
switch (true)
{
// Check error if any
case ($userfile_error == UPLOAD_ERR_NO_FILE):
case empty($file_data):
echo 'You must select a document to upload before you can save this page.';
exit;
break;
case ($userfile_error == UPLOAD_ERR_INI_SIZE):
case ($userfile_error == UPLOAD_ERR_FORM_SIZE):
echo 'The document you have attempted to upload is too large.';
break;
case ($userfile_error == UPLOAD_ERR_PARTIAL):
echo 'An error occured while trying to recieve the file. Please try again.';
break;
}
if( !empty($userfile_tmp))
{
// only MS office and text file is accepted.
if( !(($userfile_type=="application/msword") || ($userfile_type=="text/plain") || ($userfile_type=="application/vnd.ms-excel")) )
{echo 'Your File Type is:'. $userfile_type;
echo '<br>File type must be text(.txt) or msword(.doc).';
exit;
}
}
echo filesize($userfile_tmp);
}
?>
<HTML>
<HEAD>
<TITLE> PHP File Upload Script </TITLE>
</HEAD>
<BODY>
<form name="profile" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" target="_self" enctype="multipart/form-data" >
<P align ="center"><input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input name="file1" type="file" accept="application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" />
<input type="submit" name="submit1" value="Submit" />
</P>
</form>
</BODY>
</HTML>
Please help .
Thank you in advance.
You need to add following in your if condition as well
because your are checking for application/vnd.ms-excel and application/msword but file is having its header different as
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetyour" So if you add this inside if like
if(($userfile_type=="application/vnd.openxmlformats-officedocument.spreadsheetml.sheetyour") || ($userfile_type=="application/msword") || ($userfile_type=="text/plain") ||
($userfile_type=="application/vnd.ms-excel")){
// code
}
Because server will interpret the file type based on headers it receives.
If you want to show Excel file contents on your page then you should think of using PHPExcel. It is very easy to use.
Link: https://phpexcel.codeplex.com/
Examples: https://phpexcel.codeplex.com/wikipage?title=Examples&referringTitle=Home
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">
So I'm trying to set up an image upload from a form via php on my localhost and after running the code and connecting to the database okay, I'm getting the error for the upload. Since all of the other parts of the form are working after a section by section check, I'll just add the html for the upload input and its relevant php script.
<input type="file" name="image" id="image-select" />
And the portion of the php that has to deal with the image upload and verification after upload:
$image = $_FILES ['image']['name'];
$type = #getimagesize ($_FILES ['image']['tmp_name']);
//Never assume image will upload okay
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['image']['error']);
}
//Where the file will be placed
$target_path = "uploads/";
// Add the original filename to target path
$path= $target_path . basename($image);
// Check if the image is invalid before continuing
if($type === FALSE || !($type[2] === IMAGETYPE_TIFF || $type[2] === IMAGETYPE_JPEG || $type[2] === IMAGETYPE_PNG)) {
echo '<script "text/javascript">alert("This is not a valid image file!")</script>';
die("This is not a valid image file!");
} else {
move_uploaded_file($_FILES['image']['tmp_name'], $path);
}
So error appears once the code hits the upload process. I was attempting to upload a small PNG file The relevant code I added is also in their respective orders when they appear in the script.
can you please put error here. If error means that after submit page file is not being upload. then please check your form enctype. see below an example
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image-select" />
<input type="submit" value="Submit">
</form>
Just a wild stab in the dark here as you haven't provided your form tag but you have remembered the enctype attribute haven't you?
Sorry I don't have 50 reputation otherwise I would ask this as a comment.
<form enctype='multipart/form-data' action=''>
<input type="file" name="image" id="image-select" />
</form>
Also you should check if the file uploaded OK before calling getimagesize() (not that this would be the source of your issue)
if you are using PHP5 and Imagick, then you can try to use something like the following:
$image->readImageFile($f);
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!