O'Reilly Forums: 7Chapter - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

7Chapter start of chapter 7 and get function

#1 User is offline   oppaseoulstyle 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 15-March 13

Posted 15 March 2013 - 03:44 AM

I'm stuck in the chapter 7 , cannot move on.
because of the $_GET function. in my opinion, it should be used with hyperlink
or forms using 'get method'. however i can not see the hyperlink or get method form.
I guess this is use with session or cookie right??
it is written in advance for session?
or any other reason?

please help me :(
i will be waiting your helps

thank you!

This post has been edited by oppaseoulstyle: 15 March 2013 - 04:17 AM

0

#2 User is offline   drewdin 

  • Super Veteran Member
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: Members
  • Posts: 589
  • Joined: 11-February 10
  • Gender:Male
  • Location:Boston

Posted 15 March 2013 - 11:19 AM

Can you post your code, along with any errors you are getting? We cant help if we cant see what your doing. thanks
0

#3 User is offline   airbrushtutor 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 28-March 13

Posted 28 March 2013 - 01:21 AM

Hi Drewdin - i'm having the same problem as the original post(er) on this topic. Based on the description in the book i believe that the mismatch application should work after we have account logins. We are instructed to create a login script, which works perfectly fine for logging in etc, however we are unable to use other scripts such as 'viewprofile.php' or 'editprofile.php'.
It appears the reason for the discrepancies is because the viewing of the information within these scripts is subject to an 'if' statement with parameters passed via GET, however we are not passing any parameters in the URL - so there'll obviously be a problem accessing these parts of the profile.
The description and pictures in the book show a fully functioning application after the login script is first made, however this is not the case. I'm up to page 387 and it shows a fully functioning application, however when you read the conditional statements of the 'editprofile.php' & 'viewprofile.php', you can see that this isn't possible. The book also says that the index page should display a series of links to other user's profiles when logged in, however this code doesn't appear till later in the chapter.
I don't believe it's necessary to post the code at this stage as the application doesn't function as pictured even using the code downloaded from the site - however i haven't finished this chapter yet, so i'll persist and get back to you on this thread to let you know if it's actually errata or if it is in fact solved throughout the chapter, as very well may be the case.
0

#4 User is offline   drewdin 

  • Super Veteran Member
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: Members
  • Posts: 589
  • Joined: 11-February 10
  • Gender:Male
  • Location:Boston

Posted 28 March 2013 - 05:32 AM

again, can you post your code and any errors you are getting.
0

#5 User is offline   airbrushtutor 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 28-March 13

Posted 28 March 2013 - 05:54 AM

Hi Drew, Here's the code in question - like i said, it may just be that we are not far enough along in this tutorial for the scripts to function correctly as the viewprofile.php script uses information passed via the $_GET['user_id'] super global, however no URLs are sent via the index.php script.
Also the editprofile.php script requires a variable '$user_id' in the WHERE clause of a SQL query, however neither the included login.php, nor the editprofile.php scripts include this variable.
The chapter starts off by saying that the application isn't fully functioning so we'll wait and see - it's a lot of code i've just posted so i wouldn't expect anyone to go through it as i don't believe there is a problem at this stage, i think the scripts just need to be finished/ amended. Will let you know if it appears otherwise.. :)

index.php:
<!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" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Mismatch - Where opposites attract!</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
  <h3>Mismatch - Where opposites attract!</h3>

<?php
  require_once('appvars.php');
  require_once('connectvars.php');

  // Generate the navigation menu
	// If the user is logged in, generate a logout option also
	if (isset($_COOKIE['user_id'])) {
 	  echo '❤ <a href="viewprofile.php">View Profile</a><br />';
		echo '❤ <a href="editprofile.php">Edit Profile</a><br />';
		echo '❤ <a href="logout.php">Log Out (' . $_COOKIE['username'] . ')</a>';
	}
	else {
	  echo '❤ <a href="viewprofile.php">View Profile</a><br />';
  	echo '❤ <a href="editprofile.php">Edit Profile</a><br />';
	}

  // Connect to the database 
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 

  // Retrieve the user data from MySQL
  $query = "SELECT user_id, first_name, picture FROM mismatch_user WHERE first_name IS NOT NULL ORDER BY join_date DESC LIMIT 5";
  $data = mysqli_query($dbc, $query);

  // Loop through the array of user data, formatting it as HTML
  echo '<h4>Latest members:</h4>';
  echo '<table>';
  while ($row = mysqli_fetch_array($data)) {
    if (is_file(MM_UPLOADPATH . $row['picture']) && filesize(MM_UPLOADPATH . $row['picture']) > 0) {
      echo '<tr><td><img src="' . MM_UPLOADPATH . $row['picture'] . '" alt="' . $row['first_name'] . '" /></td>';
    }
    else {
      echo '<tr><td><img src="' . MM_UPLOADPATH . 'nopic.jpg' . '" alt="' . $row['first_name'] . '" /></td>';
    }
    echo '<td>' . $row['first_name'] . '</td></tr>';
  }
  echo '</table>';

  mysqli_close($dbc);
?>

</body> 
</html>


login.php:
<?php
require_once('connectvars.php');

//Clear the error message
	$error_msg = "";
	
//check to see if the server AUTH_USER and PASSWORD have been set
if (!isset($_COOKIE['user_id'])) {
	if (isset($_POST['submit'])) {
		
		//Connect to the database
		$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
		
		//Load the user input into variables
		$user_username = mysqli_real_escape_string($dbc, trim($_POST['username']));
		$user_password = mysqli_real_escape_string($dbc, trim($_POST['password']));
		
		if (!empty($user_username) && !empty($user_password)) {
			//Look up the username and password in the database
			$query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND password = SHA('$user_password')";
			$data = mysqli_query($dbc, $query);
			
			if (mysqli_num_rows($data) == 1) {
				// The log-in is successful so set the username and user_id COOKIEs and redirect to the homepage
				$row = mysqli_fetch_array($data);
				setcookie('user_id', $row['user_id']);
				setcookie('username', $row['username']);
				$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
        header('Location: ' . $home_url);
			}
			else {
				// The log-in details are incorrect so set an error message
				$error_msg = 'Sorry, you must enter a valid username and password to log-in and access this page. If you ' .
    	  'aren\'t already a registered member, please <a href="signup.php">sign up here!</a>.';
			}
		}
		else {
			//the username password weren't entered so set an error message
			$error_msg = 'Sorry, you must enter your username and password to log in.';
		}
	}
}
?>

<html>
<head>
	<title>Mismatch - Log In!</title>
  <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
  <h3>Mismatch - Log In</h3>
  <?php
	// If the cookie is empty, show any error message and the log-in form; otherwise confirm the log-in
	if (empty($_COOKIE['user_id'])) {
		echo '<p class="error">' . $error_msg . '</p>';
	?>
  <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  	<fieldset>
   		<legend>Log In</legend>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" value="<?php if(!empty($user_username)) {echo $user_username;}?>"/><br/>
        <label for"password">Password:</label>
        <input type="password" id="password" name="password" />
    </fieldset>
    <input type="submit" value="Log In" name="submit"/>
   </form>
    
   <?php
}
else {
    // Confirm the successful log-in
    echo('<p class="login">You are logged in as ' . $_COOKIE['username'] . '.</p>');
  }
	?>
 </body>
</html>


viewprofile.php:
<?php
require_once('login.php');
?>
<!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" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Mismatch - View Profile</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
  <h3>Mismatch - View Profile</h3>

<?php
  require_once('appvars.php');
  require_once('connectvars.php');

  // Connect to the database
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

  // Grab the profile data from the database
  if (!isset($_GET['user_id'])) {
    $query = "SELECT username, first_name, last_name, gender, birthdate, city, state, picture FROM mismatch_user WHERE user_id = [b]'$user_id'[/b]";
  }
  else {
    $query = "SELECT username, first_name, last_name, gender, birthdate, city, state, picture FROM mismatch_user WHERE user_id = '" . $_GET['user_id'] . "'";
  }
  $data = mysqli_query($dbc, $query);

  if (mysqli_num_rows($data) == 1) {
    // The user row was found so display the user data
    $row = mysqli_fetch_array($data);
    echo '<table>';
    if (!empty($row['username'])) {
      echo '<tr><td class="label">Username:</td><td>' . $row['username'] . '</td></tr>';
    }
    if (!empty($row['first_name'])) {
      echo '<tr><td class="label">First name:</td><td>' . $row['first_name'] . '</td></tr>';
    }
    if (!empty($row['last_name'])) {
      echo '<tr><td class="label">Last name:</td><td>' . $row['last_name'] . '</td></tr>';
    }
    if (!empty($row['gender'])) {
      echo '<tr><td class="label">Gender:</td><td>';
      if ($row['gender'] == 'M') {
        echo 'Male';
      }
      else if ($row['gender'] == 'F') {
        echo 'Female';
      }
      else {
        echo '?';
      }
      echo '</td></tr>';
    }
    if (!empty($row['birthdate'])) {
      if (!isset($_GET['user_id']) || ($user_id == $_GET['user_id'])) {
        // Show the user their own birthdate
        echo '<tr><td class="label">Birthdate:</td><td>' . $row['birthdate'] . '</td></tr>';
      }
      else {
        // Show only the birth year for everyone else
        list($year, $month, $day) = explode('-', $row['birthdate']);
        echo '<tr><td class="label">Year born:</td><td>' . $year . '</td></tr>';
      }
    }
    if (!empty($row['city']) || !empty($row['state'])) {
      echo '<tr><td class="label">Location:</td><td>' . $row['city'] . ', ' . $row['state'] . '</td></tr>';
    }
    if (!empty($row['picture'])) {
      echo '<tr><td class="label">Picture:</td><td><img src="' . MM_UPLOADPATH . $row['picture'] .
        '" alt="Profile Picture" /></td></tr>';
    }
    echo '</table>';
    if (!isset($_GET['user_id']) || ($user_id == $_GET['user_id'])) {
      echo '<p>Would you like to <a href="editprofile.php">edit your profile</a>?</p>';
    }
  } // End of check for a single row of user results
  else {
    echo '<p class="error">There was a problem accessing your profile.</p>';
  }

  mysqli_close($dbc);
?>
</body> 
</html>


editprofile.php:
<?php
require_once('login.php');
?>

<!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" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Mismatch - Edit Profile</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
  <h3>Mismatch - Edit Profile</h3>

<?php
  require_once('appvars.php');
  require_once('connectvars.php');

  // Connect to the database
  $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

  if (isset($_POST['submit'])) {
    // Grab the profile data from the POST
    $first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
    $last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
    $gender = mysqli_real_escape_string($dbc, trim($_POST['gender']));
    $birthdate = mysqli_real_escape_string($dbc, trim($_POST['birthdate']));
    $city = mysqli_real_escape_string($dbc, trim($_POST['city']));
    $state = mysqli_real_escape_string($dbc, trim($_POST['state']));
    $old_picture = mysqli_real_escape_string($dbc, trim($_POST['old_picture']));
    $new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name']));
    $new_picture_type = $_FILES['new_picture']['type'];
    $new_picture_size = $_FILES['new_picture']['size']; 
    list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']);
    $error = false;

    // Validate and move the uploaded picture file, if necessary
    if (!empty($new_picture)) {
      if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
        ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
        ($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
        if ($_FILES['file']['error'] == 0) {
          // Move the file to the target upload folder
          $target = MM_UPLOADPATH . basename($new_picture);
          if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
            // The new picture file move was successful, now make sure any old picture is deleted
            if (!empty($old_picture) && ($old_picture != $new_picture)) {
              @unlink(MM_UPLOADPATH . $old_picture);
            }
          }
          else {
            // The new picture file move failed, so delete the temporary file and set the error flag
            @unlink($_FILES['new_picture']['tmp_name']);
            $error = true;
            echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
          }
        }
      }
      else {
        // The new picture file is not valid, so delete the temporary file and set the error flag
        @unlink($_FILES['new_picture']['tmp_name']);
        $error = true;
        echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
          ' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
      }
    }

    // Update the profile data in the database
    if (!$error) {
      if (!empty($first_name) && !empty($last_name) && !empty($gender) && !empty($birthdate) && !empty($city) && !empty($state)) {
        // Only set the picture column if there is a new picture
        if (!empty($new_picture)) {
          $query = "UPDATE mismatch_user SET first_name = '$first_name', last_name = '$last_name', gender = '$gender', " .
            " birthdate = '$birthdate', city = '$city', state = '$state', picture = '$new_picture' WHERE user_id = '$user_id'";
        }
        else {
          $query = "UPDATE mismatch_user SET first_name = '$first_name', last_name = '$last_name', gender = '$gender', " .
            " birthdate = '$birthdate', city = '$city', state = '$state' WHERE user_id = '$user_id'";
        }
        mysqli_query($dbc, $query);

        // Confirm success with the user
        echo '<p>Your profile has been successfully updated. Would you like to <a href="viewprofile.php">view your profile</a>?</p>';

        mysqli_close($dbc);
        exit();
      }
      else {
        echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>';
      }
    }
  } // End of check for form submission
  else {
    // Grab the profile data from the database
    $query = "SELECT first_name, last_name, gender, birthdate, city, state, picture FROM mismatch_user WHERE user_id = '$user_id'";
    $data = mysqli_query($dbc, $query);
    $row = mysqli_fetch_array($data);

    if ($row != NULL) {
      $first_name = $row['first_name'];
      $last_name = $row['last_name'];
      $gender = $row['gender'];
      $birthdate = $row['birthdate'];
      $city = $row['city'];
      $state = $row['state'];
      $old_picture = $row['picture'];
    }
    else {
      echo '<p class="error">There was a problem accessing your profile.</p>';
    }
  }

  mysqli_close($dbc);
?>

  <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" />
    <fieldset>
      <legend>Personal Information</legend>
      <label for="firstname">First name:</label>
      <input type="text" id="firstname" name="firstname" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br />
      <label for="lastname">Last name:</label>
      <input type="text" id="lastname" name="lastname" value="<?php if (!empty($last_name)) echo $last_name; ?>" /><br />
      <label for="gender">Gender:</label>
      <select id="gender" name="gender">
        <option value="M" <?php if (!empty($gender) && $gender == 'M') echo 'selected = "selected"'; ?>>Male</option>
        <option value="F" <?php if (!empty($gender) && $gender == 'F') echo 'selected = "selected"'; ?>>Female</option>
      </select><br />
      <label for="birthdate">Birthdate:</label>
      <input type="text" id="birthdate" name="birthdate" value="<?php if (!empty($birthdate)) echo $birthdate; else echo 'YYYY-MM-DD'; ?>" /><br />
      <label for="city">City:</label>
      <input type="text" id="city" name="city" value="<?php if (!empty($city)) echo $city; ?>" /><br />
      <label for="state">State:</label>
      <input type="text" id="state" name="state" value="<?php if (!empty($state)) echo $state; ?>" /><br />
      <input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
      <label for="new_picture">Picture:</label>
      <input type="file" id="new_picture" name="new_picture" />
      <?php if (!empty($old_picture)) {
        echo '<img class="profile" src="' . MM_UPLOADPATH . $old_picture . '" alt="Profile Picture" />';
      } ?>
    </fieldset>
    <input type="submit" value="Save Profile" name="submit" />
  </form>
</body> 
</html>

This post has been edited by airbrushtutor: 28 March 2013 - 05:55 AM

0

#6 User is offline   drewdin 

  • Super Veteran Member
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: Members
  • Posts: 589
  • Joined: 11-February 10
  • Gender:Male
  • Location:Boston

Posted 29 March 2013 - 05:00 AM

How far are you in the book, what type of authentication are you using?

Are you using sessions yet?
0

#7 User is offline   airbrushtutor 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 28-March 13

Posted 29 March 2013 - 05:31 AM

Hi Drew, i'm currently on page 395 - Have just started reading the section on sessions and am checking what needs to be done in order to update from cookies to SESSIONs. I'm not sure what you mean by the type of authentication.. I'm not getting any errors at all, the coding seems fine, just the scripts are failing the if clauses and going straight to the 'else' statements which say 'there is an error viewing your profile etc' - but i think this is how it should be functioning at this stage? Will keep plowing through:)
0

#8 User is offline   drewdin 

  • Super Veteran Member
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: Members
  • Posts: 589
  • Joined: 11-February 10
  • Gender:Male
  • Location:Boston

Posted 29 March 2013 - 01:01 PM

Just skip to sessions, the first authentication type is no longer valid and never used. Skip by this section and go right to sessions, that's what you want.

I didnt see anywhere in the code where the cookies get set, so they are failing and kicking you out.
0

#9 User is offline   airbrushtutor 

  • New Member
  • Pip
  • Group: Members
  • Posts: 8
  • Joined: 28-March 13

Posted 30 March 2013 - 04:04 AM

Once all the SESSIONs are put in the script functions fine - this chapter just isn't as detailed as previous ones, it seems as though some of the edits to the scripts were left out - i don't think i could have authored/ edited this chapter any better though + it means you have to look around a lot more and get your head around the scripts which forces you to learn. Cheers for the help Drew, if anything else comes up i know where to ask.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users