jquery.form文件上载适用于本地系统但不适用于服务器 - 在服务器上提交后显示的空白页面

时间:2014-11-30 08:11:37

标签: php jquery forms jquery-mobile ajaxform

我使用jquery.form插件进行文件上传(从http://malsup.com/下载的代码)。它在我的本地计算机上工作正常,但在服务器上提交表单后显示空白页面。我已为要上载文件的目录设置了文件权限777。 “开箱即用”代码在服务器上运行良好。但是,我已将其合并到我的jquery移动设置中,并添加了数据库操作和文件删除表单。虽然它在本地工作,但它在服务器上显示空白页面。没有任何错误显示,文件没有上传,数据库没有更新。似乎根本不执行处理代码。我试图在表单处理代码的开头回应一些东西,但也没有发生,所以看起来ajax表单没有被提交。

以下是表单的代码,第二个是处理的代码。

<?php
    require_once ("lib/required.php");
    $_SESSION['login_data'] = get_login_data();

    # Login Protected Page - send them back home
    if (!$_SESSION['login_data']['user_logged_in']){ # not logged in
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;                       
        header ( "Location: " . $redirect_url ); # must be logged in - send them to homepage
        exit;
    } elseif ($_SESSION['login_data']['group_title'] != 'Landlord'){ # logged in but not a Landlord
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;                       
        header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
        exit;
    } elseif (isset($_GET['memid']) && $_GET['memid'] != $_SESSION['login_data']['id']){ # logged in but memid in url is no match (typed in?)
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;                       
        header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
        exit;
    } elseif (isset($_GET['propid'])){ 
        if (!$foo = sql_get_results_array("SELECT * FROM " . DBPREFIX . "tbl_property WHERE property_id = " . $_GET['propid'] . " AND landlord_id = " . $_GET['memid'])){ # logged in but propid in url is no match (typed in?)
            $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;                       
            header ( "Location: " . $redirect_url ); # id vs property mismatch - send them to homepage
            exit;
        }
    }

    # DO NOT include the code below on PayPalP Pay Subscription Page
    # This code MUST BE INCLUDED on every Login Protected Page
    # check subscription and send them to PayPal if not valid
    if (!valid_subscription($_SESSION['login_data']['id'],$_SESSION['login_data']['membership_expiry'],$_SESSION['login_data']['grace_expiry'],$_SESSION['login_data']['subscription_fee'])){ 
        $_SESSION['popup_msg_id'] = 37; # this is to popup a "final call" message
        $redirect_url = "http://" . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . "/" . PAYPAL_PAY_SUBSCRIPTION_PAGE . "?memid=" . $_SESSION['login_data']['id'];
        header ( "Location: " . $redirect_url ); # send them to referring page where resulting messages will be displayed
        exit;
    }
    # DO NOT include the code above on PayPalP Pay Subscription Page

# End-of-Housekeeping

    if (isset($_GET['memid'])){
        $member_id = $_GET['memid']; # get landlord id from url
    } else {
        $member_id = $_SESSION['login_data']['id']; # get landlord id from login        
    }

    if (isset($_GET['propid'])){ # this is for when coming from property details page with a selected property id in url
        $property_id = $_GET['propid']; # get property id from url
        $my_post_list['property-list-form-submitted'] = "1"; # fake "list" form submission to force appropriate form contents
        $my_post_list['property-list'] = $property_id;
        $property_selected = TRUE;
    }

    if ($_POST['property-list-form-submitted'] == "1") { # form submitted - property selected - copy $_POST to own array
        $my_post_list = $_POST;
        if ($my_post_list['property-list'] == 0){ # insert new data - redirect to property details page
            $redirect_url = "http://" . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . "/" . LANDLORD_PROPERTY_DETAILS_PAGE . "?memid=" . $_SESSION['login_data']['id'] . "&action=addprop";
            header ( "Location: " . $redirect_url ); # send them to property details page
            exit;
        } else {
            $property_id = $my_post_list['property-list'];
            $property_selected = TRUE;
        }
    }

    $property_list  = sql_get_results_array( "SELECT * FROM " . DBPREFIX . "tbl_property WHERE landlord_id = " . $member_id); # get list of all properties & details for this landlord in 2-dimensional associative array

    if ($my_post_list['property-list-form-submitted'] == "1") { # form submitted - property selected - display all property details
        $property_selected = TRUE;
        $property_data  = sql_get_results_array( "SELECT * FROM " . DBPREFIX . "tbl_property WHERE landlord_id = " . $member_id . " AND property_id = " . $my_post_list['property-list']);

    }

    if ($_POST['remove-pic-form-submitted'] == "1"){ # delete saved image that was clicked upon

        if (!db("DELETE FROM " . DBPREFIX . "tbl_property_picture WHERE property_id = " . $property_id . " AND landlord_id = '" . $member_id . "' AND picture_path = '" . $_POST['remove-this-path'] . "' AND picture_filename = '" . $_POST['remove-this-file'] . "'")){ # delete didn't work
            $_SESSION['popup_msg_id'] = 14; # this is to popup error message if delete fails
        } # /if

        $propimage = $_POST['remove-this-path'] . $_POST['remove-this-file'];
        // See if it exists before attempting deletion on it
        if (file_exists($propimage)) {
            unlink($propimage); // Delete now
        } 
        // See if it exists again to be sure it was removed
        if (file_exists($propimage)) {
            echo "Problem deleting " . $propimage;
        }

        $propthumb = $_POST['remove-this-path'] . "thumb_" . $_POST['remove-this-file'];
        // See if it exists before attempting deletion on it
        if (file_exists($propthumb)) {
            unlink($propthumb); // Delete now
        } 
        // See if it exists again to be sure it was removed
        if (file_exists($propthumb)) {
            echo "Problem deleting " . $propthumb;
        }
    } # /if file delete form submitted

?>
<!doctype html>
<html>
<head>
    <title><?php echo $page_title ;?></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <?php include("inc/pl_css.inc"); ?>
    <link href="css/image-upload.css" rel="stylesheet" type="text/css" />
    <?php include("inc/pl_js.inc"); ?>
    <script type="text/javascript"> 
        $(document).ready(function() { 
        //elements
        var progressbox         = $('#progressbox'); //progress bar wrapper
        var progressbar         = $('#progressbar'); //progress bar element
        var statustxt           = $('#statustxt'); //status text element
        var submitbutton        = $("#SubmitButton"); //submit button
        var myform              = $("#UploadForm"); //upload form
        var output              = $("#output"); //ajax result output element
        var completed           = '0%'; //initial progressbar value
        var FileInputsHolder    = $('#AddFileInputBox'); //Element where additional file inputs are appended
        var MaxFileInputs       = 10; //Maximum number of file input boxes

        // adding and removing file input box
        var i = $("#AddFileInputBox div").size() + 1;
        $("#AddMoreFileBox").click(function () {
                event.returnValue = false;
                if(i < MaxFileInputs)
                {
                    $('<span><input type="file" id="fileInputBox" size="20" name="file[]" class="addedInput" value=""/><a href="#" class="removeclass small2"><img src="img/close_icon.gif" border="0" /></a></span>').appendTo(FileInputsHolder);
                    i++;
                }
                return false;
        });

        $("body").on("click",".removeclass", function(e){
                event.returnValue = false;
                if( i > 1 ) {
                        $(this).parents('span').remove();i--;
                }

        }); 

        $("#ShowForm").click(function () {
          $("#uploaderform").slideToggle(); //Slide Toggle upload form on click
        });

        $(myform).ajaxForm({
            beforeSend: function() { //brfore sending form
                submitbutton.attr('disabled', ''); // disable upload button
                statustxt.empty();
                progressbox.show(); //show progressbar
                progressbar.width(completed); //initial value 0% of progressbar
                statustxt.html(completed); //set status text
                statustxt.css('color','#000'); //initial color of status text

            },
            uploadProgress: function(event, position, total, percentComplete) { //on progress
                progressbar.width(percentComplete + '%') //update progressbar percent complete
                statustxt.html(percentComplete + '%'); //update status text
                if(percentComplete>50)
                    {
                        statustxt.css('color','#fff'); //change status text to white after 50%
                    }else{
                        statustxt.css('color','#000');
                    }

                },
            complete: function(response) { // on complete
                output.html(response.responseText); //update element with received data
                myform.resetForm();  // reset form
                submitbutton.removeAttr('disabled'); //enable submit button
                progressbox.hide(); // hide progressbar
                $("#uploaderform").slideUp(); // hide form after upload
            }
        });

        }); 
    </script> 
</head>
<body>

<!-- property-images-page -->
   <div data-role="page" id="property-details-page" class="globalpage" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>"> 
        <script type="text/javascript"> function loadPage(url){document.location.href = url;};</script>

        <!-- this .inc file contains 5 panels: login/forgot/register/reset/profile - <div>s with data-role="panel" are inside this file -->
            <?php include("inc/pl_user_options_panel.inc"); ?>
        <!-- /user-options-panel -->        

        <div data-role="panel" id="menu-panel" data-position="left" data-display="overlay">
            <?php include("inc/pl_menu_panel.inc"); ?>
        </div><!-- /menu-panel -->      

        <!-- top header, non-scrolling, shows two action buttons on sides & user data in the middle -->
        <div data-role="header" data-position="fixed">
            <?php include("inc/pl_data_role_header.inc"); ?>
        </div> <!-- /header -->

        <div role="main" class="ui-content">
            <!-- page load popup handler -->      
            <?php include("inc/pl_popup_handler.inc"); ?>
            <!-- scrolling page header with PeterLandlord logo -->
            <?php include("inc/pl_page_header.inc");?>

            <div class="formbox">
            <?php # property selection form ?>
            <form name="property-list-form" class="form" action="<?php echo $_SERVER['PHP_SELF'];?>?memid=<?php echo $member_id;?>" method="post">
                <input type="hidden" name="property-list-form-submitted" value="1"/>
                <div id="property-list-div" class="ui-field-contain">
                    <label for="property-list" class="<?php echo $message['msg_class'];?>"><b></label>
<?php 
                if ($my_post_list['property-list-form-submitted'] != "1" || sizeof($property_data) == 0) { # form not submitted
?>
                    <select name="property-list" id="property-list" data-native-menu="false" onChange="this.form.submit()">
                        <option value="choose-one" data-placeholder="true"><?php echo get_contents(600); ?></option>
                        <option value="0"><?php echo get_contents(601); ?></option>
<?php
                } else { # form submitted
?>
                    <select name="property-list" id="property-list" data-native-menu="false" onChange="this.form.submit()">
<?php 
                    if ($my_post_list['property-list'] != "0") { # an existing property selected
?>          
                        <option value="<?php echo($my_post_list['property-list']);?>"><?php echo get_contents(602); ?> 
<?php 
                            echo 
                            $property_data[0]['address_line'].", ".
                            $property_data[0]['address_locality'].", ".
                            $property_data[0]['address_state'].", ".
                            $property_data[0]['address_postcode'];
                            $skip_this_property = $property_data[0]['property_id'];
?>
                        </option>
<?php 
                    } # /if an existing property selected
?>
                        <option value="0"><?php echo get_contents(601); ?></option>
<?php
                } # /else
            if ($my_post_list['property-list-form-submitted'] == "1" && $my_post_list['property-list'] == "0") { # add new property selected
                # do nothing
            } else { # display remaining properties
                for ($i=0; $i<sizeof($property_list); $i++){
                    if ($property_list[$i]['property_id'] != $skip_this_property){ # Don't display selected property in the list - it is displayed above 
?>          
                        <option value="<?php echo $property_list[$i]['property_id'];?>">
<?php 
                            echo 
                            $property_list[$i]['address_line'].", ".
                            $property_list[$i]['address_locality'].", ".
                            $property_list[$i]['address_state'].", ".
                            $property_list[$i]['address_postcode'];
?>
                        </option>
<?php
                    } # /if add new property selected
                } # /for
            } # /if Don't display selected property
?>          
                        </select>
                    </div> <!-- /property-list-div -->
                </form> <!-- /property-list-form -->
            </div> <!-- formbox for property selection-->
<?php 
        if ($property_selected){ # only show stored images & image upload form if property is selected

            $sql = "SELECT * FROM " . DBPREFIX . "tbl_property_picture WHERE property_id = " . $property_id . " AND  landlord_id = " . $member_id;
            if (!($property_pics = sql_get_results_array($sql))){
                $no_images = TRUE;
            } else {
                $no_images = FALSE;
            }
?>          
            <div class="formbox">
            <table align="center" border="0" cellpadding="4" cellspacing="0">
            <tr>
<?php 
            if ($no_images){
?>
                <td align="center"><img src="<?php echo PROPERTY_IMG_FOLDER ;?>noimages.png" alt="Thumbnail" width="100" height="100"></td>
<?php 
            } else {
                for ($i=0; $i<sizeof($property_pics); $i++){
                    list($ImageWidth,$ImageHeight)=getimagesize($property_pics[$i]['picture_path'] . $property_pics[$i]['picture_filename']);
?>
                    <td align="center">
                        <a href="#popup<?php echo $i;?>" data-rel="popup" data-transition="pop" class="ui-btn-<?php echo $_SESSION['login_data']['data_theme'];?>"><img src="<?php echo $property_pics[$i]['picture_path'];?><?php echo $property_pics[$i]['picture_thumbname'];?>" alt="Thumbnail<?php echo $i;?>" height="100px" width="100px"></a>
                        <br>
                        <form name="delete-form-<?php echo $i;?>" id="delete-form-<?php echo $i;?>" class="form" action="<?php echo $_SERVER['PHP_SELF'];?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>" method="post">
                            <input type="hidden" name="remove-pic-form-submitted" value="1"/>
                            <input type="hidden" name="remove-this-path" value="<?php echo $property_pics[$i]['picture_path'];?>"/>
                            <input type="hidden" name="remove-this-file" value="<?php echo $property_pics[$i]['picture_filename'];?>"/>
                            <a href="#" onClick="document.getElementById('delete-form-<?php echo $i;?>').submit()" class="ui-corner-all ui-btn ui-shadow ui-icon-delete ui-btn-icon-right ui-btn-inline""></a>
                        </form>
                    </td>

                    <div data-role="popup" id="popup<?php echo $i;?>" class="ui-content" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" style="max-width:1000px;">
                        <a href="#" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a>
                        <p class="txtcopyright"><img src="<?php echo $property_pics[$i]['picture_path'];?><?php echo $property_pics[$i]['picture_filename'];?>" alt="Image<?php echo $i;?>" width="<?php echo $ImageWidth;?>" height="<?php echo $ImageHeight;?>"></p>
                    </div>
<?php 
                } # /for
            } # /if no images
?>
            </tr>
            </table>
            </div> <!-- formbox for image display-->

            <div class="formbox">
                <div id="uploaderform">
                    <form action="<?php echo LANDLORD_PROPERTY_IMAGES_PROCESS;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>" method="post" enctype="multipart/form-data" name="UploadForm" id="UploadForm">
                        <input type="hidden" name="max-to-upload" value="<?php echo 10 - sizeof($property_pics);?>"/>
                        <h1>Property image file upload</h1>
                        <p>Up to 10 images can by added with each image file size less than 1MB!</p>

                        <label>Images
                        <span class="small"><a href="#" id="AddMoreFileBox">Add More Images</a></span>
                        </label>
                        <div id="AddFileInputBox"><input id="fileInputBox" style="margin-bottom: 5px;" type="file"  name="file[]"/></div>
                        <div class="sep_s"></div>

                        <button type="submit" class="button" id="SubmitButton">Upload</button>

                        <div id="progressbox"><div id="progressbar"></div ><div id="statustxt">0%</div ></div>
                    </form>
                </div>
                <div id="uploadResults">
                    <div align="center" style="margin:20px;"><a href="#" id="ShowForm">Toggle Upload Form</a></div>
                    <div id="output"></div>
                </div>
            </div> <!-- formbox -->
<?php 
        } # /if property selected
?>          
            <div class="formbox">
                <hr>
                <table class="fixed">
                    <tr>
                        <td><button onClick="loadPage('<?php echo LANDLORD_PROPERTY_DETAILS_PAGE;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>');" data-rel="external" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" class="ui-btn ui-corner-all ui-icon-action"><?php echo get_contents(618)?></button></td>
                        <td>
<?php                       if ($property_selected){ # only show this button if property is selected ?>
                                <button type="reset" onClick="loadPage('<?php echo LANDLORD_PROPERTY_IMAGES_FORM;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>');" data-rel="external" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" class="ui-btn ui-corner-all">Refresh View</button>
<?php                       }?>
                        </td>
                        <td><button onClick="loadPage('<?php echo LANDLORD_PROPERTY_FEATURES_PAGE;?>?memid=<?php echo $member_id;?>&propid=<?php echo $property_id;?>');" data-rel="external" data-theme="<?php echo $_SESSION['login_data']['data_theme'];?>" class="ui-btn ui-corner-all ui-icon-action"><?php echo get_contents(609)?></button></td>
                    </tr>
                </table>
            </div> <!-- formbox2 -->
        </div> <!-- /role-main -->  

        <div data-role="footer" data-position="fixed">
            <?php include("inc/pl_page_footer.inc"); ?>
        </div> <!-- /footer --> 
    </div>
<!-- /property-images-page -->
</body>
</html>

表格处理代码:

<?php
# pl_landlord_property_img_upl_proc.php

# Housekeeping
    require_once ("lib/required.php");
    $_SESSION['login_data'] = get_login_data();

    # Login Protected Page - send them back home
    if (!$_SESSION['login_data']['user_logged_in']){ # not logged in
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
        header ( "Location: " . $redirect_url ); # must be logged in - send them to homepage
        exit;
    } elseif ($_SESSION['login_data']['group_title'] != 'Landlord'){ # logged in but not a Landlord
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
        header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
        exit;
    } elseif (isset($_GET['memid']) && $_GET['memid'] != $_SESSION['login_data']['id']){ # logged in but memid in url is no match (typed in?)
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
        header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
        exit;
    } elseif (isset($_GET['propid'])){
        if (!$foo = sql_get_results_array("SELECT * FROM " . DBPREFIX . "tbl_property WHERE property_id = " . $_GET['propid'] . " AND landlord_id = " . $_GET['memid'])){ # logged in but propid in url is no match (typed in?)
            $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
            header ( "Location: " . $redirect_url ); # id vs property mismatch - send them to homepage
            exit;
        } else {
            # go through...
        }
    } else {
        $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . '/' . HOME_PAGE;
        header ( "Location: " . $redirect_url ); # id mismatch - send them to homepage
        exit;
    }

    # DO NOT include the code below on PayPalP Pay Subscription Page
    # This code MUST BE INCLUDED on every Login Protected Page
    # check subscription and send them to PayPal if not valid
    if (!valid_subscription($_SESSION['login_data']['id'],$_SESSION['login_data']['membership_expiry'],$_SESSION['login_data']['grace_expiry'],$_SESSION['login_data']['subscription_fee'])){
            $_SESSION['popup_msg_id'] = 37; # this is to popup a "final call" message
            $redirect_url = "http://" . $_SERVER['HTTP_HOST'] . APPLICATION_FOLDER . "/" . PAYPAL_PAY_SUBSCRIPTION_PAGE . "?memid=" . $_SESSION['login_data']['id'];
            header ( "Location: " . $redirect_url ); # send them to referring page where resulting messages will be displayed
            exit;
    }
    # DO NOT include the code above on PayPalP Pay Subscription Page

# End-of-Housekeeping

    $member_id = $_GET['memid'];
    $property_id = $_GET['propid'];

    // If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini

 //Some Settings
    $ThumbSquareSize        = 100; //Thumbnail will be 100x100
    $BigImageMaxSize        = 1000; //Image Maximum height or width
    $ThumbPrefix            = "thumb_"; //Normal thumb Prefix
    $DestinationDirectory   = PROPERTY_IMG_FOLDER; //Upload Directory ends with / (slash)
    $Quality                = 90;

    //ini_set('memory_limit', '-1'); // maximum memory!

    foreach($_FILES as $file){
        // some information about image we need later.
        $ImageName      = $file['name'];
        $ImageSize      = $file['size'];
        $TempSrc        = $file['tmp_name'];
        $ImageType      = $file['type'];


        if (is_array($ImageName)){
            $c = count($ImageName);
            echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
            echo '<tr>';
            if ($_POST['max-to-upload'] < 0){
                $max_to_upload = 0;
            } else {
                $max_to_upload = $_POST['max-to-upload'];
            }           
            for ($i=0; $i < $c; $i++){
                if ($max_to_upload == 0){ 
                    echo '<div class="error">Only 10 files in total allowed!<br>Delete some to upload more.</div>';
                    break;
                }
                $max_to_upload--;
                $processImage = true;   

                if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i])){
                    echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
                } else {
                    //Validate file + create image from uploaded file.
                    switch(strtolower($ImageType[$i]))
                    {
                        case 'image/png':
                            $CreatedImage = imagecreatefrompng($TempSrc[$i]);
                            break;
                        case 'image/gif':
                            $CreatedImage = imagecreatefromgif($TempSrc[$i]);
                            break;
                        case 'image/jpeg':
                        case 'image/pjpeg':
                            $CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
                            break;
                        default:
                            $processImage = false; //image format is not supported!
                    }
                    //get Image Size
                    list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);

                    //Get file extension from Image name, this will be re-added after random name
                    $ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
                    $ImageExt = str_replace('.','',$ImageExt);

                    //Construct a new image name (with time plus counter) for our new image.
                    $NewImageName = $member_id . $property_id . time()+$i . '.' . $ImageExt;

                    //Set the Destination Image path with Random Name
                    $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
                    $DestRandImageName          = $DestinationDirectory.$NewImageName; //Name for Big Image

                    //Resize image to our Specified Size by calling resizeImage function.
                    if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i])){
                        //Create a square Thumbnail right after, this time we are using cropImage() function
                        if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i])){
                            echo 'Error Creating thumbnail';
                        } # /if !cropImage
                        /*
                        At this point we have succesfully resized and created thumbnail image
                        We can render image to user's browser and/or store information in the database
                        */

                        //Get New Image Size
                        list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
                        echo '<td align="center"><a href="' . PROPERTY_IMG_FOLDER . $NewImageName . '" data-rel="popup" data-transition="pop" class="ui-btn-' . $_SESSION['login_data']['data_theme'] . '"><img src="' . PROPERTY_IMG_FOLDER . $ThumbPrefix.$NewImageName . '" alt="Thumbnail" height="100px" width="100px"></a></td>';
                        // Insert info into database table
                        $sql = "INSERT INTO " . DBPREFIX . "tbl_property_picture (property_id,landlord_id,picture_path,picture_filename,picture_thumbname)
                                VALUES (" . $property_id . "," . $member_id . ",'" . PROPERTY_IMG_FOLDER . "','" . $NewImageName . "','" . $ThumbPrefix.$NewImageName . "')";
                        if (!db($sql)){
                            echo '<div class="error">Error inserting into database</div>';
                        }
                    } else {
                        echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>'; //output error
                    } # /if $processImage && resizeImage
                } # /else (!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
            } # /for
            echo '</tr>';
            echo '</table>';
        } # /is_array($ImageName
    } # /foreach    

// This function will proportionally resize image 
    function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
    {
        //Check Image size is not 0
        if($CurWidth <= 0 || $CurHeight <= 0) 
        {
            return false;
        }

        //Construct a proportional size of new image
        $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight); 
        $NewWidth           = ceil($ImageScale*$CurWidth);
        $NewHeight          = ceil($ImageScale*$CurHeight);

        if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
        {
            $NewWidth = $CurWidth;
            $NewHeight = $CurHeight;
        }
        $NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);
        // Resize Image
        if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
        {
            switch(strtolower($ImageType))
            {
                case 'image/png':
                    imagepng($NewCanves,$DestFolder);
                    break;
                case 'image/gif':
                    imagegif($NewCanves,$DestFolder);
                    break;          
                case 'image/jpeg':
                case 'image/pjpeg':
                    imagejpeg($NewCanves,$DestFolder,$Quality);
                    break;
                default:
                    return false;
            }
            if(is_resource($NewCanves)) { 
              imagedestroy($NewCanves); 
            } 
            return true;
        }
    }

//This function corps image to create exact square images, no matter what its original size!
    function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
    {    
        //Check Image size is not 0
        if($CurWidth <= 0 || $CurHeight <= 0){
            return false;
        }

        //abeautifulsite.net has excellent article about "Cropping an Image to Make Square"
        //http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
        if($CurWidth>$CurHeight){
            $y_offset = 0;
            $x_offset = ($CurWidth - $CurHeight) / 2;
            $square_size    = $CurWidth - ($x_offset * 2);
        } else {
            $x_offset = 0;
            $y_offset = ($CurHeight - $CurWidth) / 2;
            $square_size = $CurHeight - ($y_offset * 2);
        } # /else

        $NewCanves  = imagecreatetruecolor($iSize, $iSize); 
        if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)){
            switch(strtolower($ImageType)){
                case 'image/png':
                    imagepng($NewCanves,$DestFolder);
                    break;
                case 'image/gif':
                    imagegif($NewCanves,$DestFolder);
                    break;          
                case 'image/jpeg':
                case 'image/pjpeg':
                    imagejpeg($NewCanves,$DestFolder,$Quality);
                    break;
                default:
                    return false;
            } # /switch

            if(is_resource($NewCanves)) { 
              imagedestroy($NewCanves); 
            } # /if is_resource
            return true;

        } # /if imagecopyresampled
    } # /function

?>

有人可以指点我一个解决方案,谢谢......

0 个答案:

没有答案