Page 1 of 1

Blog/comments integration with login

Posted: Sat Apr 13, 2013 10:49 pm
by Z645
Hi, I just finished the blog and comments tutorial and was wondering if there was a way to integrate the blog thing with the login. So everytime someone wants to post a status or a post, they don't need to post their name (or username). It'll automatically enter it into the database.

My code of what I have so far:
home.php
<?php

include('core/init.inc.php');

if (isset($_POST['user'], $_POST['body'])){
	add_post($_POST['user'], $_POST['body']);
	header('Location: home.php');
	die();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Welcome to ViBeate</title>
		<meta name="description" content="Welcome to ViBeate. ViBeate allows you to connect with friends, family, and co-workers." />
		<meta name="keywords" content="social, networking, games, chat, hangout, friends" />
		<meta name="robots" content="index, follow" />

		<link rel="stylesheet" href="styles/style.css" type="text/css">
        <script type="text/javascript">
          WebFontConfig = {
            google: { families: [ 'Chewy::latin' ] }
          };
          (function() {
            var wf = document.createElement('script');
            wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
              '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
            wf.type = 'text/javascript';
            wf.async = 'true';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(wf, s);
          })(); </script>
    </head>
	
    <body>
        <div id="wrapper">
            <?php include('extras/menu.php'); ?>
            <br />
            <br />
            <div id="main">
                <div id="left_side">
					<form action="" method="post">
						<p>
							<label for="user">Name</label>
							<input type="text" name="user" id="user" />
						</p>
						<p>
							<textarea name="body" rows="5" cols="60" placeholder="Post a status here..."></textarea>
						</p>
						<p>
							<input type="submit" value="Post" />
						</p>
					</form>
                    <?php
						$posts = get_posts();
						
						foreach ($posts as $post){
							?>
							<h3><?php echo $post['user']; ?></h3> Posted on <?php echo $post['date']; ?>
							<hr />
							<p><?php echo $post['preview']; ?></p>
							<i><a href="read_post.php?pid=<?php echo $post['id']; ?>">(<?php echo $post['total_comments']; ?> comments) <?php echo $post['last_comment']; ?></a></i>
							<?php
						}
						
					?>
                </div>
                
                <div id="right_side">
                    <div class="ads">
                        /*Advertisments go here*/
                        Advertisment
                    </div>
					<br />
                    <div class="footer">
                        <center><?php include('extras/footer.php'); ?></center>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

read_posts.php
<?php

include('core/init.inc.php');

if (isset($_GET['pid'], $_POST['user'], $_POST['body'])){
	if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])){
		header("Location: read_post.php?pid={$_GET['pid']}");
	}else{
		header("Location: home.php");
	}
	
	die();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Welcome to ViBeate</title>
		<meta name="description" content="Welcome to ViBeate. ViBeate allows you to connect with friends, family, and co-workers." />
		<meta name="keywords" content="social, networking, games, chat, hangout, friends" />
		<meta name="robots" content="index, follow" />

		<link rel="stylesheet" href="styles/style.css" type="text/css">
        <script type="text/javascript">
          WebFontConfig = {
            google: { families: [ 'Chewy::latin' ] }
          };
          (function() {
            var wf = document.createElement('script');
            wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
              '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
            wf.type = 'text/javascript';
            wf.async = 'true';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(wf, s);
          })(); </script>
    </head>
	
    <body>
        <div id="wrapper">
            <?php include('extras/menu.php'); ?>
            <br />
            <br />
            <div id="main">
                <div id="left_side">
                    <?php
						if (isset($_GET['pid']) === false || valid_pid($_GET['pid']) === false){
							echo 'Invalid post ID!';
						}else{
						$post = get_post($_GET['pid']);
					?>
					
					<h3><?php echo $post['user']; ?></h3> Posted on <?php echo $post['date']; ?>
					<hr />
					<p><?php echo $post['body']; ?></p>
					<i>(<?php echo count($post['comments']); ?> comments)</i>
					<hr />
					
					<?php
					
					foreach ($post['comments'] as $comment){
						?>
						<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
						<p><?php echo $comment['body']; ?></p>
						<hr />
						<?php
					}
					
					?>
					<form action="" method="post">
						<p>
							<label for="user">Name</label>
							<input type="text" name="user" id="user">
						</p>
						<p>
							<textarea name="body" rows="5" cols="60" placeholder="Type in your comment"></textarea>
						</p>
						<p>
							<input type="submit" value="Add comment">
						</p>
					</form>
					<?php
					
					}
					?>
                </div>
                
                <div id="right_side">
                    <div class="ads">
                        /*Advertisments go here*/
                        Advertisment
                    </div>
					<br />
                    <div class="footer">
                        <center><?php include('extras/footer.php'); ?></center>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
posts.inc.php
<?php

//checks if the given post id is in the table
function valid_pid($pid){
	$pid = (int)$pid;
	
	$total = mysql_query("SELECT COUNT(`post_id`) FROM `posts` WHERE `post_id` = '{$pid}'");
	$total = mysql_result($total, 0);
	
	echo mysql_error();
	
	if ($total != 1){
		return false;
	}else{
		return true;
	}
}

//fetches a summary of all the posts
function get_posts(){
	$sql = "SELECT
				`posts`.`post_id` AS `id`,
				`posts`.`post_body` AS `preview`,
				`posts`.`post_user` AS `user`,
				DATE_FORMAT(`posts`.`post_date`, '%d/%m/%Y %H:%i') AS `date`,
				`comments`.`total_comments`,
				DATE_FORMAT(`comments`.`last_comment`, '%d/%m/%Y %H:%i:%s') AS `last_comment`
			FROM `posts`
			LEFT JOIN(
				SELECT 
					`post_id`,
					COUNT(`comment_id`) AS `total_comments`,
					MAX(`comment_date`) AS `last_comment`
				FROM `comments`
				GROUP BY `post_id`
			) AS `comments`
			ON `posts`.`post_id` = `comments`.`post_id`
			ORDER BY `posts`.`post_date` DESC";
	
	$posts = mysql_query($sql);
	
	$rows = array();
	while (($row = mysql_fetch_assoc($posts)) !== false){
		$rows[] = array(
			'id'				=> $row['id'],
			'preview'			=> $row['preview'],
			'user'				=> $row['user'],
			'date'				=> $row['date'],
			'total_comments'	=> ($row['total_comments'] === null) ? 0 : $row['total_comments'],
			'last_comment'		=> ($row['last_comment'] === null) ? 'No recent comments. Be the first to comment!' : $row['last_comment']
		);
	}
	
	return $rows;
}

//fetches a single post from the table
function get_post($pid){
	$pid = (int)$pid;
	
	$sql = "SELECT
				`post_body` AS `body`,
				`post_user` AS `user`,
				`post_date` AS `date`
			FROM `posts`
			WHERE `post_id` = {$pid}";
			
	$post = mysql_query($sql);
	$post = mysql_fetch_assoc($post);
	
	$post['comments'] = get_comments($pid);
	
	return $post;
}

// adds a new post entry
function add_post($name, $body){
	$name = mysql_real_escape_string(htmlentities($name));
	$body = mysql_real_escape_string(nl2br(htmlentities($body)));
	
	mysql_query("INSERT INTO `posts` (`post_user`, `post_body`, `post_date`) VALUES ('{$name}', '{$body}', NOW())");
}
?>
comments.inc.php
<?php

//fetches all of the comments for a given post
function get_comments($pid){
	$pid = (int)$pid;
	
	$sql = "SELECT 
				`comment_body` AS `body`,
				`comment_user` AS `user`,
				DATE_FORMAT(`comment_date`, '%d/%m/%Y %H:%i:%s') AS `date`
				FROM `comments`
				WHERE `post_id` = {$pid}";
				
	$comments = mysql_query($sql);
	
	$return = array();
	while (($row = mysql_fetch_assoc($comments)) !== false){
		$return[] = $row;
	}
	
	return $return;
}

//adds a comment
function add_comment($pid, $user, $body){
	if (valid_pid($pid) === false){
		return false;
	}
	
	$pid 	= (int)$pid;
	$user 	= mysql_real_escape_string(htmlentities($user));
	$body 	= mysql_real_escape_string(nl2br(htmlentities($body)));
	
	mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
	
	return true;
}
?>

Re: Blog/comments integration with login

Posted: Mon Apr 15, 2013 11:01 pm
by ExtremeGaming
Just use the $_SESSION username when inserting into the database.

Re: Blog/comments integration with login

Posted: Tue Apr 16, 2013 2:14 am
by Z645
Explanation please? I tried replacing everything I could think of o-o

Re: Blog/comments integration with login

Posted: Tue Apr 16, 2013 7:20 am
by Helx
Z645 wrote:Explanation please? I tried replacing everything I could think of o-o
Line 25 of comments.inc.php;
When you call the function "add_comment" (when they submit their comment), instead of using a $_POST variable (or whatever) use a $_SESSION variable.

You can't just make one up like a normal $variable, it has to be set. This should be earlier in the code you have created in a login function (I can't seem to find it with what you've given us).

Normally it's called "user" or "username". It's much like a $_POST variable, it's set out like so: $_SESSION['NAME_OF_SESSION'].
So really, it's just a replace exercise (replace$_POST['user'] with $_SESSION['NAME_OF_SESSION']).

I hope I was clear enough, I'm not that great at explanations xD

Re: Blog/comments integration with login

Posted: Tue Apr 16, 2013 11:35 pm
by Z645
Helx wrote:
Z645 wrote:Explanation please? I tried replacing everything I could think of o-o
Line 25 of comments.inc.php;
When you call the function "add_comment" (when they submit their comment), instead of using a $_POST variable (or whatever) use a $_SESSION variable.

You can't just make one up like a normal $variable, it has to be set. This should be earlier in the code you have created in a login function (I can't seem to find it with what you've given us).

Normally it's called "user" or "username". It's much like a $_POST variable, it's set out like so: $_SESSION['NAME_OF_SESSION'].
So really, it's just a replace exercise (replace$_POST['user'] with $_SESSION['NAME_OF_SESSION']).

I hope I was clear enough, I'm not that great at explanations xD
Well, this is the user.inc.php from the login page.
<?php

// Checks if the given username exists in the table.
function user_exists($user){
	$user = mysql_real_escape_string($user);
	
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}'");
	
	return (mysql_result($total, 0) == '1') ? true : false;
}

// Checks if the given username and password combination is valid.
function valid_credentials($user, $pass){
	$user = mysql_real_escape_string(htmlentities($user));
	$pass = mysql_real_escape_string($pass);
	
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}' AND `user_password` = '{$pass}'");
	
	return (mysql_result($total, 0) == '1') ? true : false;
}


// Checks if the given user account is active
function is_active($user){
	$user = mysql_real_escape_string($user);
	
	$sql = "SELECT
				COUNT(`user_activations`.`user_id`)
			FROM `users`
			INNER JOIN `user_activations`
			ON `users`.`user_id` = `user_activations`.`user_id`
			WHERE `users`.`user_name` = '{$user}'";
			
	$result = mysql_query($sql);
	
	return (mysql_result($result, 0) == '0') ? true : false;
}

// Activates the account related to the given activation code
function activate_account($aid){
	$aid = mysql_real_escape_string($aid);
	
	mysql_query("DELETE FROM `user_activations` WHERE `activation_code` = '{$aid}'");
}

// Adds a user to the Database.
function add_user($user, $email, $pass, $first_name, $last_name){
	$user = mysql_real_escape_string(htmlentities($user));
	$email = mysql_real_escape_string($email);
	$pass = sha1($pass);
	$first_name = mysql_real_escape_string(htmlentities($first_name));
	$last_name = mysql_real_escape_string(htmlentities($last_name));
	
	$charset = array_flip(array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9)));
	$aid = implode('', array_rand($charset, 10));
	
	$body = <<<EMAIL
	
	Welcome to ViBeate!
	
	Before you can login you must activate your account by clicking the link below.
	
	http://vibeate.webege.com/activate.php?aid={$aid}
	
	-The ViBeate Team!
	
EMAIL;
	
	mail($email, 'Welcome to ViBeate', $body, 'From: admin@vibeate.webege.com');
	
	mysql_query("INSERT INTO `users` (`user_name`, `user_password`, `user_email`, `first_name`, `last_name`) VALUES ('{$user}', '{$pass}', '{$email}', '{$first_name}', '{$last_name}')");

	$user_id = mysql_insert_id();
	
	mysql_query("INSERT INTO `user_activations` (`user_id`, `activation_code`) VALUES ({$user_id}, '{$aid}')");
}

function email_exists($email){
                $email = mysql_real_escape_string($email);
               
                $total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '{$email}'");
       
                return (mysql_result($total, 0) == '1') ? true : false;
}

function new_password($email){
	$email = mysql_real_escape_string($email);

	$charset = array_flip(array_merge(range('a','z'), range('A','Z'), range(0, 9)));
	$new_password = implode('', array_rand($charset,15));
					 
	$sql = "UPDATE
											`users`
							SET
											`pass` = '{$new_password}'
							WHERE
											`email` = '{$email}' ";
										   
	mysql_query($sql);
	
	$body = <<<EMAIL
	
	Here is your new password! {$new_password}
	
	-The ViBeate Team!

EMAIL;

	 mail($email, 'Your new password', $body, 'From: admin@vibeate.webege.com');
 
}

?>
And so I replace:
<?php

include('core/init.inc.php');

if (isset($_GET['pid'], $_POST['user'], $_POST['body'])){
	if (add_comment($_GET['pid'], $_POST['user'], $_POST['body'])){
		header("Location: read_post.php?pid={$_GET['pid']}");
	}else{
		header("Location: home.php");
	}
	
	die();
}

?>
into:
<?php

include('core/init.inc.php');

if (isset($_GET['pid'], $_SESSION['user'], $_POST['body'])){
	if (add_comment($_GET['pid'], $_SESSION['user'], $_POST['body'])){
		header("Location: read_post.php?pid={$_GET['pid']}");
	}else{
		header("Location: home.php");
	}
	
	die();
}

?>
?

Edit: I actually fixed it by adding "hidden" to
<p>
							<input type="text" value="<?php echo $_SESSION['username']; ?>" name="user" id="user" hidden>
						</p>

Re: Blog/comments integration with login

Posted: Thu Apr 18, 2013 4:26 am
by Helx
Oh I see what you wanted to do now :)
But I must say, you could probably use type="hidden" to get the same effect as what you now have.

Re: Blog/comments integration with login

Posted: Thu Apr 25, 2013 12:21 am
by Z645
uhm. I've gone through another error with linking user profiles. I can't seem to get the uid to show when the user clicks portfolio. And then I get an error:
Notice: Undefined index: uid in /home/a8126323/public_html/home.php on line 6
The home.php:
<?php

include('core/init.inc.php');
echo error_reporting(E_ALL);

$user_info = fetch_user_info($_GET['uid']);

if (isset($_POST['user'], $_POST['body'])){
	add_post($_POST['user'], $_POST['body']);
	header('Location: http://vibeate.webege.com/home.php');
	die();
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Welcome to ViBeate</title>
		<meta name="description" content="Welcome to ViBeate. ViBeate allows you to connect with friends, family, and co-workers." />
		<meta name="keywords" content="social, networking, games, chat, hangout, friends" />
		<meta name="robots" content="index, follow" />

		<link rel="stylesheet" href="styles/style.css" type="text/css">
        <script type="text/javascript">
          WebFontConfig = {
            google: { families: [ 'Chewy::latin' ] }
          };
          (function() {
            var wf = document.createElement('script');
            wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
              '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
            wf.type = 'text/javascript';
            wf.async = 'true';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(wf, s);
          })(); </script>
    </head>
	
    <body>
        <div id="wrapper">
            <?php include('extras/menu.php'); ?>
            <br />
            <br />
            <div id="main">
                <div id="left_side">
					<form action="" method="post">
						<p>
							<input type="text" value="<?php echo $_SESSION['username']; ?>" name="user" id="user" hidden>
						</p>
						<p>
							<textarea name="body" rows="5" cols="60" placeholder="Post a status here..."></textarea>
						</p>
						<p>
							<input type="submit" value="Post" />
						</p>
					</form>
                    <?php
						$posts = get_posts();
						
						foreach ($posts as $post){
							?>
							<h3><a href="http://vibeate.webege.com/users/portfolio.php?uid=<?php echo $user_info['id']; ?>"><?php echo $post['user']; ?></a></h3> Posted on <?php echo $post['date']; ?>
							<hr />
							<p><?php echo $post['preview']; ?></p>
							<i><a href="read_post.php?pid=<?php echo $post['id']; ?>">(<?php echo $post['total_comments']; ?> comments) <?php echo $post['last_comment']; ?></a></i>
							<?php
						}
						
					?>
                </div>
                
                <div id="right_side">
                    <div class="ads">
                        Advertisment
                    </div>
					<br />
                    <div class="footer">
                        <center><?php include('extras/footer.php'); ?></center>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
profile.inc.php:
<?php

//fetches all the users from the table
function fetch_users(){
	$result = mysql_query('SELECT `user_id` AS `id`, `user_name` AS `username` FROM `users`');
	
	$users = array();
	
	while (($row = mysql_fetch_assoc($result)) !== false){
		$users[] = $row;
	}
	
	return $users;
}

//fetches profile information for the given user
function fetch_user_info($uid){
	$uid = (int)$uid;

	$sql = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_id` = '{$uid}'");
			
	$result = mysql_query($sql);
	return $result;
}

?>

Re: Blog/comments integration with login

Posted: Thu Apr 25, 2013 4:23 am
by ExtremeGaming
That error means that uid isn't present in the url. Make sure you check if it exists first.
<?php
if(isset($_GET['uid'])) {
$user_info = fetch_user_info($_GET['uid']);
} else {
die("uid is not set");
}
?>
The URL should look like home.php?uid=1234