简体   繁体   中英

Undefined index in first lines of thumbnail generation script

I'm using a script i found to generate thumbnails, but i'm getting an error in the first in lines 3 and 4. I'm guessing one of the functions is deprecated (it's a year old), but i really have no idea. GD support is enabled. I'm reading linked questions and realizing there is something i'm not getting about isset , but i'm not sure how to write this for both 'image' and 'width', it also seems like it is set in the next few lines. All help appreciated.

Notice: Undefined index: image in C:\\xampp\\htdocs\\thumbnail\\thumbnail.php on line 3

Notice: Undefined index: width in C:\\xampp\\htdocs\\thumbnail\\thumbnail.php on line 4

<?php

$imageSrc = (string)$_GET['image'];    
$width = $_GET['width']; 

if (is_numeric($width) && isset($imageSrc)){ 
    header('Content-type: image/jpeg');
    makeThumb($imageSrc, $width); 
}

function makeThumb($src,$newWidth) { 
    // read the source image given 
    $srcImage = imagecreatefromjpeg($src); 
    $width = imagesx($srcImage); 
    $height = imagesy($srcImage); 

    // find the height of the thumb based on the width given 
    $newHeight = floor($height*($newWidth/$width)); 

    // create a new blank image 
    $newImage = imagecreatetruecolor($newWidth,$newHeight);

     // copy source image to a new size 
     imagecopyresized($newImage,$srcImage,0,0,0,0,$newWidth,$newHeight,$width,$height);

     // create the thumbnail 
     imagejpeg($newImage); 
} 
?>

I realize generating scripts on the fly for every page load is not efficient, but i'm just trying to get something working.

I made the the third change suggested by Lawrence and i'm still getting an error:

Notice: Undefined variable: width in C:\\xampp\\htdocs\\thumbnail\\thumbnail.php on line 13

You need to check there set before using:

Change:

$imageSrc = (string)$_GET['image'];    
$width = $_GET['width']; 

to

$imageSrc = (isset($_GET['image']))?$_GET['image']:null;    
$width =  (isset($_GET['width']))?$_GET['width']:null;

or the if else way

if(isset($_GET['image'])){$imageSrc = $_GET['image'];}else{$imageSrc =null;}
if(isset($_GET['width'])){$width = $_GET['width'];}else{$width =null;}

Or you can forget about thos 2 lines and just do:

if (isset($_GET['width']) && is_numeric($_GET['width']) && isset($_GET['image'])){ 
    header('Content-type: image/jpeg');
    makeThumb(basename($_GET['image']), $_GET['width']); 
}

Use isset

Try

$imageSrc = isset($_GET['image']) ? $_GET['image'] : null;    
$width = isset($_GET['width']) ? $_GET['width'] : null ; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM