Okay, so I set up an upload engine for a website so that an authenticated user can upload a audio file (a key) for a song in the library, but I come across this strange problem when I try to upload any file over 5MB.
I set my php.ini max filesize to 50MB by the way
Everything uploads properly, but there is no data associated with the file on the other end.
HTML CODE:
<form action="keyUpload.php?id=<?php echo $id;?>" method="post" enctype="multipart/form-data">
<p style="color:#fff;font-size:30px;font-family:Times">
Add a new Key:<br/><input name="uploaded" type="file" id="file"><br />
<input type="text" name="kname" id="kname" value placeholder="Key Name (Ex. Demo, A#, etc.)" style="width:300px;"><br/>
<button class="button">Upload File</button><br/>
<span style="font-size:12px;">*Max Filesize is 50 MB*</span>
</p>
</form>
PHP CODE:
<?php
$id=$_GET["id"];
$name=$_POST["kname"];
$name = str_replace(" ","%20",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
Both $filename and $ext are empty variables when I upload a file larger than 5 MB. In all other cases, this engine works perfectly.
When echoed, simply nothing happens, so obviously the engine will not save the file if it doesn't exist. What's going on?
var_dump:
array(0) { }
Thanks for all your help!
Check for upload errors:
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['uploaded']['error']);
}
The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
As well, do NOT use filenames to validate the uploads. It is beyond trivial for a malicious user to fake a filename and upload malicious files, eg.
ren nastyvirus.exe good_tune.mp3
And don't use string operations on filenames. There's a whole whack of PHP functions for filename manipulation, e.g. http://php.net/basename
Set max_post_size in php.ini as well.
Related
I am trying on upload file from local file system to a remote server using php.
I am using move_uploaded_file function but when i select a file on my local file system, it tries to find the file on remote server and hence fails. maybe i am missing something. Let's say if i am trying to upload a file from C:\Data\abc.txt. It tries to find the file on /server/abc.txt and hence fails to upload the file. Please let me know if i am missing something.
<?
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$original = $root_path .$file_name;
echo $_FILES['image']['tmp_name'];
if($file_size > 100097152){
$errors[]='File size must be less than 100 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp, '/uploads');
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
I dont know if I have understood you correctly, but you means with remote server your webserver?
This server doesnt access your file system directly because of your browser's sandbox mode. It gets only the submitted file, the origin path doesnt matter.
The second parameter of the function move_uploaded_file has to be the target file, not the target dictionary.
Example:
move_uploaded_file($file_tmp, '/uploads/' . $file_name);
diffcult to answer pls tell me the php version and as a hint: have you checked is_uploaded_file() php.net/manual/function.is-uploaded-file.php
could help to use the error/status-reporting in $_FILES['image']['error'] - gives feedback on error/status code of your file upload, so you can better understand what the source of the problem possibly is:
0 = success
1 = file too big (php.ini set)
2 = file too big (max file size directive)
4 = no file was uploaded
6 = no access to temp folder on server
7 = file could not be written to server
8 = upload stopped by a php extension
hope that helps
I am completely a novice in all this ...
I have created a Social Networking project in which there is a module which allows user to upload photos..
I have hosted this project in my college server
I access that server using bitvise client with my server credentials.
My problem is i don't know how to setup upload mechanism for remote server ... In my localhost i simply use
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
function but i don't know how to do this for remote server ...
I tried FTP by looking at some tutorials but that didn't worked for me.
In my project structure there is a directory
users/user_id (diff for all users)/photos
here i want to place the uploaded files....
A proper description with example and proper functioning might be very helpful for me.... Thank you
EDIT:
Below is my code.
Photos.php
<form class="input-group-btn" method="post" action="editPhotos.php"enctype="multipart/form-data" id="myForm">
<input type="file" name="file" id="imgInp">
<button type="submit" class="btn btn-primary" name="form-submit">Done</button>
</form>
editPhotos.php
if( isset($_POST['form-submit']) ){
$target_file = "users/".$email."/pictures/Photos/" . basename($_FILES["file"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
$img =str_replace(" ", "",basename($_FILES["file"]["name"]));
rename($target_file, "users/".$email."/pictures/Photos/".$img);
header('Refresh: 1; url=Photos.php?user='.$email);
}
Small tutorial how to upload file.
For sure, you need correct encryption and file's type in your form (ommited other fields, to clear example):
form.html
< form action="upload.php" method="post" enctype="multipart/form-data">< /form>
< input name="test" type=file>
upload.php
In $_FILES you have all data of uploaded file. In given example, we have field named test.
Advice, to always first check error $_FILES['test']['error'] - the values you can find in here.
If this is correct, then prepare upload path. Some advices:
remember that if you use original filename ($_FILES['test']['name']), then is User upload second file, with same name, you will need overwrite file or ignore upload. Other way, is to save data to database and generate temporary name form him.
destination path(target_file) - regardless if upload folder is in the same catalog, you should always use global path, as good practice. You can use DIR for that.
don't use in path data, like email - is you have project, and want give opportunity to change email in configuration, what you will do with files? Better save user to Database and use his ID as key.
If you have path, then you simply need only use of move_uploaded_file, but remember to check result, as it not always will return true. You can have error, when you don't have permissions to destination folder (you'll need debug this).
I see that you, first upload file, then rename (then you should check, if rename was success). Don't extends this process, if it not necessary. Upload file for final path and name.
Example of code (I this rattle off)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$fileName = basename($_FILES["file"]["name"]);
$fileName = str_replace(" ", "", $fileName);
$target_file = sprintf(__DIR__ . "/users/%s/pictures/Photos/%s", $email, $fileName);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
// File was uploaded
header('Refresh: 1; url=Photos.php?user=' . $email);
} else {
// File was not uploaded;
throw new \Exception('File was not uploaded. Check warnings.');
}
}
Used other method to check, if this is POST
use method sprintf, for better code quality
checked effect of move_uploaded_file
use global path for destination file
Below code is risky in live environment, please use cautiously
Use a relative path to the uploads folder. For example, if your uploads folder is placed outside your current folder. Then
$PATH = '/absolute/example/path/to/uploads';//from config file
$target_file = "$PATH/file_name";
move_uploaded_file($_FILES['file']['tmp_name'],$target_file);
The above code will work both in local and remote server.
Other checks are below:
Check for errors while uploading file in server
To enable error handling use below code in your upload logic:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Another important note is to make uploads folder writable otherwise file upload wont work.
I want users to be able to upload a profile picture (which can be .jpg or .png) and I also want this to be displayed on their profile. I have written some code, based on sources I found here, on Stackoverflow and Google. However, it does not seem to work and I can't find my mistake.
This is the html
<form action="account_settings.php" method="POST">
<input type="file" name="profilePicture"><br><br>
<input type="submit" value="Change!">
</form>
This is how to uploaded file will be processed.
<?php
include ('inc/header.inc.php');
if(isset($_FILES["profilePicture"]["tmp_name"]) && isset($_FILES["profilePicture"]["name"])) {
$ext = pathinfo($_FILES['profilePicture']['name'], PATHINFO_EXTENSION);
$name = $_SESSION['user_login'];
$tmp_name = $_FILES["profilePicture"]["tmp_name"];
if($ext == 'png' || $ext == 'jpg') {
if (isset($tmp_name)) {
if(!empty($tmp_name)) {
$location = '../profielfotos/';
$full_name = $name.'.'.$ext;
if(move_uploaded_file($tmp_name, $location.$full_name)) {
echo 'Photo uploaded!';
}
Down here are just some else statements with error reports.
The code below is used to display the image. I have tested it by putting an image in the profile pictures folder and it did display the image. However, there is still a problem. People are allowed to upload .jpg or .png, how can I make the website display the picture (find the profile picture with the right extension).
I have put this code inside the src attribute of the <img>tag.
<?php if ($handle = opendir('profielfotos/')) {
$file = mysql_real_escape_string($_GET['u']);
echo 'profielfotos/'.$file.'.png';
}
closedir($handle);
I hope someone can help, thanks in advance!
ps. this is my first post ever on stack overflow :-D!
Since you are not storing any info about the file uploaded, you just have check which file exists, using he file_exists() method. See here:
http://php.net/manual/en/function.file-exists.php
So your code will become something like this (Not tested):
<?php if ($handle = opendir('profielfotos/')) {
$file = mysql_real_escape_string($_GET['u']);
if (file_exists('profielfotos/'.$file.'.png')) {
echo 'profielfotos/'.$file.'.png';
} else if (file_exists('profielfotos/'.$file.'.jpg')) {
echo 'profielfotos/'.$file.'.jpg';
}
}
closedir($handle);
You need to add the following to your form:
<form action="account_settings.php" method="POST" enctype="multipart/form-data">
Otherwise it won't allow a file upload as it expects only text.
This is totally insecure. Files uploaded by a user shall never ever be stored within the root of the web server.
Instead, put the files somewhere outside of the doc root.
Write a handler, which takes control of he files
check the mime type by checking the content, not the extension
have arbitrary names, not the name from the upload, that might interfer (imagine 5 people uploading a "profile.png")
let the handler deliver the image by an id ("...imagloader?file=4711"),
name of the file (and extension and location) is stored in a database (with the user record?)
I have been playing with various php upload examples to get a feel of how it works.
Before my database is in place, I want to understand why when I click my "post comment" button on my form that it goes to another page showing my whole php code. (is this due to database not made yet?)
I also think that I am not understanding the line of code: "$upload_path ="
I put the directory path of the folder containing my text document. From what I have been reading it said it has to be a directory and usually only has examples of just "\files\" or "\uploads\" which doesn't make sense to me.
Also what does:
$filename . '" title="Your File">here</a>'; // It worked.
line of code mean or does?
I want my upload to post to my website. In other words, click upload button and the document displays below the form on the same page.
I have a html form inside a html document and then I have a separate php document.
HTML:
<form id="comments" action="upload.php" method="POST" enctype="multipart/form-data">
Comment: <input type="text" name="comment">
<br>
Text Document: <input type="file" name="documentfile" />
<br>
<input type="submit" name="submit" value="Post comment" class="button">
</form>
PHP:
<?php
$allowed_filetypes = array('.text'); // types of files to use
$max_size = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = '\\ps....\ps.....\w...\Data\Aly...\HTML\TechSite - Copy\TechSite - Copy\files';
$filename = $_FILES['documentfile']['name']; // Get the name of the file and extension.
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get file extension
// Check if the filetype is allowed, if not tell user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Check filesize, if too large tell user.
if(filesize($_FILES['documentfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to path, if not tell 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['documentfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file <a href="' . $upload_path .
$filename . '" title="Your File">here</a>'; // It worked.
else
echo 'There was an error during the file upload. Please try again.';
?>
Once again: I played with examples I found for the php file because I am learning as I go with it. Please let me know if there is something in the php file that doesn't make sense and explain if possible. I'm wanting to understand if my php will be ok once my database is in place. I'd appreciate it!
I'm having users upload .xls, .xlsx, and .csv files to my website. From there I want to save them to the folder /upload/ in the same directory as the handler. I also want the name to remain constant. I have developed a code from what I have seen across the internet. Upon submission, the page turns white and no file is uploaded to the folder.
Form:
<form name="file" enctype="multipart/form-data" action="update_handler.php" method="post" >
<b>Accepted File Extensions: .csv .xls </b><br>
Please save your excel table as one of the <br>accepted file extensions prior to uploading.
<br><br>
<u>Upload File:</u> <input type="file" name="file"><br>
<input type="submit" value="Submit">
</form>
Handler:
<?php
$uploadDir = '/upload/';
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
?>
You named your form file <form name="file"
Where it should be for your input <input type="file" name="file"> <= which am sure read something else, since it was edited. Both form and the input hold the same named attribute. Remove the one for the form or give it another name if it is required for something else.
Also, David pointed out another issue which I did think of earlier, but failed to mention after. Since I took your comment about the "face palm" had fixed everything. I would've commented, but did not.
I was going to suggest that actually, about your use of /upload/ instead of upload/ if running your script from the root, but failed to mention it earlier.
David seems to have deleted his answer.
Plus; you may need to use ../upload/ or something similar, depending on the script's execution location and make sure proper write permissions are set.