Newb advice

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Mate that's really good of you - thanks.

It will take me a couple of days to go through and get my head around the whole
thing so I'll be back by the weekend !

Best wishes
Monty
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Got this going quicker than I thought - spotted a slight conflict though.
I'm using

Code: Select all

 
session_start(); 
if (@!$_SESSION['id']) {
 
and the user is identified on a site wide basis by 'id' which is the primary key for the members table.
So with the session start at the top of the script this will (I think) conflict with this

Code: Select all

 
mysql_query("INSERT INTO `Pictures`
    (`ID`, `username`, `Filename`, `Gallery`, `Picture`)
    VALUES
    {$pictures};") or trigger_error(mysql_error(), E_USER_ERROR);
 
in your script as it would have to read 'ID', 'id' which is bound to screw things up.
Can I change 'ID' to anything I like (in the script and in the table) or is it a kind of reserved code for mysql ?
Or do I just delete 'username" ?

Best wishes
Monty
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Newb advice

Post by jackpf »

if (@!$_SESSION['id'])
I thought we talked about that :evil: lol

And no, that should still work fine. If you insert the user id into the username field (you may want to rename it for consistency :)...maybe to `User_ID`, or `TheNameOfYourUsersTable_id` or whatever), you can then just join on the users table to see who owns the picture.

It shouldn't make any difference.
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Trouble...

this thing has a flash front end and from what I can discover that is going to be a
huge headache with an images db.

And I've now managed to break half the cool things that were working :?

So... I'm back to a simple uploader that puts the images into the user's images folder then
writes some .txt files for Flash to read.
Need to fix the bits I broke first though !

Best wishes
Monty
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Back to basics....

Only three small things to fix and this is rock n rolling !

1) the images upload to the right place and rename incrementally - but with no extension.
So instead of 22.jpg I get 22. and no "jpg"

2) A couple of error messages that I can't solve:
Notice: Undefined index: image in /Sites/com/shutterbugclub/www/upload.php on line 36
Notice: Undefined variable: filename in /Sites/com/shutterbugclub/www/upload.php on line 67

The script I'm using is a bit of a mish-mash of stuff I've learned in this thread and some from a tutorial
I've been following so I know I need to go through and do the "isset" bits but for now this is how she looks:

Code: Select all

 
session_start(); 
if (@!$_SESSION['id']) { 
$msgToUser = '<br /><br /><font color="#FF0000">Only site members can do that</font><p><a href="register.php">Join Here</a></p>';
 
include_once 'msgToUser.php'; 
  exit(); 
} 
////////////////////////////////////////////////      End member Log in check       ///////////////////////////////////////////////////
// Connect to database, needed every time the page runs or is refreshed in a browser
include_once "scripts/connect_to_mysql.php";
 
// Get the user session id variable into a local php variable for easier use in scripting
$id = $_SESSION['id'];
 
// Now let's initialize vars to be printed to page in the HTML section so our script does not return errors 
// they must be initialized in some server environments, not shown in video
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$error_msg = "";
$success_msg = "";
$firstname = "";
$lastname = "";
$user_pic = "";
 
 
 
// Parsing section for the member picture... only runs if they attempt to upload or replace a picture
 
if (@$_POST['parse_var'] == "pic"){
$image=$_FILES['image']['name'];
if ($image)
{
$filename = stripslashes($_FILES['image']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{exit("Upload failed.<BR>Unacceptable file type.<br. Use only jpg, jpeg, png or fig formats");
echo '<h1>Only try to upload .jpg, .jpeg, .png and .gif files!</h1>';
$errors=1;
}}
 
        if (@!$_FILES['fileField']['tmp_name']) {
        
            $error_msg = '<font color="#FF0000">ERROR: Please browse for an image before you press submit.</font>';
            
        } else {
 
            $maxfilesize = 51200; // 51200 bytes equals 50kb
            if($_FILES['fileField']['size'] > $maxfilesize ) { 
 
                        $error_msg = '<font color="#FF0000">ERROR: Ooops - your image was too large, please try again.</font>';
                        unlink($_FILES['fileField']['tmp_name']); 
 
            } else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['fileField']['name'] ) ) {
 
                        $error_msg = '<font color="#FF0000">ERROR: Ooops - Your image was not one of our accepted formats, please try again.</font>';
                        unlink($_FILES['fileField']['tmp_name']); 
 
            } else { 
                    // rename the picture incfrementally
                    $extension = getExtension($filename);
                    $extension = strtolower($extension);
                    $groovy = sizeof(glob("members/$id/images/*"));
                    $groovy = ++$groovy;
                
                    $image_name=$groovy.'.'.$extension;
                    $newname="".$image_name;
 
                        //$newname = "giraffe.jpg";
                        $place_file = move_uploaded_file( $_FILES['fileField']['tmp_name'], "members/$id/images/".$newname);
                        chmod ("members/$id/images/$newname", 0644);
                        $success_msg = '<span class="Big_Orange_Times">Your image has been uploaded, it may take a few moments to appear in your gallery, please be patient.</span>';
            }
 
        } // close else that checks file exists
 
}
 
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Scratched my head and got it solved !

If you have a minute log in, upload a new avatar, upload a few pictures
(the drop down doesn't do a thing yet so ignore it) then click on your profile
and view your gallery - should all be working and I'd love to hear that it is !


Best wishes
Monty
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Newb advice

Post by jackpf »

It all seems to be working :)

You should download your site to your localhost...don't edit it live.

And why are you still using error suppression?!
this thing has a flash front end and from what I can discover that is going to be a
huge headache with an images db.
It makes no difference tbh. You just need a single script that will pull the images from the database and display them...like the one I included in the zip :) But yeah...if you're storing them as files now, it doesn't really matter.

I just find it a lot easier storing files in the database...that way, when I download all my scripts so I can edit them/back them up, I don't need to download a huge amount of other peoples' files as well...

As I said, I also think they're a lot easier to manage in a database. For example...say you wanted to allow users to delete multiple pictures at once.

But it's up to you :)
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

I know - you're right - and as soon as this is up and running I'm going to build a mini
version just to learn the whole management of images via a database but for now my clumsy
version is working and time is against me. So far so good just don't say "short cuts make long delays" !
:D

Best wishes
Monty
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Last few steps (hopefully)...

I found a resize script that seems to do the job - only it gives an error I cannot solve no matter how I write the string it needs. The bit that's causing the issue is listed first, the whole upload script second and the class I'm calling third (sorry for the acres of code but I thought it might help) :?

The issue (I think) is with the line: (in the first block)
$image->image_to_resize = "members/".$id."/images/".$newname;
which asks for a full path (which I can't give it because it could be anywhere) so I'm
giving it all the variables it needs to create the path. Only it doesn't...
The error I get is: (pasted - it really does say .jpg.jpg)
Warning: imagejpeg() [function.imagejpeg]: Unable to open 'members/$id/images/14.jpg.jpg' for writing in /Sites/com/shutterbugclub/www/scripts/resize.class.php on line 140

All and any help much appreciated because once the resizing is done (I broke the mechanism that was working
to do this - God knows how but I did) then the whole thing can be wrapped up and made to look pretty.

Best wishes
Monty

CODE: The resize bit at the end of the upload script:

Code: Select all

 
$image = new Resize_Image;
 
                        $image->new_width = 900;
                        $image->new_height = 530;
 
                        $image->image_to_resize = "members/".$id."/images/".$newname; // Full Path to the file
 
                        $image->ratio = true; // Keep Aspect Ratio?
 
// Name of the new image (optional) - If it's not set a new will be added automatically
 
                        $image->new_image_name = $newname;
 
/* Path where the new image should be saved. If it's not set the script will output the image without saving it */
 
                        $image->save_folder = 'members/$id/images/';
 
                        $process = $image->resize();
 
                        if($process['result'] && $image->save_folder)
                    {
                        echo 'The new image ('.$process['new_file_path'].') has been saved.';
                    }
                        $success_msg = '<span class="Big_Orange_Times">Your image has been uploaded, it may take a few moments to appear in your gallery, please be patient.</span>';
 

CODE: The whole upload script

Code: Select all

 
<?php 
 
session_start();
if (@!$_SESSION['id']) {
$msgToUser = '<br /><br /><font color="#FF0000">Only site members can do that</font><p><a href="register.php">Join Here</a></p>';
include_once 'msgToUser.php';
  exit();
}
////////////////////////////////////////////////      End member Log in check       ///////////////////////////////////////////////////
// Connect to database, needed every time the page runs or is refreshed in a browser
include_once "scripts/connect_to_mysql.php";
include 'scripts/resize.class.php';
 
define ("MAX_SIZE","100");
 
// Get the user session id variable into a local php variable for easier use in scripting
$id = $_SESSION['id'];
 
// Now let's initialize vars to be printed to page in the HTML section so our script does not return errors
// they must be initialized in some server environments, not shown in video
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$error_msg = "";
$success_msg = "";
$firstname = "";
$lastname = "";
$user_pic = "";
 
 
 
// Parsing section for the member picture... only runs if they attempt to upload or replace a picture
 
if (@$_POST['parse_var'] == "pic"){
$image=$_FILES['fileField']['name'];
if ($image)
{
$filename = stripslashes($_FILES['fileField']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{exit("Upload failed.<BR>Unacceptable file type.<br. Use only jpg, jpeg, png or fig formats");
echo '<h1>Only try to upload .jpg, .jpeg, .png and .gif files!</h1>';
$errors=1;
}}
 
        if (@!$_FILES['fileField']['tmp_name']) {
       
            $error_msg = 'Please browse for an image before you press Go.';
           
        } else {
 
            $maxfilesize = 256000; // 256000 bytes equals 250kb
            if($_FILES['fileField']['size'] > $maxfilesize ) {
                        $error_msg = 'Ooops - your image was too large,<br> 250kb Maximum. Please try again.';
                        unlink($_FILES['fileField']['tmp_name']);
 
            } else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['fileField']['name'] ) ) {
 
                        $error_msg = 'Ooops - Your image was not one of our accepted formats, please try again.';
                        unlink($_FILES['fileField']['tmp_name']);
 
            } else {
                    // rename the picture incfrementally
                    $extension = getExtension($filename);
                    $extension = strtolower($extension);
                    $groovy = sizeof(glob("members/$id/images/*"));
                    $groovy = ++$groovy;
               
                    $image_name=$groovy.'.'.$extension;
                    $newname="".$image_name;
 
                        
                        $place_file = move_uploaded_file( $_FILES['fileField']['tmp_name'], "members/$id/images/".$newname);
                        chmod ("members/$id/images/$newname", 0666);
                        print $newname;
                        $image = new Resize_Image;
 
                        $image->new_width = 900;
                        $image->new_height = 530;
 
                        $image->image_to_resize = "members/".$id."/images/".$newname; // Full Path to the file
 
                        $image->ratio = true; // Keep Aspect Ratio?
 
// Name of the new image (optional) - If it's not set a new will be added automatically
 
                        $image->new_image_name = $newname;
 
/* Path where the new image should be saved. If it's not set the script will output the image without saving it */
 
                        $image->save_folder = 'members/$id/images/';
 
                        $process = $image->resize();
 
                        if($process['result'] && $image->save_folder)
                    {
                        echo 'The new image ('.$process['new_file_path'].') has been saved.';
                    }
                        $success_msg = '<span class="Big_Orange_Times">Your image has been uploaded, it may take a few moments to appear in your gallery, please be patient.</span>';
                        //NOW MAKE THE RESIZE CALL
                        //img_resize ($_FILES [ 'fileField'] [ 'name'], $_FILES [ 'fileField'] [ 'tmp_name'], 537, $newname);
                        
 
                        
            }
 

Some MORE Code The resize class I'm calling as an include:

Code: Select all

 
<?php
/*
---------------------------------------------------------------------
Credits: Bit Repository
 
Source URL: http://www.bitrepository.com/resize-an- ... nd-gd.html
---------------------------------------------------------------------
*/
class Resize_Image {
 
var $image_to_resize;
var $new_width;
var $new_height;
var $ratio;
var $new_image_name;
var $save_folder;
 
function resize()
{
if(!file_exists($this->image_to_resize))
{
  exit("File ".$this->image_to_resize." does not exist.");
}
 
$info = GetImageSize($this->image_to_resize);
 
if(empty($info))
{
  exit("The file ".$this->image_to_resize." doesn't seem to be an image.");
}
 
$width = $info[0];
$height = $info[1];
$mime = $info['mime'];
 
/*
Keep Aspect Ratio?
 
Improved, thanks to Larry
*/
 
if($this->ratio)
{
// if preserving the ratio, only new width or new height
// is used in the computation. if both
// are set, use width
 
if (isset($this->new_width))
{
$factor = (float)$this->new_width / (float)$width;
$this->new_height = $factor * $height;
}
else if (isset($this->new_height))
{
$factor = (float)$this->new_height / (float)$height;
$this->new_width = $factor * $width;
}
else
exit("neither new height or new width has been set");
}
 
// What sort of image?
 
$type = substr(strrchr($mime, '/'), 1);
 
switch ($type)
{
case 'jpeg':
    $image_create_func = 'ImageCreateFromJPEG';
    $image_save_func = 'ImageJPEG';
    $new_image_ext = 'jpg';
    break;
 
case 'png':
    $image_create_func = 'ImageCreateFromPNG';
    $image_save_func = 'ImagePNG';
    $new_image_ext = 'png';
    break;
 
case 'bmp':
    $image_create_func = 'ImageCreateFromBMP';
    $image_save_func = 'ImageBMP';
    $new_image_ext = 'bmp';
    break;
 
case 'gif':
    $image_create_func = 'ImageCreateFromGIF';
    $image_save_func = 'ImageGIF';
    $new_image_ext = 'gif';
    break;
 
case 'vnd.wap.wbmp':
    $image_create_func = 'ImageCreateFromWBMP';
    $image_save_func = 'ImageWBMP';
    $new_image_ext = 'bmp';
    break;
 
case 'xbm':
    $image_create_func = 'ImageCreateFromXBM';
    $image_save_func = 'ImageXBM';
    $new_image_ext = 'xbm';
    break;
 
default:
    $image_create_func = 'ImageCreateFromJPEG';
    $image_save_func = 'ImageJPEG';
    $new_image_ext = 'jpg';
}
 
    // New Image
    $image_c = ImageCreateTrueColor($this->new_width, $this->new_height);
 
    $new_image = $image_create_func($this->image_to_resize);
 
    ImageCopyResampled($image_c, $new_image, 0, 0, 0, 0, $this->new_width, $this->new_height, $width, $height);
 
        if($this->save_folder)
        {
           if($this->new_image_name)
           {
           $new_name = $this->new_image_name.'.'.$new_image_ext;
           }
           else
           {
           $new_name = $this->new_thumb_name( basename($this->image_to_resize) ).'_resized.'.$new_image_ext;
           }
 
        $save_path = $this->save_folder.$new_name;
        }
        else
        {
        /* Show the image without saving it to a folder */
           header("Content-Type: ".$mime);
 
           $image_save_func($image_c);
 
           $save_path = '';
        }
 
        $process = $image_save_func($image_c, $save_path);
 
        return array('result' => $process, 'new_file_path' => $save_path);
 
    }
 
    function new_thumb_name($filename)
    {
    $string = trim($filename);
    $string = strtolower($string);
    $string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
    $string = ereg_replace("[ tnr]+", "_", $string);
    $string = str_replace(" ", '_', $string);
    $string = ereg_replace("[ _]+", "_", $string);
 
    return $string;
    }
}
?>
 
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Newb advice

Post by jackpf »

Try using an absolute path, with $_SERVER['DOCUMENT_ROOT']...
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

So check out the new gallery !

http://www.shutterbugclub.com/gallery.php

Best wishes
Monty
User avatar
Weiry
Forum Contributor
Posts: 323
Joined: Wed Sep 09, 2009 5:55 am
Location: Australia

Re: Newb advice

Post by Weiry »

Im not sure if it is meant to happen or not... but when i click an image in that gallery, nothing happens... but when i click the "Landscape" or "Portrait" buttons etc, it takes me to the respective gallery.

I went to test to make sure it wasn't Google Chrome's fault that i couldn't click pictures, so i opened up with IE8.
IE8 has more problems... :(
No menu up the top, and i can see your debugging stuff on the right had side of your flash outside the window..
Attached Screenshot of the site in IE8

Can somone else please confirm that its only me.. id hate to see something like this die in MICROSOFTS EVIL WEB BROWSER 8) :lol:

PS: sorry about the size of the screenshots
Attachments
gallery-IE8-2.jpg
gallery-IE8-2.jpg (189.51 KiB) Viewed 904 times
gallery-IE8.jpg
gallery-IE8.jpg (241.54 KiB) Viewed 904 times
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Newb advice

Post by jackpf »

Confirmed :P
MiniMonty
Forum Contributor
Posts: 196
Joined: Thu Sep 03, 2009 9:09 am
Location: UK

Re: Newb advice

Post by MiniMonty »

Thanks for that feedback - it's really helpful to see the bug in IE.
Will have to look into that...

In the meantime, a fews days of drawing pictures and making things look pretty have
cleared my head and I am left with only two smallish issues.

First one today !

I'm using this at the end of my upload script:

Code: Select all

 
 $place_file = move_uploaded_file( $_FILES['fileField']['tmp_name'], "members/$id/images/".$newname);
                        chmod ("members/$id/images/$newname", 0666);
                        //print $newname;
                        //NOW WRITE THE  .txt FILE IN THE APPROPRIATE GALLERY FOLDER
                        $myFile = "images/gallery/".$_POST ['gowhere']. "/gallarray.txt";
                        $fh = fopen($myFile, 'a+') or die("can't open file");
                        $stringData = "members/".$id."/images/".$newname .",";
                        fwrite($fh, $stringData);
                        fclose($fh);
                        //COUNT THE ITEMS IN THE ARRAY (string)
                        $textfile = file_get_contents("images/gallery/".$_POST ['gowhere']. "/gallarray.txt");
                        $filepaths= explode(",",$textfile);
                        $fh =fopen($myFile, 'a+') or die("can't open the file");
                        $stringdata2 = "&totalimgs=" .count($filepaths);
                        fwrite($fh, $stringdata2);
                        fclose($fh);
 
As you can see it writes the path to the recently uploaded image to a txt file in the gallery defined by [gowhere].
It counts the items in the string in the txt file so flash can loop the gallery. This works - except... before the new
file path is written I need to strip out the final line of the string "&totalimgs=10", (number will be random) then
append the new file path, then the new value of "&totalimgs="

I've tried this (to no avail).

Code: Select all

 
$myFile = str_replace("&totalimgs=","",$myFile);
 
Any ideas ?

Best wishes
Monty
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Newb advice

Post by jackpf »

I don't follow...

I don't see where $myFile would even contain &totalimgs=....


Sorry :/
Post Reply