PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Fri Dec 15, 2017 10:47 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 16 posts ]  Go to page 1, 2  Next
Author Message
PostPosted: Thu Mar 09, 2017 6:31 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 179
Hi,

I'm a beginner in php. Starting my learning at php 7 and not 5 or earlier.
I don't understand why php 7 is acting weird. It give different result at different time. Do you guy mind checking if I got the coding wrong or if I've come across a php 7 bug ?
It is a basic member registration & login script.

How It Works:
1. When you register (username, password, email), it dumps the data onto a MySQL table "pending_users" and inserts "0" on "account activation" row. It will replace the "0" with "1" after you click the account activation link that gets emailed to you.
It sends you email with your account activation link that contains your account activation code (GET METHOD).


2. When you click the account activation link, your email gets verified and a new table in mysql gets created under your username. That table will contain data of your account activities.
Script replaces the "0" (table: pending_users, row: account activation) with "1" after you click the account activation link that gets emailed to you. If you click the link anytime, anyday after that then you get alerted a message asking you why you trying to activate an account you already activated.

That's about it.

Pages: register.php AND account_activation.php.

The problems are in the account_activation.php. When you click the account activation link in your email then that page takes over. So far, so good. Now, notice that after you get the message that your account has been activated, you do not get redirected to home.php like the script says. Redirection failing in php 7.

PROBLEM 2: You will see you get errors not on the error file but on the activation_account.php page. The error:

<pre>You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'varchar(30) NOT NULL, Email varchar(50) NOT NULL, Forename varchar(30)' at line 3</pre>


OTHER ISSUE:
I am trying to learn php starting from php 7. Getting these codes watching youtube php channels. I update as much as I can to customize according to my needs. I fear the code may contain php 5 syntax and so if you spot any then kindly show me a php 7 syntax example and get a thumbs-up from here.

PS - Why don't you guys open a php 7 tutorial channel and teach how to build Social Network like facebook, twitter and youtube etc. ? There are channels in youtube that teach these but they don't regularly upload videos and and I hate the waiting.

Thanks


register.php

Syntax: [ Download ] [ Hide ]

<!DOCTYPE html>
<html>
<head>
<title>Signup Page</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<center><h2>Loud Gobs Browser Signup Form</h2></center>
<form method="post" action="">
<div class="form-group">
<center><label for="username">Username:</label>
<input type="text" class="form-control" id="user" placeholder="Enter a unique Username" name="member_registration_username"></center>
</div>
<div class="form-group">
<center><label for="password">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter new Password" name="member_registration_password"></center>
</div>
<div class="form-group">
<center><label for="password">Repeat Password:</label>
<input type="password" class="form-control" id="member_registration_repeat_pwd" placeholder="Repeat new Password" name="member_registration_password_confirmation"></center>
</div>
<div class="form-group">
<center><label for="forename">First Name:</label>
<input type="text" class="form-control" id="member_registration_first_name" placeholder="Enter your First Name" name="member_registration_forename"></center>
</div>
<div class="form-group">
<center><label for="surname">Surname:</label>
<input type="text" class="form-control" id="member_registration_last_name" placeholder="Enter your Surname" name="member_registration_surname"></center>
</div>
<div class="form-group">
<center><label for="email">Email:</label>
<input type="email" class="form-control" id="member_registration_email" placeholder="Enter your Email" name="member_registration_email"></center>
</div>
<div class="form-group">
<center><label for="email">Repeat Email:</label>
<input type="email" class="form-control" id="member_registration_repeat_email" placeholder="Repeat your Email" name="member_registration_email_confirmation"></center>
</div>
<center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
<center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
</form>
</div>
</body>
</html>
<?php
require "conn.php";
if  (isset($_POST['submit']))
{
        if(!empty($_POST["member_registration_username"]) && !empty($_POST["member_registration_password"])&& !empty($_POST["member_registration_password_confirmation"])&& !empty($_POST["member_registration_email"])&& !empty($_POST["member_registration_email_confirmation"])&& !empty($_POST["member_registration_forename"])&& !empty($_POST["member_registration_surname"]))
        {
                $member_registration_account_activation = 0;
                $member_registration_random_numbers = random_int(0, 9999999999);
               
               
        $member_registration_username = trim($_POST["member_registration_username"]);
        $member_registration_forename = trim($_POST["member_registration_forename"]);
        $member_registration_surname = trim($_POST["member_registration_surname"]);
        $member_registration_password = trim($_POST["member_registration_password"]);
        $member_registration_password_confirmation = trim($_POST["member_registration_password_confirmation"]);
        $member_registration_email = trim($_POST["member_registration_email"]);
        $member_registration_email_confirmation = trim($_POST["member_registration_email_confirmation"]);
                $member_registration_account_activation_code = trim("$member_registration_random_numbers");      
               
        $member_registration_username = mysqli_real_escape_string($conn,$_POST["member_registration_username"]);
        $member_registration_forename = mysqli_real_escape_string($conn,$_POST["member_registration_forename"]);
        $member_registration_surname = mysqli_real_escape_string($conn,$_POST["member_registration_surname"]);
        $member_registration_password = mysqli_real_escape_string($conn,$_POST["member_registration_password"]);
        $member_registration_password_confirmation = mysqli_real_escape_string($conn,$_POST["member_registration_password_confirmation"]);
        $member_registration_email = mysqli_real_escape_string($conn,$_POST["member_registration_email"]);
        $member_registration_email_confirmation = mysqli_real_escape_string($conn,$_POST["member_registration_email_confirmation"]);       
        $member_registration_account_activation_code = mysqli_real_escape_string($conn,$member_registration_account_activation_code);    
               
                if($member_registration_email != $member_registration_email_confirmation)
                {
            echo "<center>Your email inputs do not match! Try inputting again and then re-submit.</center>";
            $conn->close();
                exit();
        }
        else
            {
        }
        if($member_registration_password != $member_registration_password_confirmation)
                {
            echo "<center>Your password inputs do not match! Try inputting again and then re-submit.</center>";
            $conn->close();
                exit();
        }
        else
        {
        }
               
        $sql_check_username_in_pending_users = "SELECT * FROM pending_users WHERE Username='".$member_registration_username."'";
        $result_username_in_pending_users = mysqli_query($conn,$sql_check_username_in_pending_users);
        if(mysqli_num_rows($result_username_in_pending_users)>0)
                {
                    echo "<script>alert('That Username $member_registration_username is pending registration!')</script>";
            exit();
        }
                       
                $sql_check_username_in_users = "SELECT * FROM users WHERE Username='".$member_registration_username."'";
        $result_username_in_users = mysqli_query($conn,$sql_check_username_in_users);
        if(mysqli_num_rows($result_username_in_users)>0)
                {
            echo "<script>alert('That Username $member_registration_username is already registered!')</script>";
            exit();
        }

        $sql_check_email_in_pending_users = "SELECT * FROM pending_users WHERE Email='".$member_registration_email."'";
        $result_email_in_pending_users = mysqli_query($conn,$sql_check_email_in_pending_users);
        if(mysqli_num_rows($result_email_in_pending_users)>0)
                {
            echo "<script>alert('That Email $member_registration_email is pending registration!')</script>";
            exit();
        }
               
                $sql_check_email_in_users = "SELECT * FROM users WHERE Email='".$member_registration_email."'";
        $result_email_in_users = mysqli_query($conn,$sql_check_email_in_users);
        if(mysqli_num_rows($result_email_in_users)>0)
                {
            echo "<script>alert('That Email $member_registration_email is already registered!')</script>";
            exit();
        }

            $sql = "INSERT INTO pending_users(Username,Password,Email,Forename,Surname,Account_Activation_Code,Account_Activation) VALUES('".$member_registration_username."','".$member_registration_password."','".$member_registration_email."','".$member_registration_forename."','".$member_registration_surname."','".$member_registration_account_activation_code."','".$member_registration_account_activation."')";
        if($conn->query($sql)===TRUE)
            {
                echo "Data insertion into table success!";
        }
            else    
            {
            echo "Data insertion into table failure!";
                $conn->close();
                exit();
            }
       
            $to = "$member_registration_email";
            $subject = "loudgobs Browser Account Activation!";
            $body = "$member_registration_forename $member_registration_surname,\n\n You need to click the following link to confirm your email address and activate your account.\n\n\
            http://www.loudgobs.com/loudgobs-browse ... ation_code"
;
            $from = "admin_loudgobs-browser@loudgobs.com";
            $message = "from: $from";
       
            mail($to,$subject,$body,$message);
            echo "<script>alert('Check your email for further instructions!')</script>";
            $conn->close();
    }
        else
        {
            echo "<script>alert('You must fill-in all input fields!')</script>";
                $conn->close();
        }
}

?>

 


activate_account.php

Syntax: [ Download ] [ Hide ]

<?php
session_start();
require "conn.php";

    //Grab account activator's email and account activation code from account activation link's url.
       
if(!isset($_GET["email"], $_GET["member_registration_account_activation_code"]) === TRUE)
{
        echo "<script>alert('Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account!')</script>";
    $conn->close();    
        header("location:register.php");
        exit();
}
else
{
        $confirmed_email = trim($_GET["email"]);
        $member_registration_account_activation_code = trim($_GET["member_registration_account_activation_code"]);
       
        $confirmed_email = mysqli_real_escape_string($conn,$confirmed_email);
        $member_registration_account_activation_code = mysqli_real_escape_string($conn,$member_registration_account_activation_code);
       
       
        //Check User's Username (against users tbl) if it has already been taken or not whilst User was in midst of activating his/her account.
   
    $query = "SELECT * FROM users WHERE Email = '".$confirmed_email."'";
    $result = mysqli_query($conn,$query);
        $numrows = mysqli_num_rows($result);
        if($numrows != 0)
    {  
        echo "<script>alert('That email '".$confirmed_email."' is already registered!')</script>";
                $conn->close();
                exit();
        }
        else
    {
        //Grab User details from table "pending_users". Search data with confirmed Email Address.
                       
                $query = "SELECT * FROM pending_users WHERE Email = '".$confirmed_email."'";
                $result = mysqli_query($conn,$query);
                $numrows = mysqli_num_rows($result);
                if($numrows = 0)
                {              
                        echo "<script>alert('Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account!')</script>";
                        $conn->close();
                        exit();
                }
                else
                {
                    while($row = mysqli_fetch_assoc($result))
                    {    
                                $db_id = $row["Id"];
                                $db_username = $row["Username"];
                                $db_password = $row["Password"];
                                $db_email = $row["Email"];
                                $db_forename = $row["Forename"];
                                $db_surname = $row["Surname"];
                                $db_account_activation_code = $row["Account_Activation_Code"];
                                $db_account_activation = $row["Account_Activation"];               
           
                                if($db_account_activation != 0)
                                {
                                        echo "<script>alert('Since your account is already activated, why are you trying to activate it again ?')</script>";
                                        $conn->close();
                                        exit();
                                }
                                else
                                {
                                        $conn->query("UPDATE pending_users SET Account_Activation 1 WHERE Email = '".$confirmed_email."'");            
                            echo "Activating your account! Wait to be auto-logged-in to your account as that will be the sign that your account has been activated.";
                                        echo "Your email '".$confirmed_email."' has now been confirmed!";
                                    echo "Activating your account! Wait to be auto-logged-in to your account as that will be the sign that your account has been activated.";
               
               
                                        //Create table under $username to hold user account activity data.

                                        $sql = "CREATE TABLE $db_username (
                                        Id INT(6) UNSIGNED AUTO_INCREMENT, PRIMARY KEY
                                        Username varchar(30) NOT NULL,
                                        Email varchar(50) NOT NULL,
                                        Forename varchar(30) NOT NULL,
                                        Surname varchar(30) NOT NULL,
                                        Password varchar(32) NOT NULL,
                                        Profile_Pic (longblob) NOT NULL,
                                        Bio varchar(250) NOT NULL,
                                        Status varchar(100) NOT NULL)"
;
         
                                        if ($conn->query($sql) != TRUE)
                                        {
                                            echo "Error creating table: " . mysqli_error($conn);
                                                $conn->close();
                    }
                                        else
                                        {
                        echo "Table $db_username created successfully";
                                                                       
                       
                                                //Copy $user's registration data from table "pending_users" to table user.
       
                                                $sql = "INSERT INTO $db_username(Username,Password,Email,Forename,Surname,Account_Activation_Code) VALUES('$db_username','$db_password','$db_email','$db_forename','$db_surname','$db_account_activation_code')";

                                                if($conn->query($sql) != TRUE)
                                                {
                                                        echo "inserting data into table $db_username failed! " . mysqli_error($conn);
                                                        $conn->close();
                                                       
                                                }
                                                else
                                                {      
                                                        echo "inserted data into table $db_username!";
                                       
                               
                                                        //Copy $user's registration data from table "pending_users" to table users.
       
                                                        $sql = "INSERT INTO users (Username,Password,Email,Forename,Surname,Account_Activation_Code) VALUES('$db_username','$db_password','$db_email','$db_forename','$db_surname','$db_account_activation_code')";

                                                        if($conn->query($sql) != TRUE)
                                                        {
                                                                echo "inserting data into table users failed! " . mysqli_error($conn);
                                                                $conn->close();
                                                               
                                                        }
                                                        else
                                                        {      
                                                                echo "inserted data into table users!";
                                               
                                               
                                                                //Redirect newly activated user to his/her account homepage.
                                                               
                                                                $user = $db_username;
                                                                $userid = $db_id;
                                                                $_SESSION["user"] = $user;
                                                               
                                                                header("location: home.php");
                                                        }
                                                }      
                                        }      
                                }
                        }
                }
    }
}

?>

 


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 12:33 am 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
Header redirects do not work if there has been any output sent already.

echo "inserted data into table users!"; is output being sent out.

Headers have to be sent before content is sent so as soon as you echo you cause whatever headers are already prepared to be sent as well. Sending a header redirect after the initial set of headers has already been sent will have no effect on your web browser.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 12:34 am 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
http://php.net/manual/en/function.header.php

Quote:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.


The documentation also says that you should see an error message if this situation is happening to you but I've honestly never seen the error.

In older versions of php for reasons unknown to me you could sometimes get away with echoing a hell of a lot of text before calling a header redirect and it would still work. Then you upgrade your server or move to a different host and suddenly NOTHING works.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 12:47 am 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
You should refactor your code at this poin.

Most of those comments that explain what the next section of code is doing are clear indicators that a section of code should probably be turned into a function. Even if you don't see anywhere else to _re-use_ that function it will at least give you easier to read code in the main file and a single easy to find location for troubleshooting / version tracking that section of code.

Quote:
//Check User's Username (against users tbl) if it has already been taken or not whilst User was in midst of activating his/her account.


This could become
Quote:
checkUsernameAvailability( $email )
and simply return true or false.

You should try to do as much of your php as possible (including all header redirects) before doing any html output.

Do your php. Set variables that will be used by the view. Think of it as 2 separate layers of logic. First layer is the logic of how the actual system works. Second layer is the logic of what to show or not show on the page, which is based on the results of the first layer of logic. There may be a few if statements that feel unnecessarily repeated in both layers but overall it results in much more readable and maintainable code.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 12:58 am 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
As a beginner you are desperate for feedback from every step of the logic so you add things like: echo "inserted data into table users!"; in every IF or ELSE.

What you could do instead is make another page full of queries that check "what is the most recent entry in table X" and keep that page open in another window and use a browser extension like ReloadEvery to make that window refresh every 5 seconds. Now when you test your code you just look over at that window to see if the new db records appeared as you expected.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 1:07 am 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
Quote:
...and a new table in mysql gets created under your username. That table will contain data of your account activities.


I'm no database expert but that sounds completely unnecessary.

There shouldn't be any problem with putting all users account activities into a single table with a field that references the unique id of the user so that you can easily select only the activity records that belong to 1 specific user.

table: user_activity
fields: id, user_id, activity_type_id, when_created

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 2:01 am 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
If you know how to navigate github take a look at the commit history of https://github.com/thinsoldier/phpdevne ... its/master and view each in side-by-side split mode to get a better idea of what I'm talking about.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 5:50 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 179
thinsoldier wrote:
You should refactor your code at this poin.

Most of those comments that explain what the next section of code is doing are clear indicators that a section of code should probably be turned into a function. Even if you don't see anywhere else to _re-use_ that function it will at least give you easier to read code in the main file and a single easy to find location for troubleshooting / version tracking that section of code.

Quote:
//Check User's Username (against users tbl) if it has already been taken or not whilst User was in midst of activating his/her account.


This could become
Quote:
checkUsernameAvailability( $email )
and simply return true or false.

You should try to do as much of your php as possible (including all header redirects) before doing any html output.

Do your php. Set variables that will be used by the view. Think of it as 2 separate layers of logic. First layer is the logic of how the actual system works. Second layer is the logic of what to show or not show on the page, which is based on the results of the first layer of logic. There may be a few if statements that feel unnecessarily repeated in both layers but overall it results in much more readable and maintainable code.


Thank you for the suggestion but I'm a complete newbie who just read upto VARIABLES section on php.net and so do not know how to build my own custom functions, Guessing you do it like thi ...

custom_function_name(write variables and php lib functions here).

But what you suggested makes sense and saves us from code clutter. Will take into account your sugg once I become a bit more experienced on how to build my own functions. Ok ? In the meanwhile putup with my lengthy comments on my php codes.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 5:52 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 179
thinsoldier wrote:
As a beginner you are desperate for feedback from every step of the logic so you add things like: echo "inserted data into table users!"; in every IF or ELSE.

What you could do instead is make another page full of queries that check "what is the most recent entry in table X" and keep that page open in another window and use a browser extension like ReloadEvery to make that window refresh every 5 seconds. Now when you test your code you just look over at that window to see if the new db records appeared as you expected.



Yeah, those feedbacks were just to check if my codes were working or not. Would remove them from the final code. Can ditch these feedbacks to another table "admin_logs". That way can check how my site is fairing.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 5:54 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 179
thinsoldier wrote:
Quote:
...and a new table in mysql gets created under your username. That table will contain data of your account activities.


I'm no database expert but that sounds completely unnecessary.

There shouldn't be any problem with putting all users account activities into a single table with a field that references the unique id of the user so that you can easily select only the activity records that belong to 1 specific user.

table: user_activity
fields: id, user_id, activity_type_id, when_created



Other programmers tell me same thing. Not to create tables under usernames but I have my reason. When you check my final code, you would understand why it was necessary.


Top
 Profile  
 
PostPosted: Fri Mar 17, 2017 6:42 pm 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
UniqueIdeaMan wrote:
Other programmers tell me same thing. Not to create tables under usernames but I have my reason. When you check my final code, you would understand why it was necessary.


You should be able to simply explain your reason to me.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Sun Oct 08, 2017 6:47 pm 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
thinsoldier wrote:
If you know how to navigate github take a look at the commit history of https://github.com/thinsoldier/phpdevne ... its/master and view each in side-by-side split mode to get a better idea of what I'm talking about.


Did you ever look at the github link? Did you learn anything from it? I'm about to delete it.

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Mon Oct 09, 2017 5:20 pm 
Offline
Forum Newbie

Joined: Sun Nov 15, 2015 12:57 pm
Posts: 12
The OP cross posts the same EXACT posts on at least 15 forums so it may take him awhile to check it out.


Top
 Profile  
 
PostPosted: Mon Oct 09, 2017 5:25 pm 
Offline
Forum Contributor

Joined: Fri Jul 20, 2007 11:29 am
Posts: 341
benanamen wrote:
The OP cross posts the same EXACT posts on at least 15 forums so it may take him awhile to check it out.


Are there actually 15 active php forums out there?

_________________
Warning: I have no idea what I'm talking about.


Top
 Profile  
 
PostPosted: Sun Oct 29, 2017 2:19 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 179
I just read your post now and checked-out github your link. I see it listing my codes from my threads. What is your point in all this ? I don't understand github. Did you manually copy & paste my codes from each of my threads here to github by opening different threads or did you somehow create the threads at github with my codes automatically ?
Anyway. best delete the githubs to erase my old buggy codes and their histories.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 16 posts ]  Go to page 1, 2  Next

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 13 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group