How to debug an image creation - php

I am trying to fix/debug a site where all images in the site are being generated by an script. Another developer created this. Now all the images for some reason don’t work.
I am trying to debug the code and try to break it somewhere where it should work so that then I can see whats broken and stablish a baseline. But I cant find a way to debug this properly.
Could anyone point me on the right direction on how to debug the following script or what could be broken? Nothing that I do seems to work.
Update: Thanks Pekka 웃 comment I can now see the error and it says Warning: imagejpeg(): Filename cannot be empty in /var/www/vhosts/mysticindia.co.uk/httpdocs/inc/class.images.php on line 496
that line is the imagejpg() that is after the line
if ($imageModify == "grey") {
imagefilter($this->imageResized, IMG_FILTER_GRAYSCALE);
}
CODE
<?php
class images {
var $imageID;
var $imageData;
var $image;
var $width;
var $height;
var $imageResized;
function __construct($imageID = null) {
if ($imageID !== null) {
$this->imageID = $imageID;
$this->imageData = $this->getImageInfo();
}
}
function removeImage() {
if ($this->imageID) {
$query = "DELETE FROM Images ";
$query .= "WHERE ImageID = '%s' ";
$result = RunQuery($query,__LINE__);
$query = sprintf($query, mysql_real_escape_string($this->imageID));
$result = RunQuery($query,__LINE__);
tableEmpty("Images");
}
}
private function buildImageQuery($options=array()) {
global $maxItems;
$maxItems = ((isset($options["maxItems"])) && (!empty($options["maxItems"]))) ? $options["maxItems"] : $maxItems;
$pageID = isset($options["pageID"]) ? $options["pageID"] : "";
$orderBy = ((isset($options["orderBy"])) && (!empty($options["orderBy"]))) ? $options["orderBy"] : "ImageIndex";
$sortBy = ((isset($options["sortBy"])) && (!empty($options["sortBy"]))) ? $options["sortBy"] : "ASC";
$groupBy = (isset($options["groupBy"])) ? $options["groupBy"] : "";
$groupBy = (isset($options["groupBy"])) ? $options["groupBy"] : "";
$limit = isset($options["limit"]) ? $options["limit"] : "";
$searchArray = isset($options["searchArray"]) ? $options["searchArray"] : "";
$recordOffset = ($pageID - 1) * $maxItems;
$query = "SELECT SQL_CALC_FOUND_ROWS i.ImageID, ImageName, ImageIndex FROM Images i ";
$query .= "WHERE i.ImageID != '0' ";
if ((isset($searchArray["catalogue"])) && (!empty($searchArray["catalogue"]))) {
$query .= "AND Catalogue = '" . $searchArray["catalogue"] . "' ";
}
if ((isset($searchArray["catalogueID"])) && (!empty($searchArray["catalogueID"]))) {
if (is_array($searchArray["catalogueID"])) {
$count = 0;
$query .= "AND (";
foreach ($searchArray["catalogueID"] as $catalogueID) {
$count++;
$query .= "CatalogueID= '" . $catalogueID . "' ";
if ($count < count($searchArray["catalogueID"])) {
$query .= "OR ";
}
}
$query .= ") ";
} else {
$query .= "AND CatalogueID= '" . $searchArray["catalogueID"] . "' ";
}
}
if ((isset($searchArray["imageName"])) && (!empty($searchArray["imageName"]))) {
$query .= "AND ImageName = '" . $searchArray["imageName"] . "' ";
}
if ((isset($groupBy)) && (!empty($groupBy))) {
$query .= "GROUP BY " . $groupBy . " ";
}
if ((isset($groupBy)) && (!empty($groupBy))) {
$query .= "GROUP BY " . $groupBy . " ";
}
if ($orderBy) {
$query .= "ORDER BY $orderBy $sortBy ";
}
if (($pageID) && (empty($limit))) {
$query .= "LIMIT $recordOffset, $maxItems ";
} else if (!empty($limit)) {
$query .= "LIMIT $limit ";
}
return $query;
}
function getImages($options=array()) {
global $maxItems;
$maxItems = ((isset($options["maxItems"])) && (!empty($options["maxItems"]))) ? $options["maxItems"] : $maxItems;
$pageID = isset($options["pageID"]) ? $options["pageID"] : "";
$recordOffset = ($pageID - 1) * $maxItems;
$dataArray = array();
$listArray = array();
$maxPages = 0;
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (($pageID) && (empty($limit))) {
$query2 = "SELECT FOUND_ROWS() AS NoItems ";
$result2 = RunQuery($query2);
$row2 = mysql_fetch_assoc($result2);
$maxPages = ceil($row2["NoItems"] / $maxItems);
}
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_assoc($result)) {
$listArray[] = $row["ImageID"];
}
$dataArray["maxPages"] = $maxPages;
$dataArray["results"] = $listArray;
return $dataArray;
}
}
function listImages($options=array()) {
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result)) {
$dataArray = array();
while ($row = mysql_fetch_assoc($result)) {
$key = $row["ImageID"];
$value = $row["ImageName"];
$dataArray[$key] = $value;
}
return $dataArray;
} else {
return false;
}
}
function manageImage($options=array()) {
global $sesAdminID;
$imageInfo = isset($options["imageInfo"]) ? $options["imageInfo"] : "";
$catalogue = isset($options["catalogue"]) ? $options["catalogue"] : "";
$catalogueID = isset($options["catalogueID"]) ? $options["catalogueID"] : "";
$imageCaption = isset($options["imageCaption"]) ? $options["imageCaption"] : "";
$imageName = isset($imageInfo["imageName"]) ? $imageInfo["imageName"] : "";
$imageWidth = isset($imageInfo["imageWidth"]) ? $imageInfo["imageWidth"] : "";
$imageHeight = isset($imageInfo["imageHeight"]) ? $imageInfo["imageHeight"] : "";
$imageType = isset($imageInfo["imageType"]) ? $imageInfo["imageType"] : "image/jpeg";
$imageIndex = isset($imageInfo["imageIndex"]) ? $imageInfo["imageIndex"] : "";
if ($this->imageID) {
$query = "UPDATE Images SET ";
$query .= "ImageName = '%s', ";
$query .= "ImageWidth = '%s', ";
$query .= "ImageHeight = '%s', ";
$query .= "ImageType = '%s', ";
$query .= "Catalogue = '%s', ";
$query .= "CatalogueID = '%s', ";
$query .= "ImageCaption = '%s', ";
$query .= "ImageIndex = '%s' ";
$query .= "WHERE ImageID = '" . $this->imageID . "' ";
} else {
$query = "INSERT INTO Images SET ";
$query .= "ImageName = '%s', ";
$query .= "ImageWidth = '%s', ";
$query .= "ImageHeight = '%s', ";
$query .= "ImageType = '%s', ";
$query .= "Catalogue = '%s', ";
$query .= "CatalogueID = '%s', ";
$query .= "ImageCaption = '%s', ";
$query .= "ImageIndex = '%s' ";
}
$query = sprintf($query, mysql_real_escape_string($imageName),
mysql_real_escape_string($imageWidth),
mysql_real_escape_string($imageHeight),
mysql_real_escape_string($imageType),
mysql_real_escape_string($catalogue),
mysql_real_escape_string($catalogueID),
mysql_real_escape_string($imageCaption),
mysql_real_escape_string($imageIndex));
$result = RunQuery($query,__LINE__);
$this->imageID = (!empty($this->imageID)) ? $this->imageID : mysql_insert_id();
return $this->imageID;
}
function updateCaption($imageCaption) {
$query = "UPDATE Images SET ";
$query .= "ImageCaption = '%s' ";
$query .= "WHERE ImageID = '%s' ";
$query = sprintf($query, mysql_real_escape_string($imageCaption),
mysql_real_escape_string($this->imageID));
$result = RunQuery($query,__LINE__);
}
function reOrderImages($options=array()) {
$catalogue = isset($options["catalogue"]) ? $options["catalogue"] : "";
$catalogueID = isset($options["catalogueID"]) ? $options["catalogueID"] : "";
$sortOrder = isset($options["sortOrder"]) ? str_replace("Image_", "", $options["sortOrder"]) : "";
if (!empty($sortOrder)) {
$sortArray = explode(",", $sortOrder);
foreach ($sortArray as $order => $imageID) {
$query = "UPDATE Images SET ";
$query .= "ImageIndex = '%s' ";
$query .= "WHERE ImageID = '%s' ";
$query .= "AND Catalogue = '%s' ";
$query .= "AND CatalogueID = '%s' ";
$query = sprintf($query, mysql_real_escape_string($order),
mysql_real_escape_string($imageID),
mysql_real_escape_string($catalogue),
mysql_real_escape_string($catalogueID));
$result = RunQuery($query,__LINE__);
}
}
}
function returnImageType($options=array()) {
$imageName = ((isset($options["imageName"])) && (!empty($options["imageName"]))) ? $options["imageName"] : "";
$imageType = ((isset($options["imageType"])) && (!empty($options["imageType"]))) ? $options["imageType"] : "";
// Image Extensions
$imgExt["pjpeg"] = "jpg";
$imgExt["jpeg"] = "jpg";
$imgExt["gif"] = "gif";
$imgExt["png"] = "png";
$imgExt["jpg"] = "jpg";
// Image Types
$imgType["pjpeg"] = "jpeg";
$imgType["jpeg"] = "jpeg";
$imgType["jpg"] = "jpeg";
$imgType["gif"] = "gif";
$imgType["png"] = "png";
if ($imageType) {
$tempImageType = explode("/", strtolower($imageType));
$tempImageType = str_replace(" ", "", $tempImageType[count($tempImageType)-1]);
} else if ($imageName) {
$tempImageType = explode("/", strtolower($imageName));
$tempImageType = explode(".", $tempImageType[count($tempImageType)-1]);
$tempImageType = $tempImageType[count($tempImageType)-1];
} else {
return "";
}
$resizeInfo = array();
$resizeInfo["imageType"] = isset($imgType[$tempImageType]) ? $imgType[$tempImageType] : "jpeg";
$resizeInfo["imageExt"] = isset($imgExt[$tempImageType]) ? $imgExt[$tempImageType] : "jpg";
return $resizeInfo;
}
function createImageName($imageFolder,$imageName) {
global $documentRoot;
if (file_exists($documentRoot . $imageFolder . $imageName)) {
$imageName = strtotime("now") . "_" . $imageName;
}
return $imageName;
}
function uploadImage($options=array()) {
global $documentRoot, $imageFolder, $maxImageW;
$imageInfo = array();
$imageLocal = ((isset($options["tmp_name"])) && (!empty($options["tmp_name"]))) ? $options["tmp_name"] : "";
$imageType = ((isset($options["type"])) && (!empty($options["type"]))) ? $options["type"] : "";
$imageName = ((isset($options["name"])) && (!empty($options["name"]))) ? $options["name"] : "";
$imageSize = ((isset($options["size"])) && (!empty($options["size"]))) ? $options["size"] : "";
$functionArray = array("imageName"=>$imageName,"imageType"=>$imageType);
$imageTypeInfo = $this->returnImageType($functionArray);
$tempImageType = $imageTypeInfo["imageType"];
$tempImageExt = $imageTypeInfo["imageExt"];
$row = getimagesize($imageLocal);
$width = $row[0];
$height = $row[1];
$imageName = $this->createImageName($imageFolder,fileNameFix($imageName) . "." . $tempImageExt);
if ($width <= $maxImageW) {
copy($imageLocal, $documentRoot . $imageFolder . $imageName);
$imageInfo["imageWidth"] = $width;
$imageInfo["imageHeight"] = $height;
} else {
$functiontoRun = "imagecreatefrom" . $tempImageType;
$this->image = $functiontoRun($imageLocal);
$functionArray = array("origWidth"=>$width,"origHeight"=>$height,"imageWidth"=>$maxImageW);
$resizeImage = $this->resizeImage($functionArray);
$newImageWidth = $resizeImage["CanvasWidth"];
$newImageHeight = $resizeImage["CanvasHeight"];
$image = imagecreatetruecolor($newImageWidth, $newImageHeight);
imagecopyresampled($image, $this->image, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
$functiontoRun = "image" . $tempImageType;
#$functiontoRun($image, $documentRoot . $imageFolder . $imageName) or die("can not create image");
$imageInfo["imageWidth"] = $newImageWidth;
$imageInfo["imageHeight"] = $newImageHeight;
}
$imageInfo["imageType"] = $imageType;
$imageInfo["imageName"] = $imageName;
return $imageInfo;
}
function uploadImages($options=array()) {
$catalogue = isset($options["catalogue"]) ? $options["catalogue"] : "";
$catalogueID = isset($options["catalogueID"]) ? $options["catalogueID"] : "";
$newImages = isset($options["newImages"]) ? $options["newImages"] : "";
$functionArray = array("searchArray"=>$options);
$imageIndex = $this->returnImageIndex($functionArray);
foreach ($newImages as $newImage) {
$imageIndex++;
$imageCaption = $newImage["caption"];
$imageInfo = $this->uploadImage($newImage);
$functionArray = array("imageCaption"=>$imageCaption,"imageInfo"=>$imageInfo,"catalogue"=>$catalogue,"catalogueID"=>$catalogueID,"imageIndex"=>$imageIndex);
$this->imageID = 0;
$this->manageImage($functionArray);
}
}
private function getDimensions($newWidth, $newHeight, $option) {
switch ($option) {
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
case 'square':
$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function getSizeByFixedHeight($newHeight) {
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}
private function getSizeByFixedWidth($newWidth) {
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}
private function getSizeByAuto($newWidth, $newHeight) {
if ($this->height < $this->width) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} elseif ($this->height > $this->width) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
if ($newHeight < $newWidth) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
// *** Sqaure being resized to a square
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
}
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function getOptimalCrop($newWidth, $newHeight) {
$heightRatio = $this->height / $newHeight;
$widthRatio = $this->width / $newWidth;
if ($heightRatio < $widthRatio) {
$optimalRatio = $heightRatio;
} else {
$optimalRatio = $widthRatio;
}
$optimalHeight = $this->height / $optimalRatio;
$optimalWidth = $this->width / $optimalRatio;
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight) {
// *** Find center - this will be used for the crop
$optionArray["cropStartX"] = ( $optimalWidth / 2) - ( $newWidth /2 );
$optionArray["cropStartY"] = ( $optimalHeight/ 2) - ( $newHeight/2 );
return $optionArray;
}
public function resizeImage($options=array()) {
$imageCrop = ((isset($options["imageCrop"])) && (!empty($options["imageCrop"]))) ? $options["imageCrop"] : "landscape";
$this->width = ((isset($options["origWidth"])) && (!empty($options["origWidth"]))) ? $options["origWidth"] : 0;
$this->height = ((isset($options["origHeight"])) && (!empty($options["origHeight"]))) ? $options["origHeight"] : 0;
$newWidth = ((isset($options["imageWidth"])) && (!empty($options["imageWidth"]))) ? $options["imageWidth"] : 0;
$newHeight = ((isset($options["imageHeight"])) && (!empty($options["imageHeight"]))) ? $options["imageHeight"] : 0;
if ((empty($newHeight)) && ($imageCrop == "square")) {
$newHeight = $newWidth;
}
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $imageCrop);
if ($imageCrop == 'square') {
$tempOptions = $this->crop($optionArray["optimalWidth"], $optionArray["optimalHeight"], $newWidth, $newHeight);
$optionArray["cropStartX"] = $tempOptions["cropStartX"];
$optionArray["cropStartY"] = $tempOptions["cropStartY"];
}
$optionArray["CanvasWidth"] = $newWidth;
$optionArray["CanvasHeight"] = (!empty($newHeight)) ? $newHeight : $optionArray["optimalHeight"];
return $optionArray;
}
function showImage($options=array()) {
global $documentRoot, $imageFolder;
$imageSize = ((isset($options["imageSize"])) && (!empty($options["imageSize"]))) ? $options["imageSize"] : "";
$imageCrop = ((isset($options["imageCrop"])) && (!empty($options["imageCrop"]))) ? $options["imageCrop"] : "";
$imageType = ((isset($options["imageType"])) && (!empty($options["imageType"]))) ? $options["imageType"] : "";
$imageName = ((isset($options["imageName"])) && (!empty($options["imageName"]))) ? $options["imageName"] : "";
$imageModify = ((isset($options["imageModify"])) && (!empty($options["imageModify"]))) ? $options["imageModify"] : "";
$imageQuality = ((isset($options["imageQuality"])) && (!empty($options["imageQuality"]))) ? $options["imageQuality"] : 100;
$imageFolder = ((isset($options["imageFolder"])) && (!empty($options["imageFolder"]))) ? $options["imageFolder"] : $imageFolder;
if (($imageType) || ($imageSize) || ($imageCrop)) {
if ((!empty($imageSize)) && (!empty($imageType))) {
$imageSize .= ucfirst($imageType);
} else if ((empty($imageSize)) && (!empty($imageType))) {
$imageSize .= strtolower($imageType);
}
$imageSize .= (!empty($imageCrop)) ? ucfirst($imageCrop) : "";
$tempWidth = lcfirst($imageSize . "W");
$tempHeight = lcfirst($imageSize . "H");
global $$tempWidth, $$tempHeight;
$maxWidth = isset($$tempWidth) ? $$tempWidth : 0;
$maxHeight = isset($$tempHeight) ? $$tempHeight : 0;
}
if (empty($maxWidth)) {
$tempWidth = "maxImageW";
$tempHeight = "maxImageH";
global $$tempWidth, $$tempHeight;
$maxWidth = isset($$tempWidth) ? $$tempWidth : 0;
$maxHeight = isset($$tempHeight) ? $$tempHeight : 0;
}
if (empty($this->imageID)) {
$searchArray = array("imageName"=>$imageName);
$functionArray = array("searchArray"=>$searchArray);
$this->imageID = $this->returnImageID($functionArray);
}
$imageData = $this->getImageInfo();
if (is_array($imageData)) {
$imageName = $imageData["ImageName"];
$width = $imageData["ImageWidth"];
$height = $imageData["ImageHeight"];
$imageType = $imageData["ImageType"];
} else {
$imageType = "";
}
$functionArray = array("imageName"=>$imageName,"imageType"=>$imageType);
$imageTypeInfo = $this->returnImageType($functionArray);
$tempImageType = $imageTypeInfo["imageType"];
$tempImageExt = $imageTypeInfo["imageExt"];
$thisImage = $documentRoot . $imageFolder . $imageName;
if (file_exists($thisImage)) {
if ((empty($width)) || (empty($height))) {
$row = getimagesize($thisImage);
$width = $row[0];
$height = $row[1];
}
if ((isset($maxWidth)) && (($width > $maxWidth) || ($height > $maxHeight))) {
$functiontoRun = "imagecreatefrom" . $tempImageType;
$this->image = $functiontoRun($thisImage);
if (!$this->image) {
$this->image = imagecreatefromjpeg($thisImage);
}
$functionArray = array("imageCrop"=>$imageCrop,"origWidth"=>$width,"origHeight"=>$height,"imageWidth"=>$maxWidth,"imageHeight"=>$maxHeight);
$resizeImage = $this->resizeImage($functionArray);
$optimalWidth = $resizeImage['optimalWidth'];
$optimalHeight = $resizeImage['optimalHeight'];
$canvasWidth = $resizeImage["CanvasWidth"];
$canvasHeight = $resizeImage["CanvasHeight"];
$cropStartX = isset($resizeImage["cropStartX"]) ? $resizeImage["cropStartX"] : 0;
$cropStartY = isset($resizeImage["cropStartY"]) ? $resizeImage["cropStartY"] : 0;
// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
$background = imagecolorallocate($this->imageResized, 255, 255, 255);
imagefill ($this->imageResized, 0, 0, $background);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);
// *** if option is 'crop', then crop too
if ($imageCrop == 'square') {
$crop = $this->imageResized;
//imagedestroy($this->imageResized);
// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($canvasWidth , $canvasHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $canvasWidth, $canvasHeight , $canvasWidth, $canvasHeight);
}
if ($imageModify == "grey") {
imagefilter($this->imageResized, IMG_FILTER_GRAYSCALE);
}
header("Content-type: image/$tempImageType");
imagejpeg($this->imageResized, "", $imageQuality);
exit();
} else {
header("Content-type: image/$tempImageType");
$image = imagecreatefromjpeg($thisImage);
imagejpeg($image);
exit();
}
}
else {
header("HTTP/1.0 404 Not Found");
exit();
}
}
private function grayscale($r, $g, $b) {
return (($r*0.299)+($g*0.587)+($b*0.114));
}
function returnImageID($options=array()) {
$imageID = 0;
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result) != 0) {
$row = mysql_fetch_assoc($result);
$imageID = $row["ImageID"];
}
return $imageID;
}
function returnImageIndex($options=array()) {
$imageIndex = 0;
$query = $this->buildImageQuery($options);
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result) != 0) {
$row = mysql_fetch_assoc($result);
$imageIndex = $row["ImageIndex"];
}
return $imageIndex;
}
private function getImageInfo() {
$query = "SELECT ImageID, ImageName, ImageWidth, ImageHeight, ImageType, Catalogue, CatalogueID, ImageCaption, ImageIndex FROM Images i ";
$query .= "WHERE ImageID= '%s' ";
$query = sprintf($query, mysql_real_escape_string($this->imageID));
$result = RunQuery($query,__LINE__);
if (mysql_num_rows($result) != 0) {
return mysql_fetch_assoc($result);
}
}
}
?>

While you state:
I am trying to fix/debug a site where all images in the site are being
generated by an script.
Looking at this chunk of code implies that the images for the site are actually stored in the file system in some way via that file_exists() check:
$thisImage = $documentRoot . $imageFolder . $imageName;
if (file_exists($thisImage)) {
if ((empty($width)) || (empty($height))) {
$row = getimagesize($thisImage);
$width = $row[0];
$height = $row[1];
}
if ((isset($maxWidth)) && (($width > $maxWidth) || ($height > $maxHeight))) {
$functiontoRun = "imagecreatefrom" . $tempImageType;
$this->image = $functiontoRun($thisImage);
if (!$this->image) {
$this->image = imagecreatefromjpeg($thisImage);
}
Also, looking at the tons of repetitive code coupled with this odd set of if ( checks I would concentrate on the code around function showImage($options=array()) {.
Now responding to your comment where you tell us what the site is & the fact the images are not loading.
Loading a URL like this:
http://www.mysticindia.co.uk/images/galleries/small/square/JCxTPFAsMGBgCmA.jpg
Shows an error—I assume that comes from your debugging—like this:
_image.phpA: Resource id #11 Warning: imagejpeg(JC0jQFgsMGBgCmA.jpg): failed to open stream: Permission denied in /var/www/vhosts/mysticindia.co.uk/httpdocs/inc/class.images.php on line 496
The failed to open stream tells me that while you are saying the images are being generated by the script, file system interaction is clearly happening at some point.
Then this error of:
Permission denied in /var/www/vhosts/mysticindia.co.uk/httpdocs/inc/class.images.php on line 496
Seems to tell me the error is not in your code, but in the file system permissions. It seems that the script is indeed generating derivative thumbnails & other versions of the parent image. But at some point the script is caching them to the file system in some way. Unclear where the source images come from—a BLOB in the database—but my best advice right now is to look at the file system permissions for the site & see if anything changed.
I mean you—or others—didn’t screw around with this script yet it stopped working right? I bet you anything that the directory this script uses to cache derivatives no longer exists or has incorrect ownership or permissions. Something like that would choke this process.

Related

Directory being deleted randomly by unknown script

I have set up a simple "Facebook" like timeline system for my friend to be able to upload statuses with images for his users to see. It seemed to all be working well although the file which stores the images keeps being deleted, and I can't seem to purposely cause the problem myself so I have no idea what is removing this directory?
I have added the upload/remove scripts below to see if anybody might be able to assist me here? I can't seem to find any part of the script which would delete the main image directory on its own?
PLEASE BARE IN MIND - This is still unfinished, and is nowhere near secure just yet, we are in testing phase and need to fix this problem before I can work on perfecting the system.
The main folder for storage of the images is post_images, this is the directory which is being deleted.
REMOVE DIR FUNCTION -
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) rrmdir($file); else unlink($file);
}
rmdir($dir);
}
DECLINE POSTS -
if(isset($_GET['decline_post'])){
$post_id = $conn->real_escape_string($_GET['decline_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
DELETE POST -
if(isset($_GET['delete_post'])){
$post_id = $conn->real_escape_string($_GET['delete_post']);
$getimagefolder = mysqli_fetch_assoc(mysqli_query($conn, "SELECT `post_image_folder` FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'"));
$image_folder = $getimagefolder['post_image_folder'];
mysqli_query($conn,"DELETE FROM `Pto6LsuQ_posts` WHERE `post_id` = '$post_id'");
$direc = 'post_images/'.$image_folder;
if (file_exists($direc)) {
rrmdir($direc);
} else {
}
header("Location: members_area.php");
}
UPLOAD POST -
if(isset($_POST['new_post'])){
$post_status = $conn->real_escape_string($_POST['status']);
$user_id = $_SESSION['user_id'];
if(!empty($_FILES['images']['tmp_name'])){
$length = 9;
$search = true; // allow the loop to begin
while($search == true) {
$rand_image_folder = substr(str_shuffle("0123456789"), 0, $length);
if (!file_exists('../post_images/'.$rand_image_folder)) {
$search = false;
}
}
mkdir("../post_images/".$rand_image_folder);
foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['images']['name'][$key];
$file_size = $_FILES['images']['size'][$key];
$file_tmp = $_FILES['images']['tmp_name'][$key];
$file_type = $_FILES['images']['type'][$key];
$check_file_type = substr($file_type, 0, strrpos( $file_type, '/'));
if($check_file_type !== 'image'){
header('Location: ../members_area.php?posterror=1');
}
$extensions = array("jpeg","jpg","png","JPEG","JPG","PNG");
$format = trim(substr($file_type, strrpos($file_type, '/') + 1));
if(in_array($format,$extensions) === false){
header('Location: ../members_area.php?posterror=1');
} else {
move_uploaded_file($file_tmp,"../post_images/".$rand_image_folder."/".$file_name);
$file = "../post_images/".$rand_image_folder."/".$file_name;
$cut_name = substr($file, strpos($file, "/") + 1);
$cut_name = explode('/',$cut_name);
$cut_name = end($cut_name);
$newfile = "../post_images/".$rand_image_folder."/thb_".$cut_name;
$info = getimagesize($file);
list($width, $height) = getimagesize($file);
$max_width = '350';
$max_height = '250';
//try max width first...
$ratio = $max_width / $width;
$new_width = $max_width;
$new_height = $height * $ratio;
//if that didn't work
if ($new_height > $max_height) {
$ratio = $max_height / $height;
$new_height = $max_height;
$new_width = $width * $ratio;
}
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($file);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($file);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($file);
$image = imagecreatetruecolor($new_width, $new_height);
$photo = imagecreatefromjpeg($file);
imagecopyresampled($image, $photo, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image, $newfile, 70);
}
}
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','$rand_image_folder','0','$post_public')");
} else {
if($account_type < 4){
$post_public = 1;
} else {
$post_public = 0;
}
mysqli_query($conn,"INSERT INTO `Pto6LsuQ_posts`
(post_id,post_user_id,post_date_time,post_status,post_image_folder,post_likes,post_public_status)
VALUES ('','$user_id',NOW(),'$post_status','','0','$post_public')");
}
header('Location: ../members_area.php?posterror=2');
}

PHP image upload memory limit reduction

I use a PHP file to upload images to my server from my web application and have recently hit some memory limit issues that I was hoping someone with more experience than me could help with. Most of the images uploaded have been from mobiles so the file size is very manageable but recently there have been some uploads from an SLR camera that have been causing the issues. These images are around 7-8MB in size and I had assumed our PHP memory limit of 64MB would handle this. Upon inspection I found the imagecreatefromjpeg() function in our crop function to be the culprit although I assume the memory has been filled up before this despite using imagedestroy() to clear any previously created images. Upon using ini_set('memory_limit') to up the limit to a much higher value I found the script worked as expected but I would prefer a cleaner solution. I have attached the code below and any help would be greatly appreciated.
ini_set('memory_limit', '256M');
if(isset($_POST)) {
############ Edit settings ##############
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$ThumbPrefix = "thumbs/"; //Normal thumb Prefix
$DestinationDirectory = '../../../uploads/general/'; //specify upload directory ends with / (slash)
$PortfolioDirectory = '../../../images/portfolio/';
$Quality = 100; //jpeg quality
##########################################
$imID = intval($_POST['imageID']);
$image = $_POST['image'];
$data = $image['data'];
$name = $image['name']; //get image name
$width = $image['width']; // get original image width
$height = $image['height'];// orig height
$type = $image['type']; //get file type, returns "image/png", image/jpeg, text/plain etc.
$desc = $image['desc'];
$album = intval($image['album']);
$customer = intval($image['customer']);
$tags = $image['tags'];
$allTags = $_POST['allTags'];
$portType = intval($image['portType']);
$rating = intval($image['rating']);
$imData = array();
if(strlen($data) < 500) {
$dParts = explode('?', $data);
$path = $dParts[0];
$base64 = file_get_contents($path);
$data = 'data:' . $type . ';base64,' . base64_encode($base64);
}
function base64_to_jpeg($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
function base64_to_png($base64_string, $output_file) {
$img = str_replace('data:image/png;base64,', '', $base64_string);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$im = imagecreatefromstring($data);
if ($im !== false) {
imagepng($im, $output_file);
imagedestroy($im);
}
return $output_file;
}
if($stmt = $db -> prepare("UPDATE `images` SET name = ?, type = ?, description = ?, width = ?, height = ?, rating = ?, portType = ?, customer = ?, album = ?, dateModified = NOW() WHERE ID = ?")) {
$stmt -> bind_param("sssiiiiiii", $name, $type, $desc, $width, $height, $rating, $portType, $customer, $album, $imID);
if (!$stmt->execute()) {
echo false;
} else {
$delTags = "DELETE FROM tagLink WHERE imageID = $imID";
if(!$db->query($delTags)) {
echo $db->error;
}
if(sizeof($tags) > 0) {
foreach($tags as $tag) {
$tagQ = "INSERT INTO tagLink (imageID, tag) VALUES ($imID, '$tag')";
if(!$db->query($tagQ)) {
echo $db->error;
}
}
}
switch(strtolower($type))
{
case 'png':
$fname = $name . '(' . $imID . ').png';
$file = $DestinationDirectory . $fname;
$portfile = $PortfolioDirectory . $fname;
$thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
$CreatedImage = base64_to_png($data,$file);
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
$fname = $name . '(' . $imID . ').jpeg';
$file = $DestinationDirectory . $fname;
$portfile = $PortfolioDirectory . $fname;
$thumbDest = $DestinationDirectory . $ThumbPrefix . $fname;
$CreatedImage = base64_to_jpeg($data,$file);
break;
default:
die('Unsupported File!'); //output error and exit
}
array_push($imData, $imID);
array_push($imData, $name);
array_push($imData, $type);
array_push($imData, $portType);
echo json_encode($imData);
if(!cropImage($width,$height,$ThumbSquareSize,$thumbDest,$CreatedImage,$Quality,$type))
{
echo 'Error Creating thumbnail';
}
}
$stmt -> close();
} else {
/* Error */
printf("Prepared Statement Error: %s\n", $db->error);
}
/* Close connection */
$db -> close();
include '../cron/updatePortfolio.php';
}
//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$type)
{
//Check Image size is not 0
if($CurWidth <= 0 || $CurHeight <= 0)
{
return false;
}
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);
}
switch(strtolower($type))
{
case 'png':
$imageX = imagecreatefrompng ( $SrcImage );
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
$imageX = imagecreatefromjpeg ( $SrcImage );
break;
default:
return false;
}
$NewCanves = imagecreatetruecolor($iSize, $iSize);
if(imagecopyresampled($NewCanves, $imageX, 0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
{
switch(strtolower($type))
{
case 'png':
imagepng($NewCanves,$DestFolder);
break;
case 'jpeg':
case 'pjpeg':
case 'jpeg':
imagejpeg($NewCanves,$DestFolder,$Quality);
break;
default:
return false;
}
if(is_resource($NewCanves)) {
imagedestroy($NewCanves);
}
return true;
}
}
Look in the php.ini at
upload_max_filesize = 40M
post_max_size = 40M
Change 40M to your max size

I need to put resize image 150x130

I need help with image resize I don't know how to put in
<?php
if (isset($_POST['newcover'])) {
////GET image uploading settings
$select_upload_options = mysql_query("SELECT * FROM covers_submit_options");
$uop = mysql_fetch_assoc($select_upload_options);
$poster = $uop['cover_who_post'];
$approve = $uop['cover_approve'];
$server = $uop['cover_server'];
$default_user = $uop['cover_default_user'];
$cover_title = $_POST['title'];
$cover_desc = $_POST['desc'];
$cover_desc2 = $_POST['desc2'];
$cover_date = $_POST['date'];
$cover_tags = $_POST['tags'];
$cover_okvir = $_POST['okvir'];
$cover_velicina = $_POST['velicina'];
$cover_image2 = $_POST['image2'];
$cover_category = $_POST['huge'];
if ($poster != 'user' && $_SESSION['userid'] == '') {
$poster_user = $default_user;
} else {
$poster_user = $_SESSION['userid'];
}
if ($cover_title == '') {
$post_error = '<div class="alert alert-danger"><h3>Unesite Ime i Prezme</h3></div>';
} elseif ($cover_category == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Grad ii Općinu</h3></div>';
} elseif ($cover_date == '') {
$post_error = '<div class="alert alert-danger"><h3>Unesite Datum-Godište Npr. 1965-2016</h3></div>';
} elseif ($cover_okvir == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Izgled Osmrtnice</h3></div>';
} elseif ($poster_user == '') {
$poster_user = '1';
} elseif ($_FILES['photo']['size'] == '1') {
$post_error = '<div class="alert alert-danger"><h3>Please Select Image</h3></div>';
} else {
$post_error = '';
}
if ($post_error == '') {
if ($server == 'amazon') {
////////UPLOAD TO AMAZON/////////////////////
include('includes/amazonUpload.php');
////////UPLOAD TO AMAZON/////////////////////
} else {
////////////REGULAR UPLOADER TO SERVER/////////
list($file, $error) = upload('photo', 'images/covers/', 'jpg,jpeg,gif,png');
list($width, $height, $type, $attr) = ('images/covers/' . $file);
////////////Da bi upload slike mogao da radi uklonio sam dio koda orginal kod je ovaj dolje getimagesize prije zagrade images/covers /////////
if ($width < 0 || $height < 0) {
$post_error = "<div class='alert alert-danger'><h3>The Cover is Small<br>Please note that the Minimum allowed hight is 300px and Minimum Width is 800px </h3></div>";
unlink('images/covers/' . $file);
} else {
$image = 'images/covers/' . $file;
}
////////////REGULAR UPLOADER TO SERVER/////////
$error = $post_error;
}
////Store Into Database
if (!$error) {
$string = $slug;
if (strlen($string) != mb_strlen($string, 'utf-8')) {
$slug = date("M-D-His");
} else {
$slug = preg_replace("/[^a-zA-Z0-9_\-]/", '', $cover_title);
//$slug = preg_replace('/\s+/', '-', $cover_title);
$slug = strtolower($slug);
}
$is_slug_exists = mysql_query("SELECT * FROM covers_posts WHERE post_slug = '$slug' ");
$slug_exsits = mysql_num_rows($is_slug_exists);
if ($slug_exsits != '0') {
$slug = $slug . '-' . date('sy');
} else {
$slug = $slug;
}
$cover_datum = date("d-m-Y");
$insert = mysql_query("INSERT INTO covers_posts VALUES ('',
'$cover_title',
'$cover_desc',
'$cover_desc2',
'$cover_date',
'$cover_tags',
'$cover_okvir',
'$cover_velicina',
'$slug',
'$image',
'$cover_image2',
'$cover_category',
'1',
'$poster_user',
'$approve',
'0',
'0',
'0',
'$cover_datum'
) ");
order_badge($poster_user);
$post_error = '<div class="alert alert-success"><h3>Uspješno Ste Dodali Osmrtnicu , Prebacit će vas za 5 sekundi<br>
Ukolko ste zastali Kliknite Ovde
</h3></div>';
$redir = 'osmrtnica-' . $slug . '.html';
redirect($redir, '5');
} else {
$post_error = '<div class="alert alert-danger"><h3>' . $error . '</h3></div>';
}
} else {
$post_error = $post_error;
}
$smarty->assign('UploadResult', $post_error);
}
ok I know it is older script and I changed later in mysqli connection.
I read manual about upload and resize image now it is resize image but all image are black
elseif ($cover_okvir == '') {
$post_error = '<div class="alert alert-danger"><h3>Izaberite Izgled Osmrtnice</h3></div>';
}
elseif ($poster_user == '') {
$poster_user = '1';
}else{
////////////REGULAR UPLOADER TO SERVER/////////
list($file,$error) = upload('photo','images/covers/','jpg,jpeg,gif,png');
list($width, $height, $type, $attr) = getimagesize('images/covers/'.$file);
$width = 140;
$height = 150;
////////////REGULAR UPLOADER TO SERVER/////////
$src = imagecreatefromstring('images/covers/'.$file);
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height);
imagedestroy($src);
imagepng($dst,'images/covers/'.$file); // adjust format as needed
imagedestroy($dst);
}
$image = 'images/covers/'.$file;
enter code here

getimagesize() error: “failed to open stream: No such file or directory”

i have that problem and i don't know what can i do?
Here is my script :
<?php
include('../include/cfg.php');
if($approval_system == 1) { $ap = 1; } else { $ap = 0; }
$path = "../uploads/";
function resize_img($url, $filename, $ext_p) {
$max_width = 613;
$max_height = 2000;
$destination = '../uploads';
$quality = '100';
$source_pic = ''.$url.'.jpg';
if($ext_p == 'jpg') { $src = #imagecreatefromjpg($destination.'/'.$source_pic); }
if($ext_p == 'png') { $src = #imagecreatefrompng($destination.'/'.$source_pic); }
if($ext_p == 'gif') { $src = #imagecreatefromgif($destination.'/'.$source_pic); }
if($ext_p == 'jpeg') { $src = #imagecreatefromjpeg($destination.'/'.$source_pic); }
list($width,$height)=#getimagesize($destination.'/'.$source_pic);
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if( ($width <= $max_width) && ($height <= $max_height) ){
$tn_width = $width;
$tn_height = $height;
} elseif (($x_ratio * $height) < $max_height){
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
} else {
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
$tmp=#imagecreatetruecolor($tn_width,$tn_height);
#imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);
$destination_pic = ''.$destination.'/'.$filename.'.jpg';
#imagejpeg($tmp,$destination_pic,$quality);
#imagedestroy($src);
#imagedestroy($tmp);
}
function resize_thumb($url, $filename, $ext_p) {
$max_width = 170;
$max_height = 2000;
$destination = '../uploads';
$quality = '100';
$source_pic = ''.$url.'.jpg';
if($ext_p == 'jpg') { $src = #imagecreatefromjpg($destination.'/'.$source_pic); }
if($ext_p == 'png') { $src = #imagecreatefrompng($destination.'/'.$source_pic); }
if($ext_p == 'gif') { $src = #imagecreatefromgif($destination.'/'.$source_pic); }
if($ext_p == 'jpeg') { $src = #imagecreatefromjpeg($destination.'/'.$source_pic); }
list($width,$height)=#getimagesize($destination.'/'.$source_pic);
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if( ($width <= $max_width) && ($height <= $max_height) ){
$tn_width = $width;
$tn_height = $height;
} elseif (($x_ratio * $height) < $max_height){
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
} else {
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
$tmp=#imagecreatetruecolor($tn_width,$tn_height);
#imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);
$destination_pic = ''.$destination.'/'.$filename.'.jpg';
#imagejpeg($tmp,$destination_pic,$quality);
#imagedestroy($src);
#imagedestroy($tmp);
}
$valid_formats = array("jpg", "png", "gif", "jpeg", "JPG", "PNG", "GIF", "JPEG");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*2024)) {
$photo_n = md5(rand(0,999999999999999));
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$photo_n.'.jpg')) {
if($_FILES['photoimg']['type']=='image/png') { $ext_p = 'png'; }
if($_FILES['photoimg']['type']=='image/jpg') { $ext_p = 'jpg'; }
if($_FILES['photoimg']['type']=='image/gif') { $ext_p = 'gif'; }
if($_FILES['photoimg']['type']=='image/jpeg') { $ext_p = 'jpeg'; }
resize_img($photo_n,$photo_n.'_l',$ext_p);
resize_thumb($photo_n,$photo_n.'_t',$ext_p);
$sql_photo = mysql_query("SELECT * FROM `users` WHERE `id` = '".$_SESSION['logged_id']."' LIMIT 1");
while($a=mysql_fetch_array($sql_photo)) {
if($a['photo']!='') {
unlink('../uploads/'.$a['photo'].'_t.jpg');
unlink('../uploads/'.$a['photo'].'_l.jpg');
}
unlink('../uploads/'.$photo_n.'.jpg');
mysql_query("DELETE FROM `ratings` WHERE `to` = '".$a['id']."'");
mysql_query("DELETE FROM `comments` WHERE `to` = '".$a['id']."'");
}
$height = getimagesize($site_url.'/uploads/'.$photo_n.'_t.jpg');
mysql_query("UPDATE users SET `ap` = '".$ap."', `photo` = '".$photo_n."', `size` = '".$height[1]."', `time` = '".time()."' WHERE `id` ='".$_SESSION['logged_id']."' LIMIT 1");
echo '
<img src="'.show_photo($photo_n,170,170,'l').'" style="border-radius:5px;" /><div style="position:absolute;top:0;right:0;padding:12px;padding-right:7px;padding-top:5px;border-radius:110px; width:12px; border-top-left-radius:0;border-bottom-right-radius:0;background-color:#1e7ca7;color:#fff;font-size:14px;cursor:pointer;border-top-right-radius:10px;border:0px solid #000;" class="delete-img">x</div>';
} else {
echo failed;
}
} else {
echo '<div style="width:166px;height:166px;border:2px solid #ff0000;border-radius:5px;"><div style="margin-top:65px;background-color:#ff0000;color:#fff;padding:10px;">'.max_file_size.'</div></div>';
}
} else {
echo '<div style="width:166px;height:166px;border:2px solid #ff0000;border-radius:5px;"><div style="margin-top:65px;background-color:#ff0000;color:#fff;padding:10px;">'.invalid_file_format.'</div></div>';
}
} else {
echo '<div style="width:166px;height:166px;border:2px solid #ff0000;border-radius:5px;"><div style="margin-top:65px;background-color:#ff0000;color:#fff;padding:10px;">'.select_image.'</div></div>';
}
}
?>
And message of this error is:
Warning: getimagesize(localhost/uploads/ad88ba4cacfa04317e7b56db59f9815b_t.jpg): failed to open stream: No such file or directory in C:\wamp\www\js\ajaximage.php on line 122
But this image was uploaded and exist.. what the hell?
122 line:
$height = getimagesize($site_url.'/uploads/'.$photo_n.'_t.jpg');
Please, help.. i don't understand :/
As requested by #usandfriends :)
I assume you've moved files from tmp location, then try a var_dump(getcwd()) to check current working directory, maybe the ../uploads is pointing elsewhere

Why this php script cannot detect images from other directories except from where the index.php is located at?

<?
$start = $_GET[start] ? $_GET[start] : 0 ;
$sortby = $_COOKIE[sortby] ? $_COOKIE[sortby] : "name" ;
if($_GET[sortby]){
$sortby = $_GET[sortby];
setcookie("sortby", $_GET[sortby], time()+86400 );
header("location: index.php");
}
$od = opendir("./");
while($file = readdir($od)){
if( eregi("\.(gif|jpe?g|png)$", $file) ){
$file2 = rawurlencode($file);
$img_arr[$file2] = $file;
$img_arr_filesize[$file2] = filesize($file);
$img_arr_filemtime[$file2] = filemtime($file);
list($imagex, $imagey, $type, $attr) = getimagesize($file);
$img_arr_sizexy[$file2] = $imagex."x".$imagey;
}
}
asort($img_arr);
asort($img_arr_filesize);
asort($img_arr_filemtime);
switch($sortby){
case "time":
$img_arr_final = $img_arr_filemtime;
break;
case "size":
$img_arr_final = $img_arr_filesize;
break;
case "name":
$img_arr_final = $img_arr;
break;
}
$total_images = count($img_arr_final);
foreach($img_arr_final as $k=>$v){
$i++;
if($i < $start+1) continue;
if($i > $start + $pp) break;
$img_name = strlen($img_arr[$k]) > 18 ? substr($img_arr[$k],0,16)."..." :$img_arr[$k];
$alt = $img_arr[$k] . " -|- Last modified: " . date("Y-m-d H:i:s", $img_arr_filemtime[$k]) . " ";
$imgl .= "<div class=\"img_thumb\"><img src=\"index.php?thumb=$k\" alt=\"$alt\" title=\"$alt\" /><p title=\"".$img_arr[$k]."\"><strong>".$img_name. "</strong><br /><span class=\"mini\">".$img_arr_sizexy[$k].", ".round(($img_arr_filesize[$k]/1024))." KB</span></p></div>";
}
for($p=0; $p*$pp < $total_images ; $p++){
$active = ($p*$pp) == $start ? "active" : "" ;
$page_htmo .= "".($p+1)." ";
}
$arr_sortby = array("name"=>"Name", "size"=>"Size", "time"=>"Time");
foreach($arr_sortby as $k=>$v){
if($sortby == $k){
$sortby_html[] = "<strong>$v</strong>";
} else {
$sortby_html[] = "$v";
}
}
$sortby_htmo = implode(" | ", $sortby_html);
function make_thumbnail($updir, $img){
global $thumb_width, $thumb_height;
$thumbnail_width = $thumb_width ? $thumb_width : 120;
$thumbnail_height = $thumb_height ? $thumb_height : 80;
$arr_image_details = GetImageSize("$updir"."$img");
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];
if( $original_width > $original_height ){
$new_width = $thumbnail_width;
$new_height = intval($original_height*$new_width/$original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width*$new_height/$original_height);
}
$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);
if($arr_image_details[2]==1) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; $imgx = "gif"; }
if($arr_image_details[2]==2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; $imgx = "jpeg"; }
if($arr_image_details[2]==3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; $imgx = "png"; }
if( $imgt ) {
$old_image = $imgcreatefrom("$updir"."$img");
$new_image = ImageCreateTrueColor($thumbnail_width, $thumbnail_height);
imageCopyResized($new_image,$old_image,$dest_x,
$dest_y,0,0,$new_width,$new_height,$original_width,$original_height);
header("Content-Type: image/jpeg"); imagejpeg($new_image, NULL, 80);
}
}
if($_GET['thumb']) {
if( in_array($_GET['thumb'], $img_arr) ) make_thumbnail("./", $_GET['thumb']); // against file inclusion
exit();
}
?>
This is a gallery generator script, but it only shows me the pics when they are in the same directory as the script is in, how could I modify it to allow other scripts.
I've tried many tweaks but, nothing works.
It's almost certainly a file permissions issue as you're trying to open the root directory.
$od = opendir("./");
It will work for the directory that the script is in as the script will have permissions to access that directory.
I don't recommend giving PHP permission to access the root folder (even only in read mode) as it is a huge security risk, as theoretically someone could read your passwords file.
Instead you should use a non-root directory to hold the images you want to generate a gallery for and only give read permission to that, i.e.
mkdir /var/images
chmod a+r /var/images

Categories