can someone help me fix my code?

Posted by user267490 on Stack Overflow See other posts from Stack Overflow or by user267490
Published on 2010-05-04T06:31:40Z Indexed on 2010/05/04 6:38 UTC
Read the original article Hit count: 236

Filed under:

Hi, I have this code I been working on but I'm having a hard time for it to work. I did one but it only works in php 5.3 and I realized my host only supports php 5.0! do I was trying to see if I could get it to work on my sever correctly, I'm just lost and tired lol

<?php

//Temporarily turn on error reporting
@ini_set('display_errors', 1);
error_reporting(E_ALL);

// Set default timezone (New PHP versions complain without this!)

    date_default_timezone_set("GMT");

// Common

    set_time_limit(0);

    require_once('dbc.php');
    require_once('sessions.php');

    page_protect();

// Image settings

    define('IMG_FIELD_NAME', 'cons_image');

    // Max upload size in bytes (for form)
    define ('MAX_SIZE_IN_BYTES', '512000');

    // Width and height for the thumbnail
    define ('THUMB_WIDTH', '150');
    define ('THUMB_HEIGHT', '150');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <title>whatever</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <style type="text\css">
        .validationerrorText { color:red; font-size:85%; font-weight:bold; }
    </style>
</head>
<body>
    <h1>Change image</h1>
<?php

$errors = array();

// Process form
if (isset($_POST['submit'])) {

    // Get filename
    $filename = stripslashes($_FILES['cons_image']['name']);

    // Validation of image file upload
    $allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
    if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) {

        $errors['img_empty'] = true;

    } elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') && (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) {

        $errors['img_type'] = true;

    } elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] > MAX_SIZE_IN_BYTES)) {

        $errors['img_size'] = true;

    } elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) {

        $errors['img_error'] = true;

    } elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) > 200) {

        $errors['img_nametoolong'] = true;

    } elseif ( (file_exists("\\uploads\\{$username}\\images\\banner\\{$filename}")) || (file_exists("\\uploads\\{$username}\\images\\banner\\thumbs\\{$filename}")) ) {

        $errors['img_fileexists'] = true;
    }

    if (! empty($errors)) { 
        unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
    }

    // Create thumbnail
    if (empty($errors)) {

        // Make directory if it doesn't exist
        if (!is_dir("\\uploads\\{$username}\\images\\banner\\thumbs\\")) {

            // Take directory and break it down into folders
            $dir = "uploads\\{$username}\\images\\banner\\thumbs";
            $folders = explode("\\", $dir);

            // Create directory, adding folders as necessary as we go (ignore mkdir() errors, we'll check existance of full dir in a sec)
            $dirTmp = '';
            foreach ($folders as $fldr) {
                if ($dirTmp != '') { $dirTmp .= "\\"; }
                $dirTmp .= $fldr;
                mkdir("\\".$dirTmp); //ignoring errors deliberately!
            }

            // Check again whether it exists
            if (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) {
                $errors['move_source'] = true;
                unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
            }
        }

        if (empty($errors)) {

            // Move uploaded file to final destination
            if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
                $errors['move_source'] = true;
                unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file

            } else {

                // Create thumbnail in new dir
                if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
                    $errors['thumb'] = true;
                    unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                }
            }
        }
    }

    // Record in database
    if (empty($errors)) {

        // Find existing record and delete existing images
        $sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
        $result = mysql_query($sql);
        if (!$result) {
            unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
            unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
            die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
        }
        $numResults = mysql_num_rows($result);
        if ($numResults == 1) {
            $row = mysql_fetch_assoc($result);

            // Delete old files
            unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
            unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
        }

        // Update/create record with new images
        if ($numResults == 1) {
            $sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
        } else {
            $sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
        }
        $result = mysql_query($sql);
        if (!$result) {
            unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
            unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
            die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
        }
    }

    // Print success message and how the thumbnail image created
    if (empty($errors)) {
        echo "<p>Thumbnail created Successfully!</p>\n";
        echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" />\n";
        echo "<br />\n";
    }
}
if (isset($errors['move_source'])) { echo "\t\t<div>Error: Failure occurred moving uploaded source image!</div>\n"; }
if (isset($errors['thumb'])) { echo "\t\t<div>Error: Failure occurred creating thumbnail!</div>\n"; }
?>
    <form action="" enctype="multipart/form-data" method="post">
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE_IN_BYTES; ?>" />
        <label for="<?php echo IMG_FIELD_NAME; ?>">Image:</label> <input type="file" name="<?php echo IMG_FIELD_NAME; ?>" id="<?php echo IMG_FIELD_NAME; ?>" />
<?php
if (isset($errors['img_empty'])) { echo "\t\t<div class=\"validationerrorText\">Required!</div>\n"; }
if (isset($errors['img_type'])) { echo "\t\t<div class=\"validationerrorText\">File type not allowed! GIF/JPEG/PNG only!</div>\n"; }
if (isset($errors['img_size'])) { echo "\t\t<div class=\"validationerrorText\">File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!</div>\n"; }
if (isset($errors['img_error'])) { echo "\t\t<div class=\"validationerrorText\">File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}</div>\n"; }
if (isset($errors['img_nametoolong'])) { echo "\t\t<div class=\"validationerrorText\">Filename too long! 200 Chars max!</div>\n"; }
if (isset($errors['img_fileexists'])) { echo "\t\t<div class=\"validationerrorText\">An image file already exists with that name!</div>\n"; }
?>
        <br /><input type="submit" name="submit" id="image1" value="Upload image" />
    </form>
</body>
</html>
<?php

#################################
#
#      F U N C T I O N S
#
#################################

/*
 *  Function: make_thumb
 *
 *  Creates the thumbnail image from the uploaded image
 *  the resize will be done considering the width and
 *  height defined, but without deforming the image
 *
 *  @param   $sourceFile   Path anf filename of source image
 *  @param   $destFile     Path and filename to save thumbnail as
 *  @param   $new_w        the new width to use
 *  @param   $new_h        the new height to use
*/
function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false)
{
    if ($new_w === false) { $new_w = THUMB_WIDTH; }
    if ($new_h === false) { $new_h = THUMB_HEIGHT; }

    // Get image extension
    $ext = strtolower(getExtension($sourceFile));

    // Copy source
    switch($ext) {
        case 'jpg':
        case 'jpeg':
            $src_img = imagecreatefromjpeg($sourceFile);
            break;
        case 'png':
            $src_img = imagecreatefrompng($sourceFile);
            break;
        case 'gif':
            $src_img = imagecreatefromgif($sourceFile);
            break;
        default:
            return false;
    }
    if (!$src_img) { return false; }

    // Get dimmensions of the source image
    $old_x = imageSX($src_img);
    $old_y = imageSY($src_img);

    // Calculate the new dimmensions for the thumbnail image
    // 1. calculate the ratio by dividing the old dimmensions with the new ones
    // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
    //    and the height will be calculated so the image ratio will not change
    // 3. otherwise we will use the height ratio for the image
    //    as a result, only one of the dimmensions will be from the fixed ones
    $ratio1 = $old_x / $new_w;
    $ratio2 = $old_y / $new_h;
    if ($ratio1 > $ratio2) {
        $thumb_w = $new_w;
        $thumb_h = $old_y / $ratio1;
    } else {
        $thumb_h = $new_h;
        $thumb_w = $old_x / $ratio2;
    }

    // Create a new image with the new dimmensions
    $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);

    // Resize the big image to the new created one
    imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

    // Output the created image to the file. Now we will have the thumbnail into the file named by $filename
    switch($ext) {
        case 'jpg':
        case 'jpeg':
            $result = imagepng($dst_img, $destFile);
            break;
        case 'png':
            $result = imagegif($dst_img, $destFile);
            break;
        case 'gif':
            $result = imagejpeg($dst_img, $destFile);
            break;
        default:
            //should never occur!
    }
    if (!$result) { return false; }

    // Destroy source and destination images
    imagedestroy($dst_img);
    imagedestroy($src_img);

    return true;
}

/*
 *  Function: getExtension
 *
 *  Returns the file extension from a given filename/path
 *
 *  @param   $str   the filename to get the extension from
*/
function getExtension($str)
{
    return pathinfo($str, PATHINFO_EXTENSION);
}

?>

© Stack Overflow or respective owner

Related posts about php