Jump to content

[SOLVED] Picture upload, resize, lossing my mind, help


Recommended Posts

Hi, all

I am going crazy because I have been working on a project now for about 3 weeks. I am trying to get this last area to work right and I can't. I am at the deadline I have looked at a few tutorials dealing with this and trying to blend them all together but can figure out a few things. Every time I try and change something to the way I want it I get a syntax error or something.

 

I am trying to have an area that someone can upload a file and it will resize it to 640 in width and then make another file and resize it to 125. Then save them in 2 diffrent directories delete the temp file and so on.

 

Also validate that it is an image.

 

I have my first file that the user takes 2 passes on.

1st pass

List out the listing they have from the database. Loops them into where they can select which one they want to play with.

They then click on the link and it brings them to the same file but ?propID= some number.

2nd

The propIDs corrispond to the database. I run a check to make sure that the user that is logged in (gotten from session varible) is the use that can view this part (gotten from the database).

It shows them either all the picture tied to that listing or it trys to create the directories which I have been unsuccessful at. The script runs with no errors. but when I ftp in I see no directories created.

Then if they have less then 10 properties it shows them an upload form

that post to another page

upload.php

Here is where I have most of my problems. I have never had to work with file systems before and so have to run back and forth to the php manual every ten seconds. I have learned a lot but not enough. I want this script to upload the files and then resize them to proper sizing and save them in the dynamically created directories. I also want them renamed to 1, 2, 3, 4, 5, 6,7 and so on for when I read them out.

 

Here are the codes I have so far.

 

addpic.php

<?php @session_start(); ?>
<?php
if(!isset($_SESSION['username'])){
die ("You either are not logged in or you do not have permission to view this page you must log in. If you feel this is a mistake click here to <a href='../logout.php'>log out</a> and then immediatly log back in and try agian.");
}

//get userid needed ad so on
$loginID=$_SESSION['loginID'];
$username=$_SESSION['username'];


include("../constents.php");
mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql' . mysql_error());


if(!isset($_GET['propID'])){

//search the database to see properties that need to be paid for
$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0'";
$result=mysql_query($sql);
$numberProps=mysql_num_rows($result);	

?>


<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<p>You have <?=$numberProps ?> listings in the system.</p>
<p>Please select the property you wish to view and or edit your pictures</p>
<?

while( $row = mysql_fetch_assoc($result)){ 
?>

<? 
//this is the picture echo
echo "<img src='http://www.worldpropertiesonline.net/propimg/".$row['propID']."/th/1.jpg' width='125px' height='94px' />"; 

//followed by the detailed detialed stuff 
?>

<?=$row['title'] ?> <?=$row['propID'] ?>
    <?=$row['whenlisted'] ?>
<?=$row['paidTill'] ?>

    <a href="<?=$_SERVER['PHP_SELF'] ?>?propID=<?=$row['propID'] ?>">Manage this listings pictures</a><br />


<?
}
?>
</body>
</html>
<?





//----------------------------------------------------
//end of first pass
//----------------------------------------------------




} elseif(isset($_GET['propID'])){


//----------------------------------------------------
//start of second pass
//----------------------------------------------------


//function to delete a pic and its thumbnail out of the system.
function picdelete($filename, $property){

$path=$_SERVER['DOCUMENT_ROOT']."/propimg/".$property."/reg/".$filename;
$path2=$_SERVER['DOCUMENT_ROOT']."/propimg/".$property."/th/".$filename;
if (file_exists($path)){
fclose($path);
unlink($path);
}
if (file_exists($path2)){
fclose($path2);
unlink($path2);
}

}



$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0' and propID='".$_POST['propID']."'";
$result=mysql_query($sql);
$numberProps=mysql_num_rows($result);

//checks to see if the propID belongs to the user that is accessing it	
if($numberProps == 1){

$NoNouser=1;

} else {
//either gets the pics or creats a directory if noone has added pics before
$file_path=$_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/th/";
$file_path2=$_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/reg/";
$picarray=array();
	if(is_dir($file_path)){
		$handle=opendir($file_path);
		$pics=1;
		$i=0;
		while(false!==($picloop=readdir($handle))){
			$picarray[$i]=$picloop;	

			$i++;

		}
	} elseif(is_dir($file_path2)) {

		mkdir($file_path, 0777);
		mkdir($file_path2, 0777);
		$pics=0;

	}

}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>World Properties Online</title>

<meta name="keywords" content="glossary,property,real estate,rental,commercial,sale,by owner" />
<meta name="description" content="Welcome to World Properties Online, your guide to property for sale around the world." />
<link href="wpo.css" rel="stylesheet" type="text/css" />


</head>
<body>
<? if ($NoNouser==1){
die ("<p>Sorry but this property does not match our records. Please go back to <a href='".$_SERVER['PHP_SELF']."'>the picture management main area</a> and reslect your property.</p></body></head>");
}

if($pics==0){
echo "You currently do not have any pictures for this listing.";

} else {


$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0' and propID='".$_POST['propID']."'";
$result=mysql_query($sql);

?>
    <p>You have <?=$i ?> pictures related to your listing </p>
    <p>Remember you are only allowed to have ten pictures per listing.</p>
    <form action="" method="post">
    <input type="hidden" name="" value="" />
   <? foreach($picarray as $value){
   
   if(strlen($value) >= 4){
   if(strstr($value, "." )!=1)
   ?>
   <a href="http://www.worldpropertiesonline.net/propimg/<?=$_REQUEST['propID'] ?>/reg/<?=$value ?>"><img src="http://www.worldpropertiesonline.net/propimg/<?=$_REQUEST['propID'] ?>/th/<?=$value ?>" /></a>
   Delete<input type="checkbox" name="imgdelete[]" value="<?=$value ?>" />
   <?
   }
   }
   }  
   
?>  
<input type="submit" />
</form>
    <?
if($i < 10){
?>
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input type="hidden" name="pic" />
<input type="hidden" name="propID" value="<?=$_REQUEST['propID'] ?>" 
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload" />
</form>

<?
} else {
echo "You can not add more files till you delete the ohter ones.";
}
?>

</body>
</html>

 

 

upload.php

 


<?php
//checks to insure that it was posted from the form
if(isset($_POST['Upload']))
{
	//make sure this directory is writable!
	$path_thumbs = $_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/th/";
	$path_reg= $_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/reg/";

	//the new width of the resized image, in pixels.
	$img_thumb_width = 125; //
	$img_reg_width = 640; 

	$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)
	//List of allowed extensions if extlimit = yes
	$limitedext = array(".jpg",".jpeg", ".bmp", ".gif", ".png");

	//the image -> variables
    $file_type = $_FILES['pic']['type'];
        $file_name = $_FILES['pic']['name'];
        $file_size = $_FILES['pic']['size'];
        $file_tmp = $_FILES['pic']['tmp_name'];

        //check if you have selected a file.
        if(!is_uploaded_file($file_tmp)){
           echo "Error: Please select a file to upload!. <br />--<a href='addpic.php?propID=".$_REQUEST['propID']."'>back</a>";
           exit(); //exit the script and don't process the rest of it!
        }
       //check the file's extension
       $ext = strrchr($file_name,'.');
       $ext = strtolower($ext);
       //uh-oh! the file extension is not allowed!
       if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {
          echo "Wrong file extension. we only allow .jpg .jpeg .gif .bmp and .png  <br />--<a href='addpic.php?propID=".$_REQUEST['propID']."'>back</a>";
          exit();
       }
       //so, whats the file's extension?
       $getExt = explode ('.', $file_name);
       $file_ext = $getExt[count($getExt)-1];

       //create a random file name
       $rand_name = md5(time());
       $rand_name= rand(0,999999999);
       //the new width variable
       $ThumbWidth = $img_thumb_width;

   //////////////////////////
   // CREATE THE THUMBNAIL //
   //////////////////////////
   
       //keep image type
       if($file_size){
          if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){
               $new_img = imagecreatefromjpeg($file_tmp);
           }elseif($file_type == "image/x-png" || $file_type == "image/png"){
               $new_img = imagecreatefrompng($file_tmp);
           }elseif($file_type == "image/gif"){
               $new_img = imagecreatefromgif($file_tmp);
           }
           //list the width and height and keep the height ratio.
           list($width, $height) = getimagesize($file_tmp);
           //calculate the image ratio
           $imgratio=$width/$height;
           if ($imgratio>1){
              $newwidth = $ThumbWidth;
              $newheight = $ThumbWidth/$imgratio;
           }else{
                 $newheight = $ThumbWidth;
                 $newwidth = $ThumbWidth*$imgratio;
           }
           //function for resize image.
           if (function_exists(imagecreatetruecolor)){
           $resized_img = imagecreatetruecolor($newwidth,$newheight);
           }else{
                 die("Error: Please make sure you have GD library ver 2+");
           }
           //the resizing is going on here!
           imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
           //finally, save the image
           ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext");
       ImageDestroy ($resized_img);
           ImageDestroy ($new_img);       
           
        }

        //ok copy the finished file to the thumbnail directory
	move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");

             

	$msg = "$title was uploaded! <a href=\"upload.php\">?</a>";



} else {


echo "There was an error with this process please return to the <a href=''>main area and try agian</a>.";
}

echo $msg
?>
<p><a href="addpic.php?propID=<?=$_REQUEST['propID'] ?>">add more photos</a></p>

 

I know it seems like I am lazy and just trying to find someone else to do my work but thats not true. I am at the point with this project to were my head is spinning. You can't think straight you are tired and making the must stupid mistakes that you would normally never make and you have pressure coming down on you from all sides. I am about to just explode and this is the last little bit left of the whole site.

 

If any one has done this before and will to sure the way they did it and why? I would really appreciate it. You don't have to write the code for me. though if I don't figure this out soon I may need that from some one. I am trying to learn it but keep getting spun around with all the tutorials from that I find in google. Some seem to contradict them selves and some don't seem that secure.

 

Please help a phper out as I would try to do the same to you.

 

Thanks,

This is my image upload script

 

The first part uploads the image and saves the names in the database

The second bit resizes the image to a thumbnail and th elast bit resizes to a larger image

 

<?php 
$idir = "../images/gallery/full/";   // Path To Images Directory 
$tdir = "../images/gallery/thumbs/";   // Path To Thumbnails Directory 
$twidth = "100";   // Maximum Width For Thumbnail Images 
$theight = "75";   // Maximum Height For Thumbnail Images 
$ldir = "../images/gallery/large/";   // Path To Thumbnails Directory 
$lwidth = "400";   // Maximum Width For Thumbnail Images 
$lheight = "300";   // Maximum Height For Thumbnail Images

$pic=($_FILES['imagefile']['name']);
$gallery = $_POST['gallery'];

if (!isset($_POST['gallery'])) {
?> 
<fieldset>
    <legend><b>Image Gallery Upload</b></legend>
<form enctype="multipart/form-data" action="<? $_SERVER['PHP_SELF']; ?>" method="post">  
    <p style="margin-left:10px;">Gallery to upload to:<br />
    <select name="gallery" size="1">
    	<option value="jack">Jack</option> 
    	<option value="honeylands">Honeylands</option> 
    	<option value="events">Events</option> 
    	<option value="art">Art Auction</option> 
    </select>
    	    <p style="margin-left:10px;">Image to upload:<br />
    	    <input type="file" name="imagefile" style="width:450px" /><br /> 
    	    <P><input type="submit" name="submit" value="Upload Image" class="submit-button" style="margin-left:10px;" /></p>
    	</form>
</fieldset><br /> 
<?}
else {   // Uploading/Resizing Script 
    $url = $_FILES['imagefile']['name'];   // Set $url To Equal The Filename For Later Use 
    if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg") { 
        $file_ext = strrchr($_FILES['imagefile']['name'], '.');   // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php 
        $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']);   // Move Image From Temporary Location To Permanent Location 
            if ($copy) {   // If The Script Was Able To Copy The Image To It's Permanent Location 
       		print 'Image uploaded successfully.<br />';   // Was Able To Successfully Upload Image 
     
    //insert the image names into the database

    include_once "../includes/connection.php";

    $query = "INSERT INTO image VALUES ('','$pic','$pic','$gallery')";
    mysql_query($query);
    mysql_close();

    $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From 
    $currwidth = imagesx($simg);   // Current Image Width 
    $currheight = imagesy($simg);   // Current Image Height 
    if ($currheight > $currwidth) {   // If Height Is Greater Than Width 
        $zoom = $twidth / $currheight;   // Length Ratio For Width 
        $newheight = $theight;   // Height Is Equal To Max Height 
        $newwidth = $currwidth * $zoom;   // Creates The New Width 
    } else {    // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) 
        $zoom = $twidth / $currwidth;   // Length Ratio For Height 
        $newwidth = $twidth;   // Width Is Equal To Max Width 
        $newheight = $currheight * $zoom;   // Creates The New Height 
    } 
    $dimg = imagecreate($newwidth, $newheight);   // Make New Image For Thumbnail 
    imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete 
    $palsize = ImageColorsTotal($simg); 
    for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image 
        $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used 
        ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use 
    } 
    imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It) 
    imagejpeg($dimg, "$tdir" . $url);   // Saving The Image 
    imagedestroy($simg);   // Destroying The Temporary Image 
    imagedestroy($dimg);   // Destroying The Other Temporary Image 
    print 'Image thumbnail created successfully.';   // Resize successful 
    } else { 
        print '<font color="#FF0000">ERROR: Unable to upload image.</font>';   // Error Message If Upload Failed 
    }

    $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From 
    $currwidth = imagesx($simg);   // Current Image Width 
    $currheight = imagesy($simg);   // Current Image Height 
    if ($currheight > $currwidth) {   // If Height Is Greater Than Width 
        $zoom = $lwidth / $currheight;   // Length Ratio For Width 
        $newheight = $lheight;   // Height Is Equal To Max Height 
        $newwidth = $currwidth * $zoom;   // Creates The New Width 
    } else {    // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) 
        $zoom = $lwidth / $currwidth;   // Length Ratio For Height 
        $newwidth = $lwidth;   // Width Is Equal To Max Width 
        $newheight = $currheight * $zoom;   // Creates The New Height 
    } 
    $dimg = imagecreate($newwidth, $newheight);   // Make New Image For The Large Image
    imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete 
    $palsize = ImageColorsTotal($simg); 
    for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image 
        $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used 
        ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use 
    } 
    imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It) 
    imagejpeg($dimg, "$ldir" . $url);   // Saving The Image 
    imagedestroy($simg);   // Destroying The Temporary Image 
    imagedestroy($dimg);   // Destroying The Other Temporary Image 
    print 'Image thumbnail created successfully.';   // Resize successful 
    } else { 
        print '<font color="#FF0000">ERROR: Unable to upload image.</font>';   // Error Message If Upload Failed 
    } 
} 
?>

ok after goin off of his script I have taken everything and have put it all into one file. Everything seems alright except when I go to upload a script nothing happends. The first pass is the same the second pass has all the options and everything goes back to the second pass. I got no errors of any type at all and I am starting to freak out again so I am going to post this code, step away, get some sleep and come back to it. Being that I get no syntax errors it has to be something with my logic. So I have a feeling this is going to be tricky.

 


<?php @session_start(); ?>
<?php
if(!isset($_SESSION['username'])){
die ("You either are not logged in or you do not have permission to view this page you must log in. If you feel this is a mistake click here to <a href='../logout.php'>log out</a> and then immediatly log back in and try agian.");
}

//get userid needed ad so on
$loginID=$_SESSION['loginID'];
$username=$_SESSION['username'];


include("../constents.php");
mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql' . mysql_error());


if(!isset($_GET['propID'])){

//search the database to see properties that need to be paid for
$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0'";
$result=mysql_query($sql);
$numberProps=mysql_num_rows($result);	

?>


<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<p>You have <?=$numberProps ?> listings in the system.</p>
<p>Please select the property you wish to view and or edit your pictures</p>
<?

while( $row = mysql_fetch_assoc($result)){ 
?>

<? 
//this is the picture echo
echo "<img src='http://www.worldpropertiesonline.net/propimg/".$row['propID']."/th/".$row['mpic']."' width='125px' height='94px' />"; 

//followed by the detailed detialed stuff 
?>

<?=$row['title'] ?> <?=$row['propID'] ?>
    <?=$row['whenlisted'] ?>
<?=$row['paidTill'] ?>

    <a href="<?=$_SERVER['PHP_SELF'] ?>?propID=<?=$row['propID'] ?>">Manage this listings pictures</a><br />


<?
}
?>
</body>
</html>
<?





//----------------------------------------------------
//end of first pass
//----------------------------------------------------




} elseif(isset($_REQUEST['propID'])){


//----------------------------------------------------
//start of second pass
//----------------------------------------------------


//function to delete a pic and its thumbnail out of the system.
function picdelete($filename, $property){

$path=$_SERVER['DOCUMENT_ROOT']."/propimg/".$property."/reg/".$filename;
$path2=$_SERVER['DOCUMENT_ROOT']."/propimg/".$property."/th/".$filename;
if (file_exists($path)){
fclose($path);
unlink($path);
}
if (file_exists($path2)){
fclose($path2);
unlink($path2);
}

}

//if this pass has images to delete run the function for the valus
if($_POST['delete']=="true"){
foreach($_REQUEST['imgdelete'] as $imgfile){
picdelete($imgfile, $_REQUEST['propID']);
}
}

$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0' and propID='".$_REQUEST['propID']."'";
$result=mysql_query($sql);
$numberProps=mysql_num_rows($result);
mysql_close();

//checks to see if the propID belongs to the user that is accessing it	
if($numberProps !== 1){

$NoNouser=1;

} else {

//the image upload and resize stuff
$idir = "../propimg/".$_REQUEST['propID']."/full/";   // Path To Images Directory 
$tdir = "../propimg/".$_REQUEST['propID']."/th/";   // Path To Thumbnails Directory 
$twidth = "125";   // Maximum Width For Thumbnail Images 
$theight = "94";   // Maximum Height For Thumbnail Images 
$ldir = "../propimg/".$_REQUEST['propID']."/reg/";   // Path To Thumbnails Directory 
$lwidth = "640";   // Maximum Width For Thumbnail Images 
$lheight = "480";   // Maximum Height For Thumbnail Images

$pic=($_FILES['imagefile']['name']);
$gallery = $_POST['gallery'];


if (isset($_POST['gallery'])) {
$error=0;
$succ=0;
  // Uploading/Resizing Script 
    $url = $_FILES['imagefile']['name'];   // Set $url To Equal The Filename For Later Use 
    if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg") { 
        $file_ext = strrchr($_FILES['imagefile']['name'], '.');   // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php 
        $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']);   // Move Image From Temporary Location To Permanent Location 
            if ($copy) {   // If The Script Was Able To Copy The Image To It's Permanent Location 
       	   $succ++;// Was Able To Successfully Upload Image 
     

    $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From 
    $currwidth = imagesx($simg);   // Current Image Width 
    $currheight = imagesy($simg);   // Current Image Height 
    if ($currheight > $currwidth) {   // If Height Is Greater Than Width 
        $zoom = $twidth / $currheight;   // Length Ratio For Width 
        $newheight = $theight;   // Height Is Equal To Max Height 
        $newwidth = $currwidth * $zoom;   // Creates The New Width 
    } else {    // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) 
        $zoom = $twidth / $currwidth;   // Length Ratio For Height 
        $newwidth = $twidth;   // Width Is Equal To Max Width 
        $newheight = $currheight * $zoom;   // Creates The New Height 
    } 
    $dimg = imagecreate($newwidth, $newheight);   // Make New Image For Thumbnail 
    imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete 
    $palsize = ImageColorsTotal($simg); 
    for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image 
        $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used 
        ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use 
    } 
    imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It) 
    imagejpeg($dimg, "$tdir" . $url);   // Saving The Image 
    imagedestroy($simg);   // Destroying The Temporary Image 
    imagedestroy($dimg);   // Destroying The Other Temporary Image 
      $succ++; // Resize successful 
    } else { 
        $error++;  // Error Message If Upload Failed 
    }

    $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From 
    $currwidth = imagesx($simg);   // Current Image Width 
    $currheight = imagesy($simg);   // Current Image Height 
    if ($currheight > $currwidth) {   // If Height Is Greater Than Width 
        $zoom = $lwidth / $currheight;   // Length Ratio For Width 
        $newheight = $lheight;   // Height Is Equal To Max Height 
        $newwidth = $currwidth * $zoom;   // Creates The New Width 
    } else {    // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) 
        $zoom = $lwidth / $currwidth;   // Length Ratio For Height 
        $newwidth = $lwidth;   // Width Is Equal To Max Width 
        $newheight = $currheight * $zoom;   // Creates The New Height 
    } 
    $dimg = imagecreate($newwidth, $newheight);   // Make New Image For The Large Image
    imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete 
    $palsize = ImageColorsTotal($simg); 
    for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image 
        $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used 
        ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use 
    } 
    imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It) 
    imagejpeg($dimg, "$ldir" . $url);   // Saving The Image 
    imagedestroy($simg);   // Destroying The Temporary Image 
    imagedestroy($dimg);   // Destroying The Other Temporary Image 
   	$succ++;   // Resize successful 
    } else { 
       $error++;  // Error Message If Upload Failed 
    } 
}









//either gets the pics or creats a directory if noone has added pics before
$file_path=$_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/th/";
$file_path2=$_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/reg/";
$picarray=array();
	if(is_dir($file_path)){
		$handle=opendir($file_path);
		$pics=1;
		$i=0;
		while(false!==($picloop=readdir($handle))){
			$picarray[$i]=$picloop;	

			$i++;

		}
	} elseif(is_dir($file_path2)) {

		mkdir($file_path, 0777);
		mkdir($file_path2, 0777);
		$pics=0;

	}

}
}



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>World Properties Online</title>

<meta name="keywords" content="glossary,property,real estate,rental,commercial,sale,by owner" />
<meta name="description" content="Welcome to World Properties Online, your guide to property for sale around the world." />
<link href="wpo.css" rel="stylesheet" type="text/css" />


</head>
<body>
<? if ($NoNouser==1){
die ("<p>Sorry but this property does not match our records. Please go back to <a href='".$_SERVER['PHP_SELF']."'>the picture management main area</a> and reslect your property. here is login id ".$loginID."</p></body></head>");
}

if($error >= 1){
echo "There was a problem uploading your script";

} elseif ($succ == 3){
echo "image upload successful.";

}

if($pics==0){
echo "You currently do not have any pictures for this listing.";

} else {


?>
    <p>You have <?=$i ?> pictures related to your listing </p>
    <p>Remember you are only allowed to have ten pictures per listing.</p>
    <form action="<?=$_SERVER['PHP_SELF'] ?>" method="post">
    <input type="hidden" name="propID" value="<?=$_REQUEST['propID']?>" />
<input type="hidden" name="delete" value="true"  />
   <? foreach($picarray as $value){
   
   if(strlen($value) >= 4){
   if(strstr($value, "." )!=1)
   ?>
   <a href="http://www.worldpropertiesonline.net/propimg/<?=$_REQUEST['propID'] ?>/reg/<?=$value ?>"><img src="http://www.worldpropertiesonline.net/propimg/<?=$_REQUEST['propID'] ?>/th/<?=$value ?>" /></a>
   Delete<input type="checkbox" name="imgdelete[]" value="<?=$value ?>" />
   <?
   }
   	?>  
<input type="submit" name="Delete Properties" />
</form>
    <?
   
   }
   }  
   

if($i < 10){

if (!isset($_POST['gallery'])) {
?> 
<fieldset>
    <legend><b>Image Upload</b></legend>
<form enctype="multipart/form-data" action="<? $_SERVER['PHP_SELF']; ?>" method="post">  
		<input type="hidden" name="propID" value="<?=$_REQUEST['propID'] ?>"  />
            <input type="hidden" name="gallery" value="set" />
    	    <input type="file" name="imagefile" /><br /> 
    	    <input type="submit" name="submit" value="Upload Image" class="submit-button"  />
    	</form>
</fieldset><br /> 
<?



} else {
echo "You can not add more files till you delete the ohter ones.";
}
}
?>

</body>
</html>

 

well good fight good night. Hope someone out there can find the error in my logic.

Just a couple of other projects you might want to try out if it doesn't work:

Thacmus - Has a Media module, which can do section [batch] resizing and thumbnailing. If you just want the resize code, go to /db/media.php and look at Media::imgResize().

BAIR - Library meant for resizing

 

To test your scripts a little more easily, you'll want to setup a small, local test server. I'd suggest using XAMPP, which comes with PHP 5.2.3 and MySQL 5.x (and you can switch to PHP 4.x if you want). That way, debugging can go a lot quicker.

I thought the code created the directories. or at least I want it to. please look at my code and tell me.

 

I have this in there which should run if no directory exist.

 

 

//either gets the pics or creats a directory if noone has added pics before
$file_path=$_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/th/";
$file_path2=$_SERVER['DOCUMENT_ROOT']."/propimg/".$_GET['propID']."/reg/";
$picarray=array();
	if(is_dir($file_path)){
		$handle=opendir($file_path);
		$pics=1;
		$i=0;
		while(false!==($picloop=readdir($handle))){
			$picarray[$i]=$picloop;	

			$i++;

		}
	} elseif(!is_dir($file_path)) {

		mkdir($file_path, 0777);
		mkdir($file_path2, 0777);
		$pics=0;

	} 

 

Basically that should create the directory. but I think that is where my problem is. Because you are right no directories were created. but I stilldoes anyone see an error there am is there a problem with my logic?

 

I try using $_SERVER['DOCUMENT_ROOT'] as well to try and give the right directory. I moved a few things around in my if statments adn no get this error.

 

Warning: mkdir(../propimg/4/th/): No such file or directory in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 222

 

Warning: mkdir(../propimg/4/reg/): No such file or directory in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 223

 

which are my make directory statements.

 

I don't understand I thought mkdir() created the directory.

 

propimg already exists. do I have to create propimg/# before the other 2

 

ok.

 

I got the mkdir scritps down to where it makes the directory but when I go to upload a file I get thie

 

Warning: copy(../propimg/4/full/Autumn Leaves.jpg): failed to open stream: No such file or directory in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 136

 

Warning: imagecreatefromjpeg(../propimg/4/full/Autumn Leaves.jpg): failed to open stream: No such file or directory in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 169

 

Warning: imagesx(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 170

 

Warning: imagesy(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 171

 

Warning: Division by zero in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 177

 

Warning: imagecreate(): Invalid image dimensions in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 181

 

Warning: imagetruecolortopalette(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 182

 

Warning: imagecolorstotal(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 183

 

Warning: imagecopyresized(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 188

 

Warning: imagejpeg(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 189

 

Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 190

 

Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/worldproperties/www/worldpropertiesonline.net/control/addpic.php on line 191

There was a problem uploading your script

 

here is all my code for the whole page. I think the problem I am having now lies in where I put some of my if statements for validating the user and so on

 


<?php @session_start(); ?>
<?php
if(!isset($_SESSION['username'])){
die ("You either are not logged in or you do not have permission to view this page you must log in. If you feel this is a mistake click here to <a href='../logout.php'>log out</a> and then immediatly log back in and try agian.");
}

//get userid needed ad so on
$loginID=$_SESSION['loginID'];
$username=$_SESSION['username'];


include("../constents.php");
mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql' . mysql_error());


if(!isset($_GET['propID'])){

//search the database to see properties that need to be paid for
$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0'";
$result=mysql_query($sql);
$numberProps=mysql_num_rows($result);	

?>


<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<p>You have <?=$numberProps ?> listings in the system.</p>
<p>Please select the property you wish to view and or edit your pictures</p>
<?

while( $row = mysql_fetch_assoc($result)){ 
?>

<? 
//this is the picture echo
echo "<img src='http://worldpropertiesonline.net/propimg/".$row['propID']."/th/".$row['mpic']."' width='125px' height='94px' />"; 

//followed by the detailed detialed stuff 
?>

<?=$row['title'] ?> <?=$row['propID'] ?>
    <?=$row['whenlisted'] ?>
<?=$row['paidTill'] ?>

    <a href="<?=$_SERVER['PHP_SELF'] ?>?propID=<?=$row['propID'] ?>">Manage this listings pictures</a><br />


<?
}
?>
</body>
</html>
<?





//----------------------------------------------------
//end of first pass
//----------------------------------------------------




} elseif(isset($_REQUEST['propID'])){


//----------------------------------------------------
//start of second pass
//----------------------------------------------------


//function to delete a pic and its thumbnail out of the system.
function picdelete($filename, $property){

$path="../propimg/".$property."/reg/".$filename;
$path2="../propimg/".$property."/th/".$filename;
if (file_exists($path)){
fclose($path);
unlink($path);
}
if (file_exists($path2)){
fclose($path2);
unlink($path2);
}

}

//if this pass has images to delete run the function for the valus
if($_POST['delete']=="true"){
foreach($_REQUEST['imgdelete'] as $imgfile){
picdelete($imgfile, $_REQUEST['propID']);
}
}

$sql="SELECT * FROM ".$dbname.".tbl_props WHERE LoginID='".$loginID."' and userdeactive='0' and propID='".$_REQUEST['propID']."'";
$result=mysql_query($sql);
$numberProps=mysql_num_rows($result);
mysql_close();

//checks to see if the propID belongs to the user that is accessing it	
if($numberProps !== 1){

$NoNouser=1;

} else {

//the image upload and resize stuff
$idir = "../propimg/".$_REQUEST['propID']."/full/";   // Path To Images Directory 
$tdir = "../propimg/".$_REQUEST['propID']."/th/";   // Path To Thumbnails Directory 
$twidth = "125";   // Maximum Width For Thumbnail Images 
$theight = "94";   // Maximum Height For Thumbnail Images 
$ldir = "../propimg/".$_REQUEST['propID']."/reg/";   // Path To Thumbnails Directory 
$lwidth = "640";   // Maximum Width For Thumbnail Images 
$lheight = "480";   // Maximum Height For Thumbnail Images

$pic=($_FILES['imagefile']['name']);
$gallery = $_POST['gallery'];


if (isset($_POST['gallery'])) {
$error=0;
$succ=0;
  // Uploading/Resizing Script 
    $url = $_FILES['imagefile']['name'];   // Set $url To Equal The Filename For Later Use 
    if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg") { 
        $file_ext = strrchr($_FILES['imagefile']['name'], '.');   // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php 
        $copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']);   // Move Image From Temporary Location To Permanent Location 
            if ($copy) {   // If The Script Was Able To Copy The Image To It's Permanent Location 
       	   $succ++;// Was Able To Successfully Upload Image 
     

    $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From 
    $currwidth = imagesx($simg);   // Current Image Width 
    $currheight = imagesy($simg);   // Current Image Height 
    if ($currheight > $currwidth) {   // If Height Is Greater Than Width 
        $zoom = $twidth / $currheight;   // Length Ratio For Width 
        $newheight = $theight;   // Height Is Equal To Max Height 
        $newwidth = $currwidth * $zoom;   // Creates The New Width 
    } else {    // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) 
        $zoom = $twidth / $currwidth;   // Length Ratio For Height 
        $newwidth = $twidth;   // Width Is Equal To Max Width 
        $newheight = $currheight * $zoom;   // Creates The New Height 
    } 
    $dimg = imagecreate($newwidth, $newheight);   // Make New Image For Thumbnail 
    imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete 
    $palsize = ImageColorsTotal($simg); 
    for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image 
        $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used 
        ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use 
    } 
    imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It) 
    imagejpeg($dimg, "$tdir" . $url);   // Saving The Image 
    imagedestroy($simg);   // Destroying The Temporary Image 
    imagedestroy($dimg);   // Destroying The Other Temporary Image 
      $succ++; // Resize successful 
    } else { 
        $error++;  // Error Message If Upload Failed 
    }

    $simg = imagecreatefromjpeg("$idir" . $url);   // Make A New Temporary Image To Create The Thumbanil From 
    $currwidth = imagesx($simg);   // Current Image Width 
    $currheight = imagesy($simg);   // Current Image Height 
    if ($currheight > $currwidth) {   // If Height Is Greater Than Width 
        $zoom = $lwidth / $currheight;   // Length Ratio For Width 
        $newheight = $lheight;   // Height Is Equal To Max Height 
        $newwidth = $currwidth * $zoom;   // Creates The New Width 
    } else {    // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height) 
        $zoom = $lwidth / $currwidth;   // Length Ratio For Height 
        $newwidth = $lwidth;   // Width Is Equal To Max Width 
        $newheight = $currheight * $zoom;   // Creates The New Height 
    } 
    $dimg = imagecreate($newwidth, $newheight);   // Make New Image For The Large Image
    imagetruecolortopalette($simg, false, 256);   // Create New Color Pallete 
    $palsize = ImageColorsTotal($simg); 
    for ($i = 0; $i < $palsize; $i++) {   // Counting Colors In The Image 
        $colors = ImageColorsForIndex($simg, $i);   // Number Of Colors Used 
        ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']);   // Tell The Server What Colors This Image Will Use 
    } 
    imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight);   // Copy Resized Image To The New Image (So We Can Save It) 
    imagejpeg($dimg, "$ldir" . $url);   // Saving The Image 
    imagedestroy($simg);   // Destroying The Temporary Image 
    imagedestroy($dimg);   // Destroying The Other Temporary Image 
   	$succ++;   // Resize successful 
    } else { 
       $error++;  // Error Message If Upload Failed 
    } 
}









//either gets the pics or creats a directory if noone has added pics before
$file_path="../propimg/".$_GET['propID']."/th/";
$file_path2="../propimg/".$_GET['propID']."/reg/";
$picarray=array();
	if(is_dir($file_path)){
		$handle=opendir($file_path);
		$pics=1;
		$i=0;
		while(false!==($picloop=readdir($handle))){
			$picarray[$i]=$picloop;	

			$i++;

		}
	} elseif(!is_dir($filepath)) {
		mkdir("../propimg/".$_GET['propID'], 0777);
		mkdir($file_path, 0777);
		mkdir($file_path2, 0777);
		$pics=0;

	}

}
}



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>World Properties Online</title>

<meta name="keywords" content="glossary,property,real estate,rental,commercial,sale,by owner" />
<meta name="description" content="Welcome to World Properties Online, your guide to property for sale around the world." />
<link href="wpo.css" rel="stylesheet" type="text/css" />


</head>
<body>
<? if ($NoNouser==1){
die ("<p>Sorry but this property does not match our records. Please go back to <a href='".$_SERVER['PHP_SELF']."'>the picture management main area</a> and reslect your property. here is login id ".$loginID."</p></body></head>");
}

if($error >= 1){
echo "There was a problem uploading your script";

} elseif ($succ == 3){
echo "image upload successful.";

}

if($pics==0){
echo "You currently do not have any pictures for this listing.";

} else {


?>
    <p>You have <?=$i ?> pictures related to your listing </p>
    <p>Remember you are only allowed to have ten pictures per listing.</p>
    <form action="<?=$_SERVER['PHP_SELF'] ?>" method="post">
    <input type="hidden" name="propID" value="<?=$_REQUEST['propID']?>" />
<input type="hidden" name="delete" value="true"  />
   <? foreach($picarray as $value){
   
   if(strlen($value) >= 4){
   if(strstr($value, "." )!=1)
   ?>
   <a href="http://www.worldpropertiesonline.net/propimg/<?=$_REQUEST['propID'] ?>/reg/<?=$value ?>"><img src="http://www.worldpropertiesonline.net/propimg/<?=$_REQUEST['propID'] ?>/th/<?=$value ?>" /></a>
   Delete<input type="checkbox" name="imgdelete[]" value="<?=$value ?>" />
   <?
   }
   	?>  
<input type="submit" name="Delete Properties" />
</form>
    <?
   
   }
   }  
   

if($i < 10){

if (!isset($_POST['gallery'])) {
?> 
<fieldset>
    <legend><b>Image Upload</b></legend>
<form enctype="multipart/form-data" action="<? $_SERVER['PHP_SELF']; ?>" method="post">  
		<input type="hidden" name="propID" value="<?=$_REQUEST['propID'] ?>"  />
            <input type="hidden" name="gallery" value="set" />
    	    <input type="file" name="imagefile" /><br /> 
    	    <input type="submit" name="submit" value="Upload Image" class="submit-button"  />
    	</form>
</fieldset><br /> 
<?



} else {
echo "You can not add more files till you delete the ohter ones.";
}
}
?>

</body>
</html>


 

 

Please look through it and help my to understand my errors and where they are comming from thi si a little confusing and now complicated for me.

 

 

I got it to work. It creates directories uploads the images and everything. With or without spaces in the file name. I do have a problem though. I don't have root access to the server and somehow even though I have everything set to 0777 chmod in my php scripts the files are still coming over to 755 for my user log in. So I can't edit, delete or change the chmod of those files and folders with my ftp program. I have read some things about shell extensions through php and things of that nature. Does anybody have a code that will go and change all folders and sub folders to a different chmod. Or what can I do from a coding perspective to unlock all of those files so I can do things with an FTP program and not get a 550 error code.

 

Is it possible my host is blocking my code from creating a full 0777, and making the files on a server level to 0755?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.