3

I am trying to develop a PHP based application to upload a file to the web server

the jquery code goes like this

<form action="upload.php" method="post" enctype="multipart/form-data" name="upload">
            <input name="uploaded_file" type="file" 
                   style="border-radius:0px; width:900px; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif" required/>
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            <input type="hidden" name="id" value=<?php echo $getid; ?> />

            <br/>
            <br/>
            <input name="Upload" type="submit" value="Upload" class="btn btn-success btn-large" style="border-radius:0px;" id="uploadfile"/>

        </form>

           <div class="progress" id="progress"> 
               <div class="bar"></div >  
               <div class="percent">0%</div >  
           </div>  
           <div id="status"></div>
       <script src="jquery.js"></script>  
       <script src="jquery.form.js"></script> 
       <script>
            $(document).ready(function(){
                $('#progress').hide();

                $('#uploadfile').click(function(){
                    $('#progress').show();
                  });
            });
        </script> 
        <script>
            (function() {

            var bar = $('.bar');
            var percent = $('.percent');
            var status = $('#status');

            $('form').ajaxForm({
                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                success: function() {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function(xhr) {
                    status.html('Uploaded sucessfull');
                }
            }); 

            })();       
        </script> 

and the php code goes like this

<?php

    include('connect.php'); 
    include('antivirus.php');
    $virusstatus='FALSE';
    function clean($str) 
    {
        $str = @trim($str);
        if(get_magic_quotes_gpc()) 
        {
            $str = stripslashes($str);
        }
        return mysql_real_escape_string($str);
    }

    //Sanitize the POST values
    $filedesc= 'Enter Description';
    $fname=  mt_rand(1000,9999);
    $id=clean($_POST['id']);

    //upload random name/number
    $rd2 = mt_rand(1000,9999)."_File"; 

    //Check 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 != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload"))  {
    //Determine the path to which we want to save this file      
      //$newname = dirname(__FILE__).'/upload/'.$filename;
      $newname="uploads/".$rd2."_".$filename;      


        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) 
        {

            $vsig=scanfile($newname);
            $query=mysql_query("select * from virussig")or die(mysql_error());
            while($image=mysql_fetch_array($query))        
            {
                if($vsig==$image['vsig'])
                {
                    $virusstatus='TRUE';
                }
            }
            if($virusstatus=='TRUE')
            {
                die("This file contains some Virus signatures which is not allowed");
            }
            else
            {
                mysql_query("INSERT INTO up_files (id,fdesc,floc,fdatein,fname) VALUES ('$id','$filedesc','$newname',NOW(),'$fname')"); 
                header("location: iconview.php?id=".$id);           
            }
        }
        } 

    } 

?>

my problem is whenever error occurs in php during file upload,it gives file upload sucessful in jquery. I want the solution to somhow manage the errors got in php and display in jquery please help

Thankyou

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
likith sai
  • 527
  • 1
  • 6
  • 21
  • WHY ALL CAPS in title? And what is your error? Also, `mysql_*` functions are deprecated, use MySQLi / PDO instead. – Raptor May 08 '14 at 04:25
  • 1
    *sidenote:* what will be the content of `antivirus.php` contain? Are you calling Anti-virus software to scan upload file before storing it? – Raptor May 08 '14 at 04:26
  • its a simple function that gets the file data and converts it into hash... – likith sai May 08 '14 at 04:28
  • 1
    It seems there is error handler for `ajaxForm` plugin . try throwing some appropriate messages in else part of `if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))` whenever upload fails – shatheesh May 08 '14 at 04:28
  • code goes like this : – likith sai May 08 '14 at 04:28
  • i didnt get you mr shatheesh.. – likith sai May 08 '14 at 04:30
  • @user3603198 Like Shatheesh has said, your `if`s need an `else` block for eg., you're checking if `$ext!='.exe'` but if it is, you are not creating any error message in the `else`. – AyB May 08 '14 at 04:47
  • Try this [Display PHP errors in ajax request callback](https://stackoverflow.com/a/51412331/11047729) – Don Jan 14 '22 at 07:01

1 Answers1

0

Have something like this in your php code

    if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
    {
         $result = true;
         return json_encode($result);
    }
    else
    {
         $result = false;
         return json_encode($result);
    }

Then in your ajax success call back

    complete: function(xhr,data) {
                if(data === true)
                status.html('Uploaded sucessfull');
                else 
                status.html('Uploaded unsuccessful');
            }

Do check the syntax and json returned as well. Have written this logically.

You can also do it without json_encode. and appropriate return type in ajax call

SSS
  • 1,025
  • 7
  • 17