Blog Log in help

#1

Hello everyone,

I am trying to create a blog where the user must be logged in to comment. I can comment without being logged in. It seems there is an interrupt when I create a new user as well. Because when I log out I get these errors:

Notice : session_start(): A session had already been started - ignoring in C:\xampp2\htdocs\BlogProject\comments.php on line 87

Warning : Cannot modify header information - headers already sent by (output started at C:\xampp2\htdocs\BlogProject\posts.php:24) in C:\xampp2\htdocs\BlogProject\comments.php on line 89

I am unable to add new users anymore.

Here is my code: https://drive.google.com/drive/folders/1Fj2PjJIN2rYA5FoubQ3NlCYFdAxyfwyW?usp=sharing

#2

Sorry for how this sounds, but this code is completely disorganized and needs to be re-done. The only good thing I saw it doing was using password_hash(), but even this has a problem, since password_verify() was not being used in the login code.

I recommend that you start small, with just the main index.php page and the signup.php page, then after you get the signup working, add the login page and then the comments page. See the following list of suggestions that will help organize and simplify the code and should make it easier to produce working code -

  1. The ‘includes’ folder should only contain files that you ‘require’ into the main code for any particular page. It should not contain file(s) that are the target of a form action.
  2. You should use ‘require’ for things that your code must have for it to work and require isn’t a function, so the ( ) around the file name is unnecessary clutter.
  3. Each page must produce a valid html document. You are outputting markup and content before the start of your html document in several cases. You should validate the resultant pages at validator.w3.org
  4. The code for each page should be laid out in this general order -

Initialization - require/create things your page needs for it to work. This would be things like session_start(), the database connection… This will result in code only existing once (multiple session_start statements is the cause of your current error.)

Post method form processing code.

Get method business logic - get/produce data needed to display the page.

Html document - should contain only simple php logic needed to display dynamic content.

  1. You should use exceptions to handle database statement (connection, query, prepare, and execute) errors and in most cases let php catch and handle the exception, where it will use its error related settings to control what happens with the actual error information. When learning, developing, and debugging code/queries, you should display all errors. When on a live/public server, you should log all errors.
  2. You should use prepared queries when supplying external/unknown data to the sql query statement when you execute it. This will actually simplify the sql query syntax.
  3. You should switch to the much simpler and more consistent php PDO extension. The mysqli extension is overly complicated, especially when dealing with prepared queries.
  4. Put the form and the form processing code on the same page. This will eliminate a bunch of logic from your code.
  5. Your form processing code should detect if the REQUEST_METHOD == POST, trim all the input data, don’t copy variables to other variables, validate all the input data at once, store validation errors in an array, produce unique and helpful error messages, then only use the submitted data if there are no validation errors.
  6. Your database column names should indicate the meaning of the data in the column.
  7. To detect duplicate user submitted data, set up the database column(s) as unique index(es), just insert the data and detect if a duplicate key error occurred.
  8. User written functions should be general purpose, accept all input data as call-time parameters, and should not be responsible for echoing output.
  9. All header() redirects need exit/die statements after them to prevent the rest of the code from running.
  10. Don’t Repeat Yourself (DRY.) If you find yourself repeating code/markup, you need to separate out the duplicate and reuse it, so that it only exists once and only needs to be modified or corrected in one place.
  11. Keep It Simple (KISS.) Use the simplest code/syntax that accomplishes a task. Most programming is not complicated. If it seems like you are spending more time on the implementation details and less time on the actual logic you are trying to accomplish, you are probably doing something wrong.
  12. The header.php and footer.php files should only contain the html markup for the header/footer of the page. The common php initialization code in the header.php file and the repeated navigation markup in both should be in separate .php files.
  13. Don’t echo static markup and content. The point of php is to produce the dynamic content on a page.
  14. If you have just started learning, you should only attempt to put one form/form processing on a page, with navigation links to allow you to move between different pages on your site.
  15. Any ‘dynamic’ (unknown) values that are output on a web page need to have htmlentities() applied to them to help prevent cross site scripting.
  16. Any php error settings should be in the php.ini on your system, not in your code.
  17. The signup and login pages should detect if the current visitor is already logged in.
  18. After successfully completing any post method form processing, you should redirect to the exact same page/url to cause a get request for that page/url - PRG - Post, Redirect, Get
2 Likes
Php Email Verification Login (Code Implementation Problem)
#3

phdr has a lot of good points…

Here are my observation after quickly looking over your HTML and Code.

First stop using inline CSS, use an external CSS file.

Better yet use a Web Templating System that way you don’t really have to worry about sanitizing in PHP other than using prepared statements (in my opinion sometimes that is good enough). Two popular Templating systems are Smarty (That is the one I use) and Twig, both can be both found using a Google Search and both can do sanitizing with ease.

Here’s an example of my blog templates (I have a general template that takes care of the basic HTML/CSS structure):
blog.tpl

{extends file="general_page_template.tpl"}
{block name=title}
    {$title|escape}
{/block}



{block name=body}
    <div class="main">
        {nocache}
            <h1>The Daily Blog</h1>
            <div id="gallery" class="picture-box" data-total="{$journal|count}" >
                {counter start=-1 skip=1 print=false}
                <div class="article">
                    {foreach $journal as $cms}
                        <h2>{$cms.heading} <span class="subheading">by {$cms.author} on {$cms.date_added}</span></h2>
                        <a class="myLightBox" href="{$cms.image_path}" title="Picture Gallery" data-picture="{counter}" 
                           data-exif="{if $cms.Model}{$cms.Model}   ---   {$cms.FocalLength}    {$cms.Aperture}    {$cms.ISO}    {$cms.ExposureTime}{/if}"><img class="box" src="{$cms.thumb_path}" alt="Picture for Journal Entry"></a>                    
                        <hr>
                        <p>{$cms.content|nl2br}</p>
                    {/foreach}
                </div>
            </div>
        {/nocache}
    </div>
    {block name="aside"}
    {/block}
{/block}

Here’s my blog.php file:

require_once '../private/initialize.php';

use Library\Read\Read;

$display = new Read();

$journal = $display->readBlog(); // Read in My Blog Posts

//echo "<pre>" . print_r($journal, 1) . "</pre>";
 if (is_logged_in()) {
     header("Location: member_page.php");
     exit();
 }
 if (is_logged_in()) {
    $smarty->assign('display_status', true);
}
else {
    $smarty->assign('display_status', false);
}

$smarty->assign('holidayMessage', $holiday_message);
$smarty->assign('journal', $journal);
$smarty->assign('calendar', $calendar);
$title = "The Photo Journal";
$smarty->assign("title", $title);
$smarty->display('blog.tpl');

As you can see it splits the PHP and HTML/CSS/Javascript in two. In my opinion a person could do just the templating programing without having to know PHP just as long as the backend php developer told the person doing the templating the variables/arrays being used in php.

However, I was going off topic a little. The main thing I was trying to get at is to keep your PHP and HTML/CSS separated as possible, be it using regular php and HTML/CSS or using a templating system. I think you will find it easier making the blog and even the user registration/login system. I have a member page template (member_page.tpl) that only members (Which is only me for the moment) to add/edit/delete posts that are made. I find it easier to using a templating system, but it can be easily made without one. Without using a templating system, do what phdr recommends keep it on one page with most of the PHP on top and the all of the HTML on bottom with a little PHP sprinkle in for you blogging posts.

To see it in action -> https://www.miniaturephotographer.com/blog.php

#4

Thank you so much for your detailed explanation. No worries, I am learning and I know I will make many mistakes =). I really appreciate your feedback =D

#5

Thank you, I really appreciate you taking all that time to explain these things to me. I am truly thankful!!!