Problem with uploading multiple files PHP - php

On my site I have a page where users can upload files to go with the news post they're adding. I allow them to upload one image and one sound file. They don't have to add files if they don't want to, or they can just add one if they want. Problem I'm having is that my script only works if the user selects both files. If they choose none, or only one, then the script spits out 'Invalid File' as it can't find a file where one hasn't been selected.
I tried using:
if (isset($_FILES['filetoupload1'])) {
if (($_FILES["filetoupload1"]["type"] == "image/gif")
|| ($_FILES["filetoupload1"]["type"] == "image/jpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/pjpeg")
|| ($_FILES["filetoupload1"]["type"] == "image/png")
|| ($_FILES["filetoupload1"]["type"] == "image/jpg")
) {
if ($_FILES["filetoupload1"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload1"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload1"]["name"])) {
echo $_FILES["filetoupload1"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload1"]["tmp_name"],
"media/" . $_FILES["filetoupload1"]["name"]
);
}
} else {
echo "Invalid file";
}
}
if (isset($_FILES['filetoupload2'])) {
if ($_FILES["filetoupload2"]["type"] == "audio/mp3") {
if ($_FILES["filetoupload2"]["error"] > 0) {
echo "Return Code: " . $_FILES["filetoupload2"]["error"] . "<br />";
} else {
if (file_exists("media/" . $_FILES["filetoupload2"]["name"])) {
echo $_FILES["filetoupload2"]["name"] . " already exists. ";
}
move_uploaded_file(
$_FILES["filetoupload2"]["tmp_name"],
"media/" . $_FILES["filetoupload2"]["name"]
);
}
} else {
echo "Invalid file";
}
}
and then
if((isset($_FILES['filetoupload1'])) && (isset($_FILES['filetoupload2']))) { }
before both first and second upload scripts if the user had selected both image and audio file. In other words it did this:
if filetoupload1 isset then run upload script that filters images.
if filetoupload2 isset then run upload script that filters audio.
if filetoupload1 AND filetoupload2 isset then run both upload scripts.
I have it set like that. The above should allow for all combinations of file uploads. right? but it doesnt work so..
Now I have no idea what to do. Here's the upload script for the audio, the image one is pretty much the same:
Can someone tell me what I'm doing wrong please!

"I get the error: Invalid file"
This is correct, since your code just does this.
Do not check if the file is set but if i.e. $_FILES["filetoupload1"]["type"] is not empty.

Your script makes your server vulnerable to a malicious user being able stomp on any file the webserver has access to:
$_FILES[...]['name'] - user supplied
$_FILES[...]['type'] - user supplied
You're trusting that the client has supplied the proper MIME type for the file, but nothing stops someone from forging a request and uploading "virus.exe" and setting the mime type to 'image/jpeg'. As well, since the remote filename is under user control, it can be subverted with malicious data. Consider:
$_FILES['picture']['type'] = 'image/gif'
$_FILES['picture']['name'] = 'remote_server_control.php'
Completely legitimate according to your script, because the mime type is "right", and yet you've now put a user-supplied PHP script on your server and with that they can take total control of your site and/or server.
Never EVER trust the data in the $_FILES array. Always determine MIME types via server-side utilities. If the script is only supposed to handle images, then use getimagesize(). As well, never use user-supplied filenames. Use something determined server-side to give the file a name, like a databasde auto_increment ID number. Even though your code doesn't allow for overwriting existing files, it's trivial to just come up with a new name and boom... new version of the remote takeover script.

I suggest to you to add a hidden text, this hidden will check witch upload fields are active, you make this check with javascript:
<html lang="en">
<head>
<meta charset="utf-8">
<style>
</style>
<script type="text/javascript">
function uploadForm()
{
var size = 0;
var x = document.forms["myForm"]["upload1"].value.length;
var y = document.forms["myForm"]["upload2"].value.length;
if (x > 0)
{
size = 3;
}
if (y > 0)
{
size += 2;
}
return size;
}
</script>
</head>
<body>
<form name="myForm" action="" method="GET" onsubmit="chose.value = uploadForm()">
<input type="file" name="upload1"><br>
<input type="file" name="upload2"><br>
<input type="hidden" name="chose" value=""><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Now, when you receive the form, you have to check the value of chose filed, if its 2, that is mean the image field is not empty, 3 audio filed is not empty, 5 both not empty:
<?php
switch($_GET["chose"])
{
case 2:
//
break;
case 3;
//
break;
case 5:
//
break;
default:
// here the user doesn't use any field
}
?>

Related

PHP Post data not received

i'm currently working on a small script for my Homepage but i ran into a problem.
I Try to upload an Image, but it seems like the POST data from the form is not being received. What did i do wrong?
I already changed the post_max_size and everything in the php.ini.
These are the Errors i get:
"Notice: Undefined index: image in ...." & "Notice: Undefined index:
submit in ...."
<form method="POST" action="/eye/sites/handling/post.php" enctype="multipart/form-data">
<div class="fileUpload">
<span><i class="fa fa-folder-o" aria-hidden="true"></i> Bild wählen</span>
<input type="file" class="upload" name="image"/>
</div>
<input type="submit" value="Upload It!" name="submit"/>
</form>
<?php session_start();
error_reporting(E_ALL);
if (isset($_SESSION["login_stat"])) {
date_default_timezone_set('Europe/Berlin');
$config = "$_SERVER[DOCUMENT_ROOT]/eye/more/config.xml";
$xml = simplexml_load_file($config);
$picWidth = $xml->pic->width;
$picHeight = $xml->pic->height;
$fulldate = date('dmYHis');
if(isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
$typeCheck = $_FILES['image']['type'];
if ($typeCheck != "image/jpeg") {
$error = "Not a .jpg";
header('location: /eye/sites/post.php?stat=bad&error='.$error);
exit;
}
$file = $_SERVER['DOCUMENT_ROOT']."/uploads/".$fulldate.".jpg";
$type = "image/jpeg";
move_uploaded_file($_FILES['image']['tmp_name'], $file);
$file_thmb = $_SERVER['DOCUMENT_ROOT']."/uploads/!1A_thmb/".$fulldate.".jpg";
include "resize-class.php";
$resizeObj = new resize($file);
$resizeObj->resizeImage($picWidth, $picHeight, 'crop');
$resizeObj->saveImage($file_thmb, 100);
// header('location: /eye/sites/post.php?stat=good');
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No File');
}
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No Data');
echo $_SERVER['CONTENT_TYPE'];
echo "<br>";
echo $_FILES['image']['tmp_name'];
echo "<br>";
echo $_POST['submit'];
echo "<br>";
}
} else {
header('location: /eye/index.php?stat=in');
}
?>
Edit:
The problem is definitely about my Localhost.
This whole thing is working fine on my Webspace, but on my localhost it's not working.
BUT: I'm not getting errors anymore, when is click on Submit it goes to the php file that should save the image, but nothing is happening. I just see a white Page.
But like i said, it runs perfectly on my webspace..
If this is running on your local machine, do a quick check to make sure your "php.ini" file is configured to allow file uploads.
php.ini
file_uploads = On
The codes look fine. Check if your form action is posting to the correct path and if I may suggest using a simpler approach to test your file upload function before making it more complex. Use the following to start testing.
if (isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
echo "Upload is working!";
}
}
Keep us updated on your findings.
Perhaps this general information will help someone, as it helped me: a submitted form will only include fields that have defined 'name' attributes. 'id' is not enough.
The idea is that 'id' identifies an element in the DOM for use by JavaScript (either as a global variable or for use in document.getElementById(ID)), but 'name' identifies those elements whose names and values will be sent to the destination ('action') page.
So it makes sense that there are two different identifying attributes, used in two different ways.

PHP Upload Security- prevent user from uploading unlimited files- form with ajax upload

Edit 2 : I notices user can upload unlimited files and can take all disk space, how to prevent that?
Edit: since no one answered this question, is there a source I could read to get my answer???
I have a contact form. There are three inputs. I used a jQuery plugin for uploading files. This plugin adds another form element and uploads files by ajax.
I'm kind of beginner but this code is for a customer and a real job so I want to make sure it's safe!
in my view:
<form action="" method="post" enctype="multipart/form-data" >
<input type="text" name="name" />
<input type="number" name="phone" />
<textarea name="enquiry" rows="10" ></textarea>
<div id="upload-div">
<div id="extraupload">Upload</div>
<input type="hidden" name="count" value="0" id="count"/>
<input type="submit" />
$(document).ready(function()
{
var uploadObj = $("#extraupload").uploadFile({
url:"/uplod_url",
fileName:"file",
onSuccess:function(files,data,xhr,pd)
{
data = jQuery.parseJSON(data);
if(data.status == 'success') {
var count = $('#count').val() * 1 + 1;
for(var i=0; i<data.files.length; i++) {
$('<input type="hidden" name="file_'+count+'" value="'+data.files[i]+'">').insertBefore('#extraupload');
$('#count').val(count);
count++;
}
}
},
});
});
</script>
each successful upload,will add one to input count value
and will append an hidden input with the value of uploaded file name.
In php I check for file type and change file name:
upload_url.php:
if ($_FILES['file']['type']=='image/jpeg' || $_FILES['file']['type']=='image/pjpeg') {
$ext = '.jpg';
}
elseif ($_FILES['file']['type']=='image/png') {
$ext = '.png';
}
elseif ($_FILES['file']['type']=='application/pdf') {
$ext = '.pdf';
}
else {
echo json_encode('Only images and pdf files are allowed!');
die();
}
$fileName = md5(uniqid());
$fileName = $fileName.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"], 'image/tmp'.$fileName);
$result = array('status'=> 'success','files' => $fileName);
echo json_encode($result);
After changing the file's name to a unique hash, I save that in a tmp folder.
then when the main form is submitted this is what happens:
//validation method: if that file exists in tmp folder
if(isset($this->request->post['count']) && is_numeric($this->request->post['count'])) {
for($i=1; $i<=$this->request->post['count']; $i++ ) {
if(isset($this->request->post['file_'.$i])){
if(!file_exists('image/tmp/'.$this->request->post['file_'.$i])){
//throw error
}
} else{
//throw error
}
}
}
// hidden input count can only be integer
if(isset($this->request->post['count']) && !is_numeric($this->request->post['count'])) {
//throw error
}
and then mailing the file and saving file name in database(I did not include database part because I'm kind of sure it's ok)
//by every submition delete files in tmp folder older than 1 day
$oldFiles = glob($tmp_dir."*");
$now = time();
foreach ($oldFiles as $oldFile) {
if (is_file($oldFile)) {
if ($now - filemtime($oldFile) >= 60 * 60 * 24) {
unlink($oldFile);
}
}
}
$mail = new Mail();
//Mail Setting and details deleted
//if there's any file uploaded
if($this->request->post['count'] != 0) {
//unique directory for every form submition
$dir_path = 'image/submitted/'.uniqid();
mkdir($dir_path, 0764, true);
//for all hidden inputs move file from tmp folder to $dir_path
for ($i=1; $i <= $this->request->post['count']; $i++) {
$file = $this->request->post['file_'.$i];
rename('image/tmp'.$file, $dir_path.'/'.$file);
$mail->AddAttachment($dir_path.'/'.$file);
}
}
$mail->send();
now my question is: Is it safe this way? especially when I append hidden inputs with file's name and get the number of uploaded files from hidden input count??
This code already works, but I think this might be a security issue.
Thanks a lot for your patience and sorry for my poor english!
ps: I use opencart
There is the general misconception that in AJAX applications are more secure because it is thought that a user cannot access the server-side script without the rendered user interface (the AJAX based webpage). XML HTTP Request based web applications obscure server-side scripts, and this obscurity gives website developers and owners a false sense of security – obscurity is not security. Since XML HTTP requests function by using the same protocol as all else on the web (HTTP), technically speaking, AJAX-based web applications are vulnerable to the same hacking methodologies as ‘normal’ applications.

base64 image upload validation

I'm making a feature on my website that a user uploads an image either by loading it from file or by using their computer's built-in webcam.
I take a picture with either my webcam or I load it from file
I store the base64 in an input which is submitted to the server along with other information.
The server validates the base64 (looks for hacks)
The image is stored on the server
I understand the validation method I used:
Takes a lot of processing speed on the server (encoding and decoding)
Has bugs / not reliable
Is probably not secure enough
Is there any more secure, "server-friendly", and reliable way of validating the base64??
(I couldn't find any promising methods in other posts.)
It fails when I face the camera at certain places (somehow the base64 is affected by certain pictures)
Thanks so much for any help!
-- dragonfire
upload.php script:
<?php
$uploaded_file_b64 = htmlspecialchars($_POST['b64_img_url']); // string containing base64 of uploaded image
$FileName = "the_unique_uploaded_file_name.png";
$file_path = "/uploads/" . $FileName;
$file_relative_path = "../uploads/" . $FileName; // BUG: need to use relative path rather than absolute since absolute path doesn't work. Why???
//Must get actual base64 out of string by splicing it
$uploaded_file_actual_b64 = explode("base64,",$uploaded_file_b64);
//We need to get the second value from the array returned from explode() since there are two commas before the actual base64
$uploaded_file_actual_b64 = $uploaded_file_actual_b64[1];
// First try to decode then re-encode the base64. If works then perfect!
if ($uploaded_file_actual_b64 == base64_encode(base64_decode($uploaded_file_actual_b64))) {
// It worked!
echo "Valid base64!";
}
else {
// It failed! THIS IS WHERE IT ALWAYS ERRORS!! WHY???
echo "Not base64!";
}
// Try creating an image from the base64. If works then perfect!
$is_image = imagecreatefromstring(base64_decode($uploaded_file_actual_b64));
//doing this will help confirm it's an image, but it is still possible to inject php or js into
//the body of the image, but as long as we don't execute the image on the server
//then we should be fine
if ($is_image != false) {
echo "Valid image!";
} else {
echo "Not an image!";
}
// If we get up to here, then nothing has been tampered with!
echo "Secure!";
// Store the image on the server
if (file_put_contents($file_relative_path, base64_decode($uploaded_file_actual_b64))) {
echo "Upload success!";
} else {
echo "Upload failed!";
}
?>
Client side code:
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" id="b64_img_url" name="b64_img_url" style="display: none;"/>
<input type="submit" class="btn btn-success" value="Submit" />
<div id="btn_cam_capture" onclick="capture_webcam();">Capture</div>
<canvas id="camera-stream-canvas"></canvas>
<img id="img-drop-preview"/>
<script>
var canvas = document.getElementById("camera-stream-canvas");
function capture_webcam() {
// Executed when user takes shot.
// Previews the image by converting the canvas to a base64 image.
document.getElementById("img-drop-preview").src = canvas.toDataURL();
// The input which stores the base64
document.getElementById("b64_img_url").value = canvas.toDataURL();
}
</script>
</form>

Cant get Php restrictions to work with HTML input tag for song upload

Hello I'm trying to get restrictions to work with my php upload script to make
sure people are only uploading music nothing els but when I run in the browser
I always get upload faild all post my code below
<?php
// This PHP5 file is used to move an uploaded song file to its final
// destination. The song is scaled as part of the process.
// A normal HTML upload form will serve as the user interface for the
// upload. The song file should be submitted using a field named
// "song".
// set database connection
require("------.php");
// lets get our posts //
$song = $_FILES['song'];
// folder that will hold songs
$songpath = "songs/";
// song-file pathname
$songpath .= $song["name"];
//---------------------------------------------------------------
// this file is going to add restrictions to the song form
$ftype = $_FILES["song"]["type" ];
$xerror = $_FILES["song"]["error" ];
$xsize = $_FILES["song"]["size" ];
if (($ftype == "audio/mp3" )
|| ($ftype == "audio/ogg" )
|| ($ftype == "audio/wav" )
|| ($ftype == "audio/midi" ))
{
$it_is_a_song = 1;
}
else
{
$it_is_a_song = 0;
}
if ($it_is_a_song && ($xsize < 20971520) && ($xerror == 0))
{
$it_is_good = 1;
}
else
{
$it_is_good = 0;
}
//-----------------------------------------------------------------
print <<<END
<html>
<title>You Must Party Upload Results</title>
<body>
END;
// move the file from the tmp folder to the song folder
if ( $it_is_good &&
move_uploaded_file ($song['tmp_name'], $songpath))
{
print "<p>Upload succeeded thank you</p>\n";
}
else
{
print "<p>Upload failed, sorry</p>\n";
}
print <<<END
<p>
To continue, click here.
</p>
</body>
</html>
END;
?>
$_FILES["song"]["type"] will return mime type and song mime type doesn't exist so it'll always fail.
Instead use audio, eg. audio/ogg.

Uploading Photos Issue

i have wrote a function that takes a photo upload from a form, creates the file on the server and adds the information to the database, but Im having a nightmare trying to get it to do exactly what i want.
EDIT
Currently, it displays the correct error message if the filetype is wrong, and over 3MB but when i try to upload a 17MB .bmp file it cancels and logs me out. It appears to reinitiate my process.php file after it has processed the intended function.
I am baffled, so any help would be appreciated. Thanks
<form action="process.php" method="POST" enctype="multipart/form-data" name="formUpload">
<label>Picture:</label>
<input type="file" name="photo" id="photobrowser" tabindex="4">
<span class="error"><?php echo $form->error("photo"); ?></span><br />
<input type="hidden" name="sessionid" value="<?php echo $sessionid; ?>" />
<input type="hidden" name="subphoto" value="1" />
<input type="image" src="styling/images/button-add-photo.png" id="subBtn" tabindex="6" />
</form>
process.php
class Process {
function Process(){ /* Class constructor */
global $session;
if(isset($_POST['subphoto'])){ /* User submitted an advert photo */
$this->procAddPhoto();
} else if($session->logged_in){ /* No form was submitted therefor logout */
$this->procLogout();
} else { /* User trying to view this file */
header("Location: /");
}
}
function procAddPhoto(){
global $session, $form;
$retval = $session->addPhoto($_FILES['photo']['size'], $_FILES['photo']['type'], $_FILES['photo']['tmp_name'], $_POST['sessionid']);
if($retval == 0){ /* Successful */
// do stuff
} else if($retval == 1){ /* Errors found */
// do stuff
} else if($retval == 2){ /* Adding failed */
// do stuff
}
} // close function procAddPhoto()
};
$process = new Process; /* Initialize process */
?>
session.php
function addPhoto($subphotoSize,$subphotoType,$subphotoTmpname,$subsessionid){
global $database, $form;
$maxFileSize = 3000000; // bytes (3 MB)
/* Image error checking */
$field = "photo";
if($subphotoSize == 0){
$form->setError($field, "* No file selected");
} else {
list($width, $height, $type, $attr) = getimagesize($subphotoTmpname);
if($width > 4000){
$form->setError($field, "* Max photo width is 4000 pixels.");
} else if($subphotoSize > $maxFileSize) {
$form->setError($field, "* Photo is above the maximum of 3 MB");
} else if( ($subphotoType != "image/jpeg") && ($subphotoType != "image/pjpeg") && ($subphotoType != "image/png") ){
$form->setError($field, "* $subphotoType is wrong file type");
}
}
/* Errors exist, have user correct them */
if($form->num_errors > 0){
return 1; //Errors with form
} else { // Else use variables
/* Get random string for new filename name */
$randNum = $this->generateRandStr(10);
$filerootpath = PHOTOS_DIR.$subsessionid."/";
$thumbrootpath = PHOTOS_DIR.$subsessionid."/thumbs/";
if($subphotoType == "image/png"){
$filename = $randNum.".png";
} else if ($subphotoType == "image/jpeg" || $subphotoType == "image/pjpeg"){
$filename = $randNum.".jpg";
}
$fullURL = $filerootpath.$filename;
$thumbURL = $thumbrootpath.$filename;
/* Make sure file is RGB colors */
$getimagesize = getimagesize($subphotoTmpname);
if (isset($getimagesize['channels']) && $getimagesize['channels'] == 4 && $getimagesize[2] == IMAGETYPE_JPEG ) {
$im = #imagecreatefromjpeg($subphotoTmpname);
if ($im) {
imagejpeg($im, $image, 75);
imagedestroy($im);
}
}
/* Upload files to correct folders */
move_uploaded_file($subphotoTmpname, "$fullURL");
/* Use session ID for the advert ID because it hasnt been made yet */
$userSession = $this->userinfo['userid'];
$ownerID = $this->userinfo['id'];
if(!$database->addNewPhoto($ownerID,$fullURL,$userSession,$is_main_photo, $subsessionid, $thumbURL)){
return 2; // Failed to add to database
}
}
return 0; // Success
}
Just a thought... I am guessing that you have more than one issue here. You said that when someone tries to upload a file over X mb it basically hits the kill switch. Do you know, roughly, what that size is? If you do, can you compare it to the upload_max_filesize and post_max_size settings for your php installation? They should both be visible in phpinfo(). I think that the default is somewhere around 2mb but I could be wrong on that. Either way, I know that when you try to upload beyond those settings it basically spits the bit. You may have to change the php.ini settings for that one.
It displays an error if the filetype isnt correct, unless, the file
is several MB in size, in which case it completely logs the user out,
almost like its killing all session variables
Please open /etc/php5/apache2/php.ini (assuming you are using apache2) and set upload_max_filesize = 5M (for 5 megabyte file) and you have file_uploads = On. then restart apache. and try again.
The image cannot be displayed because it contatins errors." But when i
download the uploaded image from the server, the picture displays
fine, but not via http.
can you check you have enough permission to read image from the directory where it is stored. (and make sure you are accessing the right directory; try copying relative path of image in the browser address bar )
let me clear few things first:
1.you can upload 17 mb file but you want to restrict upload more than 3 mb.
2.it uploads 17 mb file but from browser you can see that. but if you download from your server windows can open it correctly.?
can you insert: var_dump($ubphotoSize); var_dump($$maxFileSize); at the beginning of addPhot() and try again. according to you it seems it cannot compare file sizes. please let us know our output.

Categories