2

I am using a file uploader utilising Ajax and PHP to upload files of the type "PDF". The files can be no greater than 5MB. However after I submit my form a blank white page appears, in the address bar the page is called "processuploads.php". I have a file called "processuploads.php" with the following code inside it.

Edit: My error message now states die('Something wrong with upload! Is "upload_max_filesize" set correctly?');

<?php
   if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
   ############ Edit settings ##############
   $UploadDirectory = 'C:\xampp\htdocs\ReportBazaar\reports'; //specify upload    directory ends with / (slash)
   ##########################################

   /*
   Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini". 
   Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit 
   and set them adequately, also check "post_max_size".
   */

   //check if this is an ajax request
   if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
       die();
    }


   //Is file size is less than allowed size.
   if ($_FILES["FileInput"]["size"] > 5242880) {
    die("File size is too big!");
    }

    //allowed file type Server side check
     switch(strtolower($_FILES['FileInput']['type']))
    {
       //allowed file types
         case 'application/pdf':
        break;
        default:
        die('Unsupported File!'); //output error
      }

      $File_Name          = strtolower($_FILES['FileInput']['name']);
      $File_Ext           = substr($File_Name, strrpos($File_Name, '.')); //get file extention
      $Random_Number      = rand(0, 9999999999); //Random number to be added to name.
      $NewFileName      = $Random_Number.$File_Ext; //new file name

        if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
         {
        die('Success! File Uploaded.');
         }else{
        die('error uploading File!');
         }

             }
              else
             {
          die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
             }
?>

The code below is in my "uploadreports.php" file, this is where the ajax is located and the form to be submitted.

<?php require "header.php"; 

if(check_login()) {

 } else {
   header('Location: login.php');
    exit;
  }

  function check_login () {
      if(isset($_SESSION['sess_uid']) && $_SESSION['sess_uid'] != '') {
      return true;
      } else {
        false;
   }
}
?>  

 <script type="text/javascript">
     $(document).ready(function() { 
        var options = { 
        target:   '#output',   // target element(s) to be updated with server response 
        beforeSubmit:  beforeSubmit,  // pre-submit callback 
        success:       afterSuccess,  // post-submit callback 
        uploadProgress: OnProgress, //upload progress callback 
        resetForm: true        // reset the form after successful submit 
        }; 

 $('#MyUploadForm').submit(function() { 
 $(this).ajaxSubmit(options);           
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 


//function after succesful file upload (when server response)
function afterSuccess() {
$('#submit-btn').show(); //hide submit button
$('#loading-img').hide(); //hide submit button
$('#progressbox').delay( 1000 ).fadeOut(); //hide progress bar
}

//function to check file size before uploading.
function beforeSubmit(){
    //check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{

    if( !$('#FileInput').val()) //check empty input filed
    {
        $("#output").html("Are you kidding me?");
        return false
    }

    var fsize = $('#FileInput')[0].files[0].size; //get file size
    var ftype = $('#FileInput')[0].files[0].type; // get file type


    //allow file types 
    switch(ftype)
    {
        case 'application/pdf':
            break;
        default:
            $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
            return false
    }

    //Allowed file size is less than 5 MB (1048576)
    if(fsize>5242880) 
    {
        $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big file! <br />File is too big, it should be less than 5 MB.");
        return false
    }

    $('#submit-btn').hide(); //hide submit button
    $('#loading-img').show(); //hide submit button
    $("#output").html("");  
}
else
{
    //Output error to older unsupported browsers that doesn't support HTML5 File API
    $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
    return false;
}
}

//progress bar function
function OnProgress(event, position, total, percentComplete)
{
   //Progress bar
$('#progressbox').show();
$('#progressbar').width(percentComplete + '%') //update progressbar percent complete
$('#statustxt').html(percentComplete + '%'); //update status text
if(percentComplete>50)
    {
        $('#statustxt').css('color','#000'); //change status text to white after 50%
    }
}

//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
} 

}); 

</script>


<div id="pagewrap">
<div id="content">
    <!-- /#sidebar -->

    <article class="post clearfix">

        <header id="titleindex">
            <h1 class="post-title">Upload Your PDF Reports</a></h1>
        </header>
            <form enctype="multipart/form-data" id="MyUploadForm" name="MyUploadForm" action="processuploads.php" method="post">
            <p>
                <label for="title"><strong>Title: </strong></label>
            </p>
            <p>
                <input type="text" name="title" size="40"/>
            </p>
            <p>
                <label for="description"><strong>Description: </strong></label> 
            </p>
            <p> 
                <textarea name="description" rows="6" cols="40" id="textareaupload"></textarea>
            </p>
            <p>
                <label for="filepath"><strong>Filepath: </strong></label> 
            </p>
            <p>
                <input id="FileInput" name="FileInput" type="file" title="Choose the reports file path" />
            </p>
             <div id="progressbox" ><div id="progressbar"></div ><div id="statustxt">0%</div></div>
             <div id="output"></div>
            <br/>
             <input type="submit"  id="submit-btn" value="Upload" />
             <img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
            </form>


    </article>
</div>
CodeX
  • 313
  • 1
  • 14
user2320010
  • 93
  • 1
  • 8
  • `HTTP_X_REQUESTED_WITH` might not be set, which would result in your script dying to a blank white page. Try putting a few more `die('some description')` sprinkled in your script to determine where it's getting stuck. – degenerate Feb 05 '14 at 15:05
  • I put in the debug and it picked up an error – user2320010 Feb 05 '14 at 15:11
  • I have changed the memory limits, no difference – user2320010 Feb 05 '14 at 15:13
  • That is not an error, that is just your code spitting back out to the page. Look at the first few lines of your script and you will notice those are just comments that the script author wrote. – degenerate Feb 05 '14 at 15:15
  • My error has changed now to "die('Something wrong with upload! Is "upload_max_filesize" set correctly?');" – user2320010 Feb 05 '14 at 15:23
  • I don't know what else to tell you, there could be a lot wrong here. Try putting a trailing `/` on the end of your upload path in the script, so `$UploadDirectory = 'C:\xampp\htdocs\ReportBazaar\reports\';` -- basically the script is not able to move the uploaded file. Try uploading a very small file for testing, like a 2KB text file. – degenerate Feb 05 '14 at 15:25
  • 1
    thanks for the advice, ill give it a go and if it doesnt work, ill try it again from scratch taking it slower – user2320010 Feb 05 '14 at 15:29
  • The file upload size is usually limited by the PHP.ini which you can change: http://stackoverflow.com/questions/2184513/php-change-the-maximum-upload-file-size If uploading a small file doesn't work then its a problem with the way your script is handling the upload – CodeX Jul 03 '15 at 12:33
  • Does that upload directory exist? – CodeX Jul 03 '15 at 12:39

0 Answers0