0

Alright, so I have been working on building a photographer a website. She requested that she would like a page that would allow users to log in and view their proofs and only allow THEM access to their own pictures. I have successfully created a log in page using sessions and it is working as planned. I have then created a registration form that is ONLY accessable by the photographer - she will enter users as soon as their proofs are available and it will email the user their username and password.

My problem is that I'm completely stuck on how to store the users pictures into the database and link it to their username and/or email and display them on the page automatically when they login. Here is what I have accomplished thus far:

user table:

create table users (id int NOT NULL auto_increment, firstname varchar(30) NOT NULL, lastname varchar(30) NOT NULL, email varchar(30) NOT NULL, username varchar(30) NOT NULL, password varchar(30) NOT NULL, picture varchar(50), date varchar(30) NOT NULL, PRIMARY KEY (id));

index.htm:

<html>
    <head>
       <title>Shots by Shell Login</title>
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       <link rel='stylesheet' type='text/css' href='css/style.css' />
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="validate.js"></script>


    <script type='text/javascript' src='js/example.js'></script>



    <script type="text/javascript">
     $(document).ready(function(){
       jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
       phone_number = phone_number.replace(/\s+/g, "");
       return this.optional(element) || phone_number.length > 9 &&
       phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
       }, "Please specify a valid phone number");

     $("#form").validate();
     });
    </script>

</head>
<body>
<div id="page-wrap">
        
<div class="login-block">
<h3>Shots by Shell User Login</h3>

<form action="login.php" method="POST" id="form">
                        
<table>
   <tr><td style="font-size:15; color:grey;">Username:</label></td>
   <td><input type="text" name="username" id="username" class="required"></td></tr>

   <tr><td style="font-size:15; color:grey;">Password:</label></td>
   <td><input type="password" name="password" id="password" class="required"></td></tr>

   <tr><td> <input type="submit" name="submit" id="Submit" value="Login"></td></tr>
</table> 
</form>
</div>
</div>
	
</body>
</html>

login.php

<?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];

if ($username&&$password)
{

$connect = mysql_connect("localhost","xxxx","xxxxxx") or die ("Unable to connect at this time. Please try again later.");

mysql_select_db("login2", $connect) or die ("Unable to connect to the photo database at this time. Please try again later.");


	$query = mysql_query("SELECT * FROM users WHERE username='$username'");

	$numrows = mysql_num_rows($query);


	if ($numrows!=0)
	{
		while ($row = mysql_fetch_assoc($query))
		{
			$dbusername=$row['username'];
			$dbpassword=$row['password'];
			$dbfirstname=$row['firstname'];
		}

		if ($username==$dbusername&&$password==$dbpassword)
		{
header('Location: http://mysite.example.com/member.php?id='.$_SESSION['firstname']=$dbfirstname);			

		}
		else
			echo "Incorrect password.";
	}
	else
			die("Email address does not exist.");

}
else
		die("Please enter your email address and password.");


?>

member.php

<?php

session_start();

if ($_SESSION['firstname'])
{
echo "Welcome, ".$_SESSION['firstname']."!";?><br>

<?php
echo "<a href='logout.php'>Log Out</a>";
}
else
	die("You must log in to view this page. <a href='index.php'>Click here</a> to log in.");
?>

logout.php

<?php

session_start();

session_destroy();

echo "You have successfully been logged out. <a href='index.php'>Click here</a> if you wish to log back in.";


?>

And here is the register form which creates the user

index.php

<html>
<head>
                <title>Shots by Shell Login</title>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link rel='stylesheet' type='text/css' href='css/style.css' />
                <script type="text/javascript" src="jquery.js"></script>
                <script type="text/javascript" src="validate.js"></script>


    <script type='text/javascript' src='js/example.js'></script>



                <script type="text/javascript">
                        $(document).ready(function(){
                                jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
                        phone_number = phone_number.replace(/\s+/g, "");
                                return this.optional(element) || phone_number.length > 9 &&
                                phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
                        }, "Please specify a valid phone number");

           $("#form").validate();
                        });
                </script>   

<script type="text/javascript">
   var RecaptchaOptions = {
      theme : 'clean'
   };
   </script>
</head>

<body>
      <?php
  require_once('recaptchalib.php');
  // you got this from the signup page
  $publickey = "6LfOiL0SAAAAAG5WiyZCOfp5tUUXzJ3s0yBl75QD";
  $privatekey = "6LfOiL0SAAAAAIgbTbC_K7kr89vBO7in0BYpjxQ2 ";
  $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

      require_once "formvalidator.php";
      
      $error_hash='no';

      $show_form=true;

      if(isset($_POST['Submit']))

      {

          $validator = new FormValidator();


          $validator->addValidation("Firstname","req","<B>Please enter a Firstname</B>");

          $validator->addValidation("Lastname","req","<B>Please enter a Lastname </B>");

          $validator->addValidation("Email","email","<B>The input for Email should be a valid Email address</B>");

          $validator->addValidation("Email","req","<B>Please enter an Email</B>");
          
	  $validator->addValidation("Username","req","<B>Please enter a Username</B>");

          $validator->addValidation("Password","req","<B>Please enter a Password</B>");


          if($validator->ValidateForm())

          {

              

              $show_form=false;

          }

          else

          {
		
              echo "<font color='#CC0000'><B>Validation Errors:</B></font>";

       

              $error_hash = $validator->GetErrors();

              foreach($error_hash as $inpname => $inp_err)

              {

                  echo "<p>$inpname : $inp_err</p>\n";
		$show_form=true;

              }        

          }

if($show_form===false)
              {
if (!$resp->is_valid && $show_form === false) {
              $message = '&nbsp; CAPTCHA - word verification was incorrect.<br /><br />';
              
		$show_form = true;
          	} else {
             
                      $con = mysql_connect("localhost","login","test123!")or die ("damnit");

                      mysql_select_db("login2", $con);

$email = mysql_real_escape_string($_POST['Email']);
$username = mysql_real_escape_string($_POST['Username']);

       $dupcheck = mysql_query("SELECT * FROM users WHERE (email = '$email') OR (username = '$username')",$con);

if (! mysql_num_rows ($dupcheck))
{


				//safe insert to prevent injection attacks
				$firstname = mysql_real_escape_string($_POST['Firstname']);
				$lastname = mysql_real_escape_string($_POST['Lastname']);
				$password = mysql_real_escape_string($_POST['Password']);
				//$email and $username are defined above

                            $sql="INSERT INTO users (id,firstname,lastname,email,username, password,date)
                            
                                   VALUES ('','$firstname','$lastname','$email','$username','$password',NOW())";
                          
			 mysql_query($sql,$con);
                            

				echo "<font color='#003366'><b>User Was Successfully Created!</b></font><br /><br />
					Username:<b> $username</b> <br />
					Password: <b>$password</b>";

			//need to set up mail to client here to notify them that their proofs are available.

}
		
		else
		{
		$message = 'User already exists in the database.<br /><br />';
			$show_form = true;
		}

                      mysql_close($con);

          } 

 echo "<font color='#CC0000'><B>$message</B></font>";
}
}
if (true == $show_form){                   
?>

   
	<div id="page-wrap">
        
        <div class="login-block">
            <h3>Shots by Shell User Registration</h3>
<form action="" method="POST" name="RegisterForm" id="form">
<table cellspacing='0' cellpadding='5' border='0' bordercolor='#000000' bgcolor='#ffffff'>

<tr>      
<td colspan="3" style="color:#003366; font-size:20px; font-weight:bold; padding-bottom: 10px;">User 30 Day Online Proof Registration</td>
</tr>

<tr>
<td style="font-size:15; color:grey;">Firstname:</td>
<td><input type='text' name='Firstname' size='20' class="required" value="<?php if(isset($_POST['Firstname'])){ print $_POST['Firstname']; } ?>"></td>
</tr>

<tr>
<td style="font-size:15; color:grey;">Lastname:</td>
<td><input type='text' name='Lastname' size='20' class="required" value="<?php if(isset($_POST['Lastname'])){ print $_POST['Lastname']; } ?>"></td>
</tr>

<tr>
<td style="font-size:15; color:grey;">Email:</td>
<td><input type='text' name='Email' size='20' class="required" value="<?php if(isset($_POST['Email'])){ print $_POST['Email']; } ?>"></td>
</tr>

<tr>
<td style="font-size:15; color:grey;">Username:</td>
<td><input type='text' name='Username' size='20' class="required" value="<?php if(isset($_POST['Username'])){ print $_POST['Username']; } ?>"></td>
</tr>

<tr>
<td style="font-size:15; color:grey;">Password:</td>
<td><input type='password' name='Password' size='20' class="required" value="<?php if(isset($_POST['Password'])){ print $_POST['Password']; } ?>"></td>
</tr>

<tr>
<td colspan="3">&nbsp;</td>
</tr>
</table>

<table cellspacing='0' cellpadding='10' border='0' bordercolor='#000000' bgcolor='#ffffff'>
		  
<tr>
<td><p><?php echo recaptcha_get_html($publickey);?></p></td>
</tr>

<tr>	
<td colspan="2">
<input type="submit" name="Submit" id="Submit" value="Submit">&nbsp;&nbsp;<input type="reset" value="Reset"></td>
</tr>


</table>
</form>
</table>
</div></div>
<?php
      }//true == $show_form
?>

Now that I have got all that working, I am VERY confused on how to get the pictures to link to each user.... I thought maybe since one can actually see how I started this that someone may have a better understanding of how I need this to work. I guess I just don't know exactly how to get the path of the pictures into the table, and then how to name them something that will relate to the user? I think I understand that I would have to upload the images first, then in my registration form i would have to change my insert somehow. Or do i need to make a completely separate table for the pictures ( but i will admit that i have never used more than one table before, so i'm not sure how to connect or relate between the two.

Sorry for such a long post. I hope someone can help!

3
Contributors
16
Replies
18
Views
6 Years
Discussion Span
Last Post by richieking
0

Well, from a glance I can't tell you exactly where and how to integrate into your code, but I can tell you how to accomplish many pictures for each user and displaying them.

The key here is you have a many to many data relationship(read up on some DB design), and you want to make an Images table. Sample:

CREATE TABLE Images (
id INT AUTO_INCREMENT,
path VARCHAR(100),
userid INT
)

So each row will contain the link for an image, and the id of the user. To upload an image for a specific user, the query will look something like this:

$image_path = "link/to/image.jpg";
// $userid should be the id of the user who the picture belongs to.
$query = "INSERT INTO Images (path, userid) VALUES ('$image_path', $userid)";
mysql_query($query) or die(mysql_error());

Then to get all the pictures for a specific user:

// $userid should be the id of the currently logged in user
$query = "SELECT id, path FROM images WHERE userid=$userid";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)) {
     echo "<img src='{$row['path']}' />";
}

That give you an idea?

0

Thanks for the quick reply! I am still a little confused on how to get the $userid variable. Since I am setting the $firstname from the users table as the $_SESSION variable as soon as they log into the member page how would I get their $userid from the images table?

Also, there will be multiple pictures per user. So i can't use /path/to/image.jpg since that is only one pic. How would I make it find all of their pics?

Thanks for your help!

0

The USER ID is the ID part stating from your create query up there.

To get there user id to link to the pictures tables.

Now you must modify your insert statement to accommodate the picture table. there are several ways to do this.

$foo=insert into users values ('',bal,bal,bla); the empty filed is the 
then you execute the mysql query funtion.

There is another mysql function called insert_id().
The insert id is the same as the just inserted user id or the last inserted query's id.

Now assuming you already have a table for pictures that is eg. picture(id, path,user_id)

Note that the user_id is the id for the user table. That id help referencial integrity btw the tables picture and user.

you catch the insert id like this.
$insID=mysql_insert_id();

once you have the insert_id();
You run your second insert query for the picture table.

ie. $query="insert into picture values('','$path','$insID')";

Execute the query. Now you have the exact picture matching to the user. To get the picture and the user .
query mysql as.
eg.
 $query="SELECT * FROM USER,TABEL WHERE(user.id=picture.user_id)";
assuming you have the that row   user_id to take the user ID . 

you run your while loop after your normal query.

while($row=mysql_fetch_array(result))
{
echo $row[USER_NAME];
echo "<path-to-pic/$row[PIC_PATH]/>";
BLA, BLA BLA.
}

Please contact for more info if needed.
Explore! ;)

0

There's a simpler way to do it, without worrying about insert ids or whatnot.

If you're already using the firstname to identify the user, then just use that. You'll need to change a couple DB fields:

1) Images needs a field: username VARCHAR(25)
2) Your insert query will need to look like this:

$link = "path/to/image.jpg";
$query = "INSERT INTO Images (link, username) VALUES 
('$link', '{$_SESSION['firstname']}')";
mysql_query($query) or die(mysql_error());

path/to/image.jpg is the path for one image: Let me explain.

The images table will hold many images, with one row per image. The user name(firstname) is in the images table as a key. When you say:

$query = "SELECT * FROM Images WHERE username='{$_SESSION['firstname']}' ";
$result = mysql_query($query);

It will return every row that has the same username(firstname) as the currently logged in user. Say, 20 images? It will return 20 rows. Then you simply use mysql_fetch_array() to loop through the rows.

while($image = mysql_fetch_array($result)) {
     echo "<img src='{$image['path']}' />";
}

Edited by Lsmjudoka: n/a

0

Thanks so much for you help guys, as it has been very difficult to wrap my head around this. Things all make sense except for I am STILL lost on how exactly the picture gets a unigue id.

Lsmjudoka:

{$_SESSION['firstname']}

That session only gets set when the USER logs in to view their pictures. So I guess I don't know how that would work if the PHOTOGRAPHER will be the one uploading the pictures, so that variable won't be set. The only idea i have is to have the registration form require you to upload the pictures right after you register the user, so then you could pull the $_POST through a header???

richieking:
Your post makes sense as well except for the same part..I just don't get how to make sure that the user from the users table get the EXACT id from the images table..

you said:

$foo=insert into users values ('',bal,bal,bla); the empty filed is the

I think you forgot to finish you sentence "the empty field is the...????"

Note that the user_id is the id for the user table. That id help referencial integrity btw the tables picture and user.

does "user_id" mean to look in the USER table for the field ID??? if so, i will feel very dumb because that will explain everything!

Thanks so much for you help guys, I really hope I can get this figured out!

0

Yes, dschuett. You look through the user table for the id field. Just as every table got its own unique id.

Very simple man :)

0

1.

2.
$query = "SELECT * FROM Images WHERE username='{$_SESSION}' ";
3.
$result = mysql_query($query);

$query = "SELECT * FROM Images WHERE username='{$_SESSION}' "; $result = mysql_query($query);


Lsmjudoka. Please watch out with this query. For better referencial integrity, you should not use username for query like this.

The possibility of same username is very common. There can exist more than one username and that will be a bug. Always use the uniqueness of a table and that is its ID.
If you are dealing with hundreds or thousands of usernames, You will understand why mysql always advice this mechanism.

Just a friendly advice ok?. We are all learning :)
Explore ;)

Edited by richieking: n/a

0

Yes, dschuett. You look through the user table for the id field. Just as every table got its own unique id.

Very simple man :)

richieking:
Your post makes sense as well except for the same part..I just don't get how to make sure that the user from the users table get the EXACT id from the images table..

Forgive me son. :)

The $foo=insert into users values ('',bal,bal,bla); the empty filed is the

Note: The insert statement again. $foo= insert into users values('','$path','$user_id');

There are 2 ways to get and insert the user id to reference to the picture.

1. if the user already registered and just logon to his control panel, The user can click on upload a picture and upload a picture
of his choice from his comp. if this is the case, write your script like this from the login page.

$foo= select user_id,username,fulname , pass from user where(username='$username' and password='$password');
execute mysql query.

// Now you check if the detail exists. You do this 
$results = mysql_query($foo) or die (mysql_error()); // Always do this

if(mysql_num_rows($result)){
                    while($row=mysql_fetch_array($result)){
//You put this variables in session global array for future use.
$_SESSION[user_id]=$row[user_id];
$_SESSION[username]=$row[username];
$_SESSION[fulname]=$row[fulname];

// regenerate session, register session and a php header relocation to user account. 
// now inserting the picture into the picture table is simple.
//You have the picture table picture(pic_id,path,user_id);
$user=$_SESSION[user_id];
$query="insert into picture values('','$path','$user')"; // execute query and job done. the '' is always the id of a table, its auto increment and no need to populate it.

}

}

2 if you are taking the details such as picture and registration at the same time.

// you do the first insert, that is user table.

$query="insert into user values('','$user_name','$fulname','$pass')";

//execute mysql query function.
if(mysql_query($query)){

// now, you catch the insert id to use it to rerun your second insert for the picture so that the picture table user_id field will correspond to the user id in the user table.// referencial integrity.

$insertId= mysql_insert_id(); // thats all

//second insert query.

$query= insert into picture values('','$path','$insertId'); // user id always ''. auto increment unless otherwise stated.
 //execute and job done.
}

NOTE: You can also have a single table that takes the user details and the picture at the same time. that will be very handy too.


Now to get the picture and the user out is very simple.
you select * from user,picture where (user.user_name='$username' AND user.pass='$pass' And 'user.user_id=picture.user_id');

THAT IS ALL. Do the while loop and get your username, picture etc.

I am DONE! :)

Explore ;)

0

Thanks again,

However:

if the user already registered and just logon to his control panel, The user can click on upload a picture and upload a picture
of his choice from his comp. if this is the case, write your script like this from the login page.

As I stated...the USERS are not the one's uploading their pictures. The PHOTOGRAPHER will be the one uploading pictures for USERS to see. So ONLY the PHOTOGRAPHER will have access to the register page. - She will create a user and upload her client's pictures once they are available for the USERS.

For example... the photographer just got done taking wedding pictures for a couple. Once the photographer gets home, she will create a user (with the registration page) to allow that USER access to the members page. Now the photographer needs to upload the wedding-couples' pictures to the database. Then, when the user logs in with the account i created them, they need to be able to pull ONLY their own pictures that the PHOTOGRAPHER uploaded for them.

So once again, the user's will NOT be uploading pictures...the PHOTOGRAPHER will be the one uploading pictures for the users.

I really appreciate your help! --sorry for having to deal with such a NEWBIE :)

Sorry if I have made this confusing...I am trying to be as clear as i can.

0

Ha ha that is ok but the photographer is also a user.

Please read my psedo i posted very well and you will find your way around.

Its the same logic.

I gave 2 examples. please read the script ok?

Explore :)

0

Do you feel me ???? :)

Haha, not really...because the photographer is not a user. The photographer doesn't have to log in to upload photos. - She will be doing this from a restricted site that only she has access to. And Even if the photographer was a user...you wouldn't want to use the photographers user_id...well, because that just doesn't make sense.

0

Haha, not really...because the photographer is not a user. The photographer doesn't have to log in to upload photos. - She will be doing this from a restricted site that only she has access to. And Even if the photographer was a user...you wouldn't want to use the photographers user_id...well, because that just doesn't make sense.

I will try and read through your script once more to see if I can figure anything else out... I am a little busy at work right now because we are having network problems. But should be able to read it here in a bit.

Thanks!

0

We are getting there.

1.Photographer is the Admin.
2. Admin setup account for users.
3. Admin uploads pictures of an occasion .
4. Admin give the account created to the customer(the user).

5. The user login and can see all the photos uploaded by the admin.
right?

If so. Please the script must help you. tweak it. Its the same logic.
Use your geek eyes and skills. I have already given you the idea.

Design a flow chart about your idea and send it to me.
But i will not give you full working code. since this is not only designed for you but for some other unknown geeks.

aha??? ;)

Explore:)

Edited by richieking: n/a

0

Oh come on, just give me the full code! :P Haha, just kidding...I wouldn't ask that from you. But here is the flowchart of what EXACTLY I am trying to accomplish. I have stated *NOTES where there is confusion or important information.


1. Admin takes photos for User1.
2. Admin creates account for User1. - This will automatically send an email to User1
giving them their log in info.
*Note: at this point User1 can log in to the "member.php" page, but no photos
will be returned since Admin hasn't uploaded pictures for User1 yet.
3. Admin now uploads pictures for User1.
*Note: This is where I need to somehow link the pictures that Admin is
currently uploading to a specific user (in this case, User1). Do I need to register
the user AND upload the photos at the same time? Then it would be easy to pass a
variable. I guess that is where I am a little confused. Because if you leave the
page, and upload the pictures for the user at a later time, then how do you specify
what user you are uploading pictures for? (unless you specifically specify the
user_id).
4. Pictures are now uploaded for User1, so now when User1 logs in it should display
their pictures.

Thanks again! - I am confident that i will figure this out. I might have to wait to get home to re-read your entire script that you wrote earlier. - Because I keep getting side tracked since I'm at work.

0

Ha ha you nut! :)

howdy,

dschuett, We are speaking the same language with different tenses.

As i told you, Admin will for some time be the user.

There are two things here involve.

1. admin to login automatically when the said user's account is created and start uploading the fotos.

2. admin does this from the admin CP.

if the later is true,


1. You just code a CP system that will pull registered users up which you put them in the link tag that consists of the user_id, username. (user_show.php)This mean
there must be a query to the mysql DB to look for the user. That is user firstname r username etc.

2.You write another file called upload_user_pic.php to recieve the get details from user_show.php.
The upload_user_pic.php file must have...
a. A html file upload
b. A mysql script to insert picture
c. The get variable pass the user_id and username to help mysql query so that pics doesnt get to a wrong person.
d. A session to keep the &_GET variable so that you stay in state as $_get will loose the variables originally passed.

come on say this is the kill. ;)

And that is all... :)

Explore ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.