TOR MARKETPLACE | LEARN WITH ME HOW TO CREATE YOUR TOR MARKETPLACE AND CREATE A CRYPTO PAYMENT SYSTEM WITHOUT KYC AND THIRD-PARTY APPS

D2

Администратор
Регистрация
19 Фев 2025
Сообщения
4,380
Реакции
0
Written By: 0x43rypt0n
Source: https://www.xss.is

This thread is about Creating a TOR marketplace and Creating A standalone crypto payment system Without using Any third party apps or api and staying safe from getting banned by 3d party

orders.png



In the first place I will only focus on creating a standalone Bitcoin wallet using Electrum You can use Bitcoin Core but because of the space are required by Bitcoin Core about 7Gb and the high bandwidth so I decided to use Electrum They are the same and give us the ability to create the StandAlone Bitcoin wallet and both they support RPC so we can control the Wallet from any programming languages that support networking in this example i will use php because is the most popular scripting language for web developing and i use Curl to fetch the commands like Create a new bitcoin address for every User and every payment So every time a user create a payment or buy a product the system will generate a new address and initiate the RPC protocol
and use it from php and
In this tutorial will develop all the required futures to launch a successful marketplace place if you want to add new futures like adding new vendors or users delete or any other future you can use the same code I have added in this tutorial to add your futures
For example :
If you want to create a multi vendor system future you can copy the code of the future register new member and add a new user group to the system and make small modifications to the system

In this tutorial I will not focus too much on the design iam not a UI/UX designer so the design will be very simple you can create your Style and add it to the same php code will work fine

What is the Hack the required tools?
All The tools are used in this tutorial are completely free ,
We Need Linux distribution like Ubuntu , a web server you can use any like Apache or Nginx
Dont forget to install php-fpm and finally we need the Electrum you can download it from here and install it the installation instructions are available on the official Electrum site https://electrum.org/#download

What is the Hack required to start with me?
You do know how to read and write php basic and php object-oriented programming code this is all that is required from you If you dont know how to write php go to https://www.php.net/docs.php and read the basics of php then you can continue this tutorial , the electrum rpc commands will be explained you dont have to know anything about it also the mysqli instructions will be explained for newbies , a few cron commands will be added it also not required to be a Linux professional I will also explain it

How to test the script is money needed or real Bitcoin to test the transactions ?
No none of them are required. but how to test the script ? for testing the script We will use the Testnet Bitcoin network to send Bitcoin transactions and check if the script works fine and dont worry the same script and same configuration works fine for both the testnet network and the real Bitcoin network but you only need to change the port of the electrum network from testnet to real bitcoin network I will explain everything

What is a bitcoin testnet and how do create an electrum testnet wallet to test the script and transactions before deploying the script to the internet and how do you create a real electrum Bitcoin wallet?

The testnet is a test network for the bitcoin blockchain that normally is used for testing and it is an alternative to the real bitcoin network blockchain.
The testnet coins are not the same as real network coins and are distinct from actual real bitcoin
It does not have any real value so you can't use it to buy But for testing after testing is done you can use the real bitcoin to accept payments. The testnet network allows developers like us to test their applications before deploying them to a real network and to not lose any real money

How to create an electrum testnet and a real Electrum bitcoin wallet ?
This is very easy from your Linux terminal write the command :
This command will start the Electrum daemon
electrum daemon –testnet
This command will create a Testnet Electrum Wallet
electrum create –testnet
This command will load the created testnet wallet
electrum daemon load_wallet —testnet
So now we have prepared all the required to start our testnet network
How to create the real Bitcoin network for electrum ? the same as we did in testnet but this time will only remove the –testnet example:
This command will start the Electrum daemon
electrum daemon
This command will create a Testnet Electrum Wallet
electrum create
This command will load the created testnet wallet
electrum daemon load_wallet
As you can see we just removed the –testnet and now we have both running the Testnet Bitcoin network and the real Bitcoin network
Now we can use the bitcoin wallet But we cannot use it from the programming language for sure because we still have not configured the RPC to configure the RPC you can do this with these few commands

To configure the testnet first , Again from your linux terminal type these commands :

Set the username for testnet
electrum setconfig rpcuser "user" --testnet

Set password for testnet
electrum setconfig rpcpassword "1234" --testnet

Set rpcport for testnet
electrum setconfig rpcport 8888 --testnet

So we have set the port 8888 for the testnet and user , password no we can create the config for the rpc real bitcoin network and the port for the real bitcoin rpc is 7777

electrum setconfig rpcuser "realbitcoin"
electrum setconfig rpcpassword "realbitcoin123"
electrum setconfig rpcport 7777

Same as we did before just removing the –testnet

Let's test If the electrum is setup correctly and ready to accept RPC connections
We can check by any command I will try to check using the command getbalance but before we test the rpc we first need to test directly from the terminal by typing electrum getbalance –testnet
If you want to test the normal wallet not the testnet just remove the argument –testnet
The replay from the server should be 0 if you have no balance or if you have fresh newly installed electrum

:- Response

{
"confirmed": "0.06267299"
}

This is my testnet wallet balance in a few more seconds I will teach you how you can get a free test coin bitcoin without paying any $ just remember testnet coin can’t be used to pay bitcoin bills

Now we can confirm is ready to be used from the command line but it is ready to be used from RPC lets check using curl
curl --data-binary '{"jsonrpc":"2.0","id":"curltext","method":"getbalance","params":[]}' http://user:1234@127.0.0.1:8888

You can change the user and password also the port all can be changed to the settings that you entered will setting up the rpc

-: Server response
{"result": {"confirmed": "0.06267299"}, "id": "curltext", "jsonrpc": "2.0"}root@
The response is in json format so this will be easy to parse the result
Now we confirmed that everything is going well so we can step forward and start coding the market

Let's start .

After setting the electrum Crypto wallet now will add the required tables to the Database go to your phpmyadmin if you are on the localhost it should be on this path http://localhost/phpmyadmin create a new database I already created one and name it TorMarket remember if you are under windows and you are using wamp or xmpp server the default password for the phpmyadmin is Empty no password and the username is root

When you are done creating the database now Create tables to make to you more simple just use these sql queries

Crypto_payment_system

Products

Usergorups

users

After done now We need these 13 files php,css to build the Tor market

\-- root
|-- index.php
|-- register.php
|-- login.php
|-- logout.php
|-- checktransactions.php
|-- usercp.php
\-- includes
|-- index.php
\-- php
|-- index.php
|-- classes.php
|-- navbar.php
|-- db.sql.php
\-- style
|-- index.php
|-- main.css
\-- imgs

After creating the files and folders now will fill them with the HTML codes without the php codes and after this you can see the files are not finished when adding the php code will slice the code some codes and forms will be hidden for guests and will only show only for registered users and add new products will be available only for Administrators all this will be in the php now this is the html , css codes

main.css
CSS: Скопировать в буфер обмена
Код:
body
{
    background-color:#f6faf7;
    font-family:Arial;
}
#registerLoginTable
{
    margin-top:13%;
}
#registerLoginTable h1
{
    color:#f26722;
    font-weight:100;
}
#registerLoginTable table 
{
    text-align:left;
    border:1px dotted #f26722;
    padding:5px;
}
#registerLoginTable table th,td
{
   padding:5px;
   font-weight:100;
}
#registerLoginTable input
{
   border:1px solid #034956;
   border-radius:5px;
   padding:5px;
}
#registerLoginTable button
{
   padding:15px;
   font-weight:100;
   color:#f6faf7;
   background:#034956;
   cursor:pointer;
   border:0px;
   border-radius:5px;
}
.msgregistersuccess
{
    background:#e2f1f2;
    color:#034956 !important;
    font-weight:100;
    padding:5px;
    font-size:17px;
}
.msgregisterfaild
{
    background:#e2f1f2;
    color:#f26722;
    font-weight:100;
    padding:5px;
    font-size:17px;
}
#nav
{
    text-align:center;
}
#nav ul 
{
    list-style:none;
}
#nav ul li 
{
    display:inline;
    padding:20px;
}
#nav ul li a
{
    text-decoration:none;
    font-weight:light;
    font-size:1em;
    color:#034956 !important;
}
#nav ul li b a
{
    font-weight:bold;
    font-size:2em;
    color:#f26722 !important;
    padding:30px;
}
#Products ul
{
    list-style:none;
    float:left;
    margin-left:7%;
    margin-top:5%;
}
#Products ul li
{
    display:block;   
}
#Products ul li  img
{
    max-width:250px;
}
#Products ul li a
{
    text-decoration:none;
    font-weight:light;
    color:#034956;
    font-size:1.1em;
}
#display_product
{
    margin-top:5%;
}
#display_product ul 
{
    list-style-type: none;
    margin-left:30%;
}
#display_product ul li 
{
    text-align: left;
}
#display_product ul li b
{
    color:#034956;
}
#display_product ul li h3
{
    color:#f26722;
  
}
#display_product ul li img
{
    width:500px;
    max-width:500px;
}
#display_product ul li button
{
    background-color: #034956;
    color:#e2f1f2;
    border:0px;
    padding:15px;
    cursor:pointer;
}
.orders th
{
    border:1px solid #034956;
}   
#footer 
{
    clear:both;
    margin-top:11%;
    font-weight:100;
}
#footer  a
{
   text-decoration:none;
   color:#034956;
}

navbar.php
HTML: Скопировать в буфер обмена
Код:
<div id="nav">
    <ul>
        <li><b><a href="index.php" >Tor Market</a></b></li>
        <li><a href="index.php">Home</a></li>
            
        <li><a href="register.php">Register</a></li>
        <li><a href="login.php">Login</a></li>
        <li><a href="usercp.php?addproduct">Add Product</a></li>
        <li><a href="usercp.php?orders">Orders <span style="color:#f26722"> (0)</span></a></li>
        <li><a href="usercp.php?changepassword" >change password</a></li>
        <li><a href="logout.php">Logout</a></li>
    </ul>
</div>

Index.php
HTML: Скопировать в буфер обмена
Код:
<!DOCTYPE HTML>
<html lang="en">
    <head>  
          <title>Products</title>            
            <link rel="stylesheet" type="text/css" href="admin/includes/style/main.css" />
    </head>
<body>


<div id="nav">
        <ul>
            <li><b><a href="index.php" >Tor Market</a></b></li>
            <li><a href="index.php">Home</a></li>
            <li><a href="usercp.php?addproduct">Add Product</a></li>
            <li><a href="usercp.php?orders">Orders <span style="color:#f26722"> (0)</span></a></li>
            <li><a href="usercp.php?changepassword" >change password</a></li>
            <li><a href="logout.php">Logout</a></li>
        </ul>
</div>
  
  <center>

    <div id="Products">
        
    <ul> 
                    <li>
                        <a href="index.php?product_id="><img src="imgs/paypal.com"/></a>
                        <br/>
                        <a href="index.php?product_id="></a>
                        <a href="index.php?product_id="><span style="color:#f26722;">Price : 0.15</span></a><br/>
                    </li>
                </ul> 
    </div>
   </center> 
    
    
<br/><br/><div style="clear:both;"></div>
    <div id="footer" >
        <center>
            <b>Coded by <a href="#">0x43rypt0n</a> </b>
        </center>
    </footer>
</body>
</html>

login.php
HTML: Скопировать в буфер обмена
Код:
<!DOCTYPE HTML>
<html lang="en">
    <head>
            <title>user login</title>
            <link rel="stylesheet" type="text/css" href="admin/includes/style/main.css?v=<?php echo time(); ?>" />
    </head>
<body>


    <div id="registerLoginTable"><center>
    <form action="login.php" method="post">
        <h1>Login</h1>
        <table cellpadding="0" cellspacing="0" border="0">
            <thead colspan="2">
            <tr><th colspan="2">
            </tr> </thead>
            <tbody>
                <tr><th>Username : </th><td><input type="text" name="username" required/></td></tr>
                <tr><th>Password : </th><td><input type="password" name="password" required/></td></tr>
            </tbody>
            <tfoot>
                <tr><td><button type="submit" name="login" >login</button></td> </tr>
            </tfoot>
        </table>
        </form>
    </center></div>
    <div id="footer">
        <center>
            <b>Coded by <a href="#">0x43rypt0n</a> </b>
        </center>
    </footer>
</body>
</html>

register.php
HTML: Скопировать в буфер обмена
Код:
<!DOCTYPE HTML>
<html lang="en">
    <head>
            <title>user register</title>
            <link rel="stylesheet" type="text/css" href="admin/includes/style/main.css?v=<?php echo time(); ?>" />
    </head>
<body>


    <div id="registerLoginTable"><center>
    <form action="register.php" method="post">
        <h1>Register</h1>
        <table cellpadding="0" cellspacing="0" border="0">
            <thead colspan="2">
            <tr><th colspan="2">

            </tr> </thead>
            <tbody>
                <tr><th>Username : </th><td><input type="text" name="username" required/></td></tr>
                <tr><th>Password : </th><td><input type="password" name="password" required/></td></tr>
                <tr><th>Confirm Password : </th><td><input type="password" name="password2" required/></td></tr>
            </tbody>
            <tfoot>
                <tr><td><button type="submit" name="register" >Register</button></td> </tr>
            </tfoot>
        </table>
        </form>
    </center></div>

</body>
</html>
usercp.php
HTML: Скопировать в буфер обмена
Код:
<!DOCTYPE HTML>
<html lang="en">
<head>
        <title>Home page </title>
        <link rel="stylesheet" type="text/css" href="admin/includes/style/main.css" />
</head>
<body>
        <div id="registerLoginTable"><center>
            <form action="usercp.php?addproduct" method="post" enctype="multipart/form-data">
                <h1>Product Details</h1>
                <table cellpadding="0" cellspacing="0" border="0">
                    <thead colspan="2">
                    <tr><th colspan="2">

                    </tr> </thead>
                    <tbody>
                    <tr><th>Product Name  : </th><td><input type="text" name="product_name" required/></td></tr>
                    <tr><th>Product Description  : </th><td><input type="text" name="product_desc" required/></td></tr>
                    <tr><th>Product Price In bitcoin : </th><td><input type="text" name="product_price" required/></td></tr>
                    <tr><th>Product Image : </th><td><input type="file" name="product_image" required/></td></tr>
            
                    </tbody>
                    <tfoot>
                        <tr><td><button type="submit" name="addproduct" >Add product</button></td> </tr>
                    </tfoot>
                </table>
                </form>
            </center></div>


<div id="registerLoginTable"><center>
<h1>Orders</h1>
<table cellpadding="0" cellspacing="0" border="0" class="orders">
    <thead colspan="2">
    <tbody>
        <tr>
            <th>Product Id</th>
            <th>Product Name</th>
            <th>Product Price </th>
            <th>Btc Address</th>
            <th>Payment Status</th>
        </tr>
        <?php $_products->getOrdersByUser();?>
    </tbody>
</table>
</center></div>
        



</body>
</html>

Now open your editor you can use any editor even notepad.exe but it is better to use ide I will suggest eclipse

Inside the db.sql.php define mysql connection data like host,user,pass,db
And create a new object from the mysqli class and pass the connection data check for the connection if it does not connect to the mysql server the exits with an error
On the top of the code, there is a if(!defined("FILE_ACCESS_PERMISSION"))
For now leave it as it will talk about it in the classes.php
PHP: Скопировать в буфер обмена
Код:
<?php
if(!defined("FILE_ACCESS_PERMISSION"))
{
    exit('Direct access to this file is not allowed ');
}


define("HOST","localhost");
define("DATABASE","tormarket");
define("DBUSER","root");
define("DBPASS","");

$conn = new mysqli(HOST,DBUSER,DBPASS,DATABASE);

if ($conn->connect_error) {
  exit("Connection failed: " . $conn->connect_error);
}
?>

For security reasons some of the php files should not get access directly from web browsers such as classes.php to disable the access to the direct access we have to check for the definition to do this will use the function Defined(“FILE_ACCESS_PERMISSION
”)
And if define is not available will exit(“”) the script
This will prevent anyone from accessing the file from the browser but this will also prevent us from including it in our php code so to fix this problem we have to define(“FILE_ACCESS_PERMISSION
”) in any php file will need to use or include the classes.php file
Open includes/php/classes.php make sure you write it on the top of the file before adding any include and after the session();

Now create a new class with the name secure This class is For securing the market files like who can add new products if the user logged in or Guest and who can pay the products if the user logged in
PHP: Скопировать в буфер обмена
Код:
if(!defined("FILE_ACCESS_PERMISSION"))
{
    exit('Direct access to this file is not allowed ');
}


class secure
{
    
    function __construct()
    {
        global $conn;
        $this->conn = $conn;
        if(isset($_SESSION['session']))
        {
            $this->session = $_SESSION['session'];
        }
      
    }
    function secureLoginRegisterPage()
    {
        if(isset($_SESSION['logedIn']) && $_SESSION['logedIn'] == true)
        {
            header("location: index.php");
        }
    }
    function SecureLogout()
    {
        if(!isset($_SESSION['logedIn']))
        {
            header("location: index.php");
        }
    }
    function SecurePages()
    {
        if(!isset($_SESSION['logedIn']))
        {
            header("location: login.php");
        }
    }
    function SecureAdminPages()
    {
        if($stmt = $this->conn->prepare("SELECT `usergroup` FROM `users` WHERE `session`=(?) "))
        {
            $stmt->bind_param('s',$this->session);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($usergroup);
            $stmt->fetch();
            
            if($usergroup == "1") // administrator
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    function IsUserLogedIn()
    {
        if(isset($_SESSION['logedIn']) && $_SESSION['logedIn'] == true)
        {   
            
            if($stmt = $this->conn->prepare("SELECT * FROM `users` WHERE `session`=(?) "))
            {
                $secure_session = strip_tags($this->session);
                $stmt->bind_param('s',$secure_session);
                $stmt->execute();
                $stmt->store_result();
                
                if($stmt->num_rows > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                return false;
            }
            
            // return true;
        }
        else
        {
            return false;
        }
    }

}

The first function constructor.
what is a constructor ? the constructor allows you to initialize class properties upon creation of the object. it's not a php tutorial but just in case you dont know php oop

Inside the function constructor we defined two variables global variable because the mysqli connection variable is outside the function we have defined it as global so we can use it inside the function and this global var should be defined inside every function but because we define it inside the constructor and store it in this->var so we can now use it any ware in any function inside the same class without needing to redefine it every time

Function secureLoginRegisterPage In this function we check if the user is logged in and the session is available and if the user tried to access the login or register page then we should directly redirect him to the Index.php th

Function SecureLogout In this function we again check the user status but this time we check if the user is not logged in and tried to access the logout.php we redirect him to the index.php

Keep in mind some php files can be accessed by Guests and users and some are only for registered users and some are only for admin like add product but the index.php which display all the available products in the market this page can be accessed from all type of users


Function SecureAdminPages
This function is for securing admin pages such as creating or adding new products so in case any user tries to access this page manually from the browser he will be redirected directly to index.php if the user is not in the admin groups the admin groups is number 1 and registered members usergoup number 2

Function IsUserLogedIn This function is very important and will be used in different ways in this project like navbar and adding products for the navbar if the user logged in then we can show the pages are visible only for logged in users like Orders , change password and logout and also will hide a pages are only visible to guest users like register and login

What the code is not like the other functions that we discussed there are a few changes and improvements added here like after checking if the user logged in then here we check if the existing session is available in the database or not and if the session is not available in the database then the user may try to hack the system so it returns false and the functions will not work
For processing these futures we use the function prepare from mysqli class this function is used to prepare sql statements to be executed the session is not passed directly to the function we use the function bind_param() to pass the session the s will change the question mark in the sql statement as an extra security you can add strip_tags Why its session? yes but when hackers try fuzzing the system they may also try to fuzz the session and they may try sql injection so for more security add strip_tags()

After binding the params execute the sql statement and finally store it so we can use mysql num rows to check for existing sessions if the num rows are equal to or less than Zero then the session does not exist if exists return false and the session is equal to 1 return true;

Now we have finished the first class lets create the class number 2

Creating a new class I name the class users inside this class will handle all the users actions like paying for products, registering and login

PHP: Скопировать в буфер обмена
Код:
class users
{
    
    public $user;
    public $pass;
    public $pass2;
    public $user_id;
    function __construct($user="",$pass="",$pass2="")  //default is disabled to be used in login
    {
        global $conn;
        $this->conn    =  $conn;
        $this->user    =  $user;
        $this->pass    =  $pass;
        $this->pass2   =  $pass2;
        $this->user_id;
        if(isset($_SESSION['session']))
        {
            $this->session = $_SESSION['session'];
        }
    }
    function Register()
    {
        if(empty($this->user) || empty($this->pass) || empty($this->pass2) )
        {
            echo "<h1 class=\"msgregisterfaild\">Please complete the fields  </h1></th>";
        }
        else
        {
            $this->user  = strip_tags($this->user);
            if($stmt = $this->conn->prepare('SELECT * FROM `users` WHERE `username` = (?)'))
            {
      
                $stmt->bind_param('s', $this->user);
                $stmt->execute();
                $stmt->store_result();
                if($stmt->num_rows  > 0)
                {
                    echo "<h1 class=\"msgregisterfaild\">Username already exist </h1>";
                }
                else
                {   
                    if($this->pass == $this->pass2)
                    {
                        
                        $this->pass  = password_hash($this->pass, PASSWORD_DEFAULT);
                        // $this->pass2 = password_hash($this->pass2, PASSWORD_DEFAULT);
                        
                        $_time      = date("h:i:s");
                        $_date      = date("20y-m-d");
                        $_time_date = $_date." ".$_time;
                        $_SESSION['logedIn'] = TRUE;
                        $session = $_SESSION['session'] = md5(rand(1000,9999));
                        if($stmt = $this->conn->prepare("INSERT INTO `users` ( `username`, `password`,`session`, `registerydate`, `lastonline`, `usergroup`) VALUES ( ?, ?, ?, ?, ?, ?)"))
                        {
                            $usergroup = '2';
                            $stmt->bind_param("ssssss", $this->user, $this->pass, $session , $_time_date,$_time_date,$usergroup);
                            $stmt->execute();
                            echo "<h1 class=\"msgregistersuccess\">Registration Success </h1>";
                            echo "<meta http-equiv=\"Refresh\" content=\"2; url='index.php'\" />";    
                            $stmt->close();
                        }
                        else
                        {
                            echo "<h1 class=\"msgregisterfaild\">Password and confirm password does not match</h1>";
                        }
                    }
                    else
                    {
                        echo "<h1 class=\"msgregisterfaild\">Password and confirm password does not match</h1>";
                    }
                }
            }
            else {
                echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
            }
        
        }
    }
    function Login()
    {
        $this->user  = strip_tags($this->user);
        if($stmt = $this->conn->prepare('SELECT `uid`,`username`,`password` FROM `users` WHERE `username` = (?)'))
        {
            $stmt->bind_param('s', $this->user);
            $stmt->execute();
            $stmt->store_result();
      
            if($stmt->num_rows > 0)
            {
            
                $stmt->bind_result($uid,$username,$password);
                $stmt->fetch();
                if (password_verify($this->pass, $password)) 
                {
                    $_SESSION['logedIn'] = TRUE;
                    $session = $_SESSION['session'] = md5(rand(1000,9999));
                    
                    if($dol = $this->conn->prepare("UPDATE `users` SET `session`='$session' WHERE `uid` = (?)") )
                    {
                        $dol->bind_param('s', $uid);
                        $dol->execute();
                        // $dol->store_result();
                        $dol->close();
                        echo "<h1 class=\"msgregistersuccess\">Login Success </h1>";
                        echo "<meta http-equiv=\"Refresh\" content=\"2; url='index.php'\" />";   
                        ?>
                        
                        <?php
           
                    }
                    else
                    {
                        echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                    }
                } 
                else 
                {
                    echo "<h1 class=\"msgregisterfaild\">Incorrect username and/or password! </h1>";
                }
            } 
            else 
            {
                echo "<h1 class=\"msgregisterfaild\">Incorrect username and/or password! </h1>";
            }
            $stmt->close();
        }
        else
        {
            echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
        }
    }
    function changepassword()
    {
        if(empty($this->pass) || empty($this->pass2) )
        {
            echo "<h1 class=\"msgregisterfaild\">Please complete the fields  </h1></th>";
        }
        else
        {
            if($stmt = $this->conn->prepare('SELECT `uid` FROM `users` WHERE `uid` = (?)'))
            {
                $this->user_id = $this->getUserId();
                $stmt->bind_param('s', $this->user_id);
                $stmt->execute();
                $stmt->store_result();
 
                 if($stmt->num_rows  > 0)
                 {
                    if($this->pass == $this->pass2)
                    {
                        $this->pass  = password_hash($this->pass, PASSWORD_DEFAULT);
                        if($squ = $this->conn->prepare("UPDATE `users` SET `password` = '$this->pass' WHERE `uid` = (?) "))
                        {
                            $squ->bind_param('s',$this->user_id );
                            $squ->execute();
                            echo "<h1 class=\"msgregistersuccess\">  Password updated successfully </h1>";
                            echo "<meta http-equiv=\"Refresh\" content=\"2; url='index.php'\" />";    
                            $stmt->close();
                        }else
                        {
                            echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                        }
                    }
                    else
                    {
                        echo "<h1 class=\"msgregisterfaild\">  Passwords does not matchs </h1>";
                    }
                 }
                 else
                 {   
                    echo "<h1 class=\"msgregisterfaild\">Uid does not exists </h1>";
                 } 
            }  
         }
    }
    function Logout()
    {
        unset($_SESSION["logedIn"]);
        session_destroy();
        header("location: login.php");
    }
    function getUserId()
    {
        if(isset($_SESSION['logedIn']) && $_SESSION['logedIn'] == true)
        {   
            
            if($stmt = $this->conn->prepare("SELECT `uid` FROM `users` WHERE `session`=(?) "))
            {
                $stmt->bind_param('s',$this->session);
                $stmt->execute();
                $stmt->store_result();
                
                if($stmt->num_rows > 0)
                {
                    $stmt->bind_result($uid);
                    $stmt->fetch();
                    $this->user_id = $uid;
                    return $this->user_id;
                }
                else
                {
                    return "0";
                }
            }
            else
            {
                echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                return false;
            }
            
            return true;
        }
        else
        {
            return false;
        }
    }
}

Create 4 public variables the pass2 variable will only be used in the register function to compare it with the pass variable to check if the user has remembered what he entered for the registration the user_id variable will not be used in registration or login but still, this is a very important variable will use it in more than 1 function like CountNewOrders PayProduct getOrdersByUser
in the constructor will leave it empty but will store the user ID inside it in the function getUserId
And check if the session exists store the session inside this->session variable

In the function Register we check if the inputs are empty if empty display an error else if not empty add strip_tags() function to inputted username and use the mysqli::prepare function to check if the username is already registered by another user or still available if registered
Display the error message username already exists if not registered to check the password and password 2 if they match if not match display the error message passwords do not match if matches now hash the password using the function password_hash we only hash 1 password not both and create the registration date add the sessions final step store the user in database with the random session display success message and redirect the user to index.php and close the connection to database this function is finished


The Login function
Same as we did in the register but this time we are checking if the username is in the database then will check for the password and if the imputed password matches the password stored in the database then set the session and update the session in the database to verify the password we used the function password_verify if the password does not match show error message username or password does not match in both username not found and password does not match this will the system from brute force attack

The function changepassword
Here in this function we allow the users to change their password but we need first to secure it so we first check if the 2 passwords are equal this makes sure the user remembers the password he entered and then checks if the uid passed is already in the database if yes update the old password with new hashed password Where uid or userid is equal to the current logged in user id this step is an optional cause we already make securing pages steps

The logout function is where we delete the current session and update the database and set the session in the database empty

The function getUserId here is the function that we talked before about it this function is an important function using this function can retrieve the id of the current logged in user so we can use it when we retrieve the Orders purchased by the user, pay products by the user and CountNewOrders functions The class 2 is finished now its

The class number 3 creates a new class this class will handle everything about order count , pay products and add products display all and display a single product chosen by the user so I decided to name the class ProductSystem
PHP: Скопировать в буфер обмена
Код:
class ProductSystem
{
    public $product_id;
    public  $user_id ;
    function __construct()
    {
        global $conn;
        $this->conn = $conn;
        $_user = new users();
        $this->user_id = $_user->getUserId();
        if(isset($_GET["product_id"]))
        {
            $this->product_id =   $_GET["product_id"];
        }
        if(isset($_SESSION['session']))
        {
            $this->session = $_SESSION['session'];
        }
       
    }
    function fetch_all_products()
    {
        if($stmt = $this->conn->prepare('SELECT `product_id`,`product_name`,`product_image`,`product_price` FROM `products` ORDER BY `product_id` DESC'))
        {
            
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($product_id,$product_name,$product_image,$product_price);
            while($stmt->fetch())
            {
                ?>
                <ul> 
                    <li>
                        <a href="index.php?product_id=<?php echo $product_id; ?>"><img src="<?php echo $product_image; ?>"/></a>
                        <br/>
                        <a href="index.php?product_id=<?php echo $product_id; ?>"><?php echo $product_name; ?> </a>
                        <a href="index.php?product_id=<?php echo $product_id; ?>"><span style="color:#f26722;">Price : <?php echo $product_price; ?></span></a><br/>
                    </li>
                </ul> 
                <?php
            }
            $stmt->close();
        }
    }
    function getProductData()
    {
        if (filter_var($this->product_id, FILTER_VALIDATE_INT) == false)
        {
            echo "<h1 class=\"msgregisterfaild\" style='max-width:200px;'>Wrong Product id  </h1>";
        }
        else
        {
            
            if(isset($_POST["buy"]))
            {   
                $_secure = new secure();
                if($_secure->IsUserLogedIn() == false)
                {
                    echo "<h1 class=\"msgregisterfaild\" style='max-width:200px;'>  Please Login first to buy products  </h1>";
                }
                else
                {
                    $this->PayProduct();
                }
            }
        
            if($stmt = $this->conn->prepare("SELECT `product_id`,`product_name`,`product_description`,`product_image`,`product_price` FROM `products` WHERE `product_id`=(?)"))
            {
                $stmt->bind_param('s',$this->product_id);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($product_id ,$product_name,$product_description,$product_image,$product_price);
                $stmt->fetch()
                
                ?>
                <form action="index.php?product_id=<?php echo $product_id; ?>" method="post">
                <ul> 
                    <li>
                        <img src="<?php echo $product_image; ?>"/>
                        <br/><br/>
                        <h3 ><?php echo $product_name."</h3><br/><b>".$product_description; ?> </b>
                        <b><?php echo $product_price; ?><b><br/><br/>
                        <button type="submit" name="buy">Buy now </submit>
                      
                    </li>
                </ul> <br/><br/>
                </form>
                <?php                
            }
        }
    }
    function getProductName()
    {
        if (filter_var($this->product_id, FILTER_VALIDATE_INT) == false)
        {
            exit( "<h1 class=\"msgregisterfaild\" style='max-width:200px;'>Wrong Product id  </h1>");
        }
        else
        {
            if($stmt = $this->conn->prepare("SELECT `product_id`,`product_name` FROM `products` WHERE `product_id`=(?)"))
            {
                $stmt->bind_param('s',$this->product_id);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($product_id ,$product_name);
                $stmt->fetch();
                return $product_name;
            }
            else
            {
                echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
            }
        }
    }
    function getName($n) 
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
    
        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, strlen($characters) - 1);
            $randomString .= $characters[$index];
        }
 
        return $randomString;
    }
    function Add_New_Product()
    {
        $_secure = new secure();
        if($_secure->IsUserLogedIn() == false)
        {
            echo "<h1 class=\"msgregisterfaild\" style='max-width:200px;'>  Please Login first to buy products  </h1>";
        }
        else
        {
            if($stmt = $this->conn->prepare("SELECT `usergroup` FROM `users` WHERE `session`=(?) "))
            {
                $stmt->bind_param('s',$this->session);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($usergroup);
                $stmt->fetch();
                
                if($usergroup == "1") // administrator
                {
                                    
                        $this->product_name  = strip_tags($_POST["product_name"]);
                        $this->product_desc  = strip_tags($_POST["product_desc"]);
                        $this->product_price = strip_tags($_POST["product_price"]);

                        if(filesize($_FILES["product_image"]["tmp_name"]) > 3145728)
                        {
                            echo "<h1 class=\"msgregisterfaild\">The file is to large</h1>";
                        }
                        else
                        {
                            $img_info = finfo_open(FILEINFO_MIME_TYPE);
                            $img_type = finfo_file($img_info, $_FILES["product_image"]["tmp_name"]);
                            $allowedTypes = [
                                'image/png' => 'png',
                                'image/jpeg' => 'jpg'
                            ];
                            if(in_array($img_type, array_keys($allowedTypes))) 
                            {
                                    $random_image_name  = $this->getName(10);
                                    $product_image      = basename($_FILES["product_image"]["name"]);
                                    $explode_image_name = explode(".",$product_image);
                            
                                    $product_image_extention =  $explode_image_name[1];
                                    $image_path = "imgs/".$random_image_name.".".$product_image_extention;
                                    if(move_uploaded_file($_FILES["product_image"]["tmp_name"], $image_path)) 
                                    {
                                        if($stmt = $this->conn->prepare("INSERT INTO `products` ( `product_name`, `product_description`, `product_image`, `product_price`) VALUES (?, ?, ?, ?); "))
                                        {
                    
                                            $stmt->bind_param('ssss',$this->product_name,$this->product_desc, $image_path,$this->product_price);
                    
                                            $stmt->execute();
                                            $stmt->close();
                                            echo "<h1 class=\"msgregistersuccess\">Product added successfully</h1>";
                                        }
                                        else
                                        {
                                            echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                                        }
                                    }
                                    
                            }
                            else
                            {
                                echo "<h1 class=\"msgregisterfaild\">The file/image type are not allowed</h1>";
                            }
                        }
                }
                else
                {
                    echo "<h1 class=\"msgregisterfaild\">You dont have permission to do this action                    </h1>";
                }
            }
            else
            {
                echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
            }
            
        }

    }
    function getOrdersByUser()
    {
        if( $stmt = $this->conn->prepare("SELECT `uid`,`btc_receiver_address`,`product_id`,`deal_status` FROM `crypto_payment_system` WHERE `uid`=(?)  "))
        {
            
            $uid = $this->user_id;
            $stmt->bind_param("s",$uid);
            $stmt->execute();
            $stmt->store_result();
            if($stmt->num_rows > 0)
            {
                $stmt->bind_result($uid,$btc_receiver_address,$product_id,$deal_status);
                
                while($stmt->fetch())
                {
                  
                    if($stmts = $this->conn->prepare("SELECT `product_id`,`product_name`,`product_price` FROM `products` WHERE `product_id`=(?) ORDER BY `product_id` DESC "))
                    {
                        $stmts->bind_param("s",$product_id);
                        $stmts->bind_result($product_id,$product_name,$product_price);
                        $stmts->execute();
                        $stmts->store_result();
                        while($stmts->fetch())
                        {
                  
                    ?>
                        <tr>
                        <th><?php echo $product_id; ?></th>
                        <th><?php echo $product_name; ?></th>
                        <th><?php echo $product_price; ?></th>
                        <th><?php echo $btc_receiver_address; ?></th>
                        <th>
                            <?php 
                                if($deal_status == "initialized")
                                {
                                    echo "Deal not payed yet";
                                }
                                else if($deal_status == "payed")
                                {
                                    echo "Deal payed but not confirmed yet";
                                }
                                else if($deal_status == "confirmed")
                                {
                                    echo "Deal payed  and confirmed ";
                                }
                            ?>
                        </th>
                        </tr>
                        <?php 
                       }
                    }
                    else
                    {
                        echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                    }  
                }
                $stmt->close();
            }
        }
        else
        {
            echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
        }
        ?>
         
        <?php 
    }
    function CountNewOrders()
    {
        if($stmt = $this->conn->prepare("SELECT `uid` FROM `crypto_payment_system` WHERE `uid`=(?) AND `deal_status`=(?)  "))
        {
            
            $uid = $this->user_id;
            $deal_status = "initialized";
            $stmt->bind_param("ss",$uid,$deal_status);
            $stmt->execute();
            $stmt->store_result();
            return $stmt->num_rows ;
        }
        else
        {
            echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
        }
    }

    function PayProduct()
    {
        $product_id = $_GET["product_id"];
        if (filter_var($product_id, FILTER_VALIDATE_INT) == false)
        {
            echo "<h1 class=\"msgregisterfaild\" style='max-width:200px;'>Wrong Product id  </h1>";
        }
        else
        {
            if($stmt = $this->conn->prepare("INSERT INTO `crypto_payment_system` (`deal_id`, `uid`, `btc_receiver_address`,  `product_id`, `deal_status`) VALUES (NULL,?,?,?,?) "))
            {   
                $_Payment_orders_system = new Payment_orders_system();
                $btc_address = $_Payment_orders_system->GenerateNewBitcoinAddress();
                $uid =$this->user_id;
                $deal_status = "initialized";
                $stmt->bind_param("ssss",$uid,$btc_address,$product_id,$deal_status);
                $stmt->execute();
                $stmt->close();
            }
            else
            {
                echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
            }
        }
    }
   
}

As we did before defining the public variables and initializing them in the contractor function but this time we used the function getuserid that we created in the class number 2 which is the user class one more thing is checking if the url has a product_id if yes has a value store the product id in variable $this->product_id


Fetch_all_products this function retrieves all available products in the database and displays them to retrieve the products in the first place we used the prepare function and added the SELECT statements but this time we did not use bind_param because there are no inputs or Select from Where but after executing the query and store it this time we used bind_results which will get the results from the database and we passed the data we need to retrieve as $variable one thing here I want to mention every single column you want to retrieve should be described in the mysql query statement so you can remove or add columns but when you remove or add columns on mysql statement you should do the same changes on bind_results

Finally we used the function $stmt->fetch() if you used the function without a loop it will retrieve the last added data so to retrieve them all should be added inside a while loop as we did in the code
The html section is available in index.php above I just copied the ul list and will make the required changes to the index.php when we finish the classes when we finish we close the connection


Function getProductData when we display all products the User needs to choose 1 product to view all data about it like diction or even pay it so to retrieve data for 1 product will do this using this function
This function is very similar to the function fetch_all_products but here we are retrieving data from mysql by id where `id`=$_get[product_id] and because of that because we are adding input from the user we need to secure this input or will face an Sql injection problem and the system will be vulnerable to hackers
Good thing php offers for us a ready to use function to filter data the function is
filter_var($this->product_id, FILTER_VALIDATE_INT) The first param is the data passed by the user and the second parameter is a type of data we need to filter in this case we are receiving product id this means the data type is an integer and we should only allow integers value to be passed to the mysql statement so we passed FILTER_VALIDATE_INT
So if this function fails it returns false and displays an error Wrong Product id and if returns true means the passed value is an integer then again we used mysqli::prepare to select the data where the database product id is equal to the id are passed by the user
And display it and add a form with the button pay so the user when clicks it will be added to his orders
But what if a guest tries to pay a product in case a guest clicks the pay button he will see please login message this thing is done by using the function $_secure->IsUserLogedIn()
This function we create it in class 2 user class
Okay so now if a registered user clicks pay the function pay will be invoked we have not write it yet but will do this Soon

Function getProductName
This function only retrieves the name of the product and the reason for creating this function is when a user chooses a product we need to change the title of the page to the product they are chosen by the user so we created this function with the same filters same sql query statements

Function Add_New_Product
The add product function from its name you can recognize is for adding new products first thing we did we check if the user logged in if not logged in displayed the error message Please Login first to buy products if logged in then check the user permissions if user are in administrator usergroups then allow the user to create or add new product if not administrator display error
For image upload we need to make the image name is random to fix the image name duplicated problem or the image will not be uploaded and the add product function will fail to fix this problem we can get generate a random number and use the function md5 to hash the random number and then upload the image and if the image uploaded success insert the product to the database

Function getOrdersByUser This function will get all the orders from the database but by the uid or the current logged in user id and retrieve the btc address and the order details so the user can send the bitcoin every order will have a different btc address so every order will have a unique btc address
The order status when paid by the user is initialized so this means the order generated but not paid and confirmed yet
And when the order gets paid and is not confirmed the status will be changed to payed
After the order is confirmed the status will be changed to confirmed

Function CountNewOrders in the navbar we need to display the available new orders he paid
So we select the orders by the deal_status initialized and user_id equal to the current logged in user id

Function PayProduct
In this function we do the pay function which we get the product id the user chooses to pay and add it to the user orders and add by the userid so the order if you dont add the user id you will add the product to all market members
Inside this function we need to generate a new btc address we can do this using the function
GenerateNewBitcoinAddress from class Payment_orders_system this class has not been created yet will add it when we finish now from this class

So the class number 4 is finally finished now the class number 5 and this will be the last class
PHP: Скопировать в буфер обмена
Код:
class Payment_orders_system
{
    public  $rpchost;
    public  $rpcport;
    public  $rpcuser;
    public  $rpcpass;
    public  $rpcurl;
    function __construct()
    {
        global $conn;
        $this->conn = $conn;
        $this->rpchost = "127.0.0.1";
        $this->rpcport = "8888";
        $this->rpcuser = "user";
        $this->rpcpass = "1234";
        $this->rpcurl = "http://".$this->rpcuser.":".$this->rpcpass."@".$this->rpchost.":".$this->rpcport;
    }
    function RPC_CONNECT($method,array $params=[])
    {
        $this->data = [
            "id" => "curltext",
            "method" => $this->method,
            "params" => $params,
        ];
        $this->data = json_encode($this->data);
        //var_dump($this->data);
        // echo "\n\n\n";
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_URL, $this->rpcurl );
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_POST, 1);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->data);
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, ["Content-type: application/json"]);
        $this->response = curl_exec($this->ch);
        curl_close($this->ch);
        return json_decode($this->response, true)["result"];
    }
    function GenerateNewBitcoinAddress()
    {
        $this->method = "createnewaddress";
        return  $this->RPC_CONNECT($this->method);
    }
    function GetBitcoinAddressBalance($BitcoinAddress)
    {
        $this->method = "getaddressbalance";
        $param  = ["$BitcoinAddress"];
        return $this->RPC_CONNECT($this->method,$param);
    }
    function CheckTransactionsStatus()
    {
        if($stmt = $this->conn->prepare("SELECT `deal_id`,`uid`,`product_id`,`btc_receiver_address`,`deal_status` FROM `crypto_payment_system` WHERE deal_status != (?)"))
        {
            $dealstatus = "confirmed";
            $stmt->bind_param('s',$dealstatus);
            $stmt->execute();
            $stmt->store_result();
            
          
            if($stmt->num_rows > 0)
            {
                // echo $stmt->num_rows;
                $stmt->bind_result($deal_id,$uid,$product_id,$btc_receiver_address,$deal_status);
                while($stmt->fetch())
                {
                    if($q = $this->conn->prepare("SELECT `product_id`,`product_price` FROM `products` WHERE `product_id`=(?) "))
                    {
                        $q->bind_param('s',$product_id);
                       
                        $q->execute();
                        $q->store_result();
                      
                        if($q->num_rows > 0)
                        {
                            $q->bind_result($product_id,$product_price);
                            $q->fetch();
                            $balance = $this->GetBitcoinAddressBalance($btc_receiver_address);
                            echo "Address : ".$btc_receiver_address;  
                            echo "<br/>";
                            echo "product_price : ".$product_price;
                            echo "<br/>";
                            echo "Confirmed : ".$confirmed = $balance["confirmed"];
                            echo "<Br/>";
                            echo "UnConfirmed : ".$Unconfirmed = $balance["unconfirmed"];
                            echo "<Br/>";
                            if($balance["unconfirmed"] == 0 && $balance["confirmed"] == 0)
                            {
                                echo "Deal not payed yet<br/>";
                                continue;
                            }
                            else  
                            {
                                    // echo "pid : $product_id";
                                    // payment done but not confirmed
                                    if($balance["unconfirmed"] > (float)0) // check if there any payment are made
                                    {
                                      
                                        if($product_price <= $balance["unconfirmed"])
                                        {
                                           
                                            if($squ = $this->conn->prepare("UPDATE `crypto_payment_system` SET `deal_status` = 'payed' WHERE `deal_id` = (?) "))
                                            {
                                                $squ->bind_param('s',$deal_id);
                                                $squ->execute();
                                                echo "Deal payed but not confirmed yet<br/><Br/><Br/>";
                                                $squ->close();
                                            }
                                        }                                        
                                    }
                                    else
                                    {
                                        // payment payed and confirmed
                                        if($product_price <= $balance["confirmed"]  )
                                        {
                                           if($squ = $this->conn->prepare( "UPDATE `crypto_payment_system` SET `deal_status` = 'confirmed' WHERE `deal_id` = (?) "));
                                           {
                                                $squ->bind_param('s',$deal_id);
                                                $squ->execute();
                                                echo "Deal payed  and confirmed <br/><Br/><Br/>";
                                                $squ->close();
                                           }
                                        }
                                    }
                            } 
                        }
                        $q->close();
                    }
                    else
                    {
                        echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
                    }
                }
                $stmt->close();
            }
        }
        else
        {
            echo "<h1 class=\"msgregisterfaild\">".$this->conn->error."</h1>";
        }

   
    }
}

Create a new class this class will handle the payments and check the transaction status initialized, paid, and confirmed and if the payment changed will update the database
So I named the class as Payment_orders_system

The first thing we need to do is initialize the rpc server connect details that we created at the start of this tutorial

In the RPC_CONNECT function will initialize the curl and rpc data
The rpc server receives json and responds with also json there are 2 params that the servers need to respond to us the first one is the method
The method means get_blance , generatenew address , getaddressbalance

Different between get_blance and getaddressblanace is that getbalance will retrieve the whole wallet balance so this will not be used in the system because we need to retrieve the balance for the address are generated for the user so will use the method getaddressbalance

The parameter param by default should be an empty array but when we use some methods such as getaddressbalance will use it to send the generated btc address and the server will respond with the address balance not the wallet wallet balance

After converting the data from array to json type and sending the command to the server it replays with the start key result to parse the json will use the json_decode function and get the result key finally the data that received from the server will be returned

Function GenerateNewBitcoinAddress
In this function we pass the method createnewaddress to the function RPC_CONNECT
And the RPC_CONNECT function will replay with the newly generated address

This address or this function will be used when the function PayProduct invoked

Function GetBitcoinAddressBalance
The function is responsible for retrieving the balance of a specific address
This function will be used in the function CheckTransactionsStatus

Function CheckTransactionsStatus
Here we got all transactions or deals in the database with any deal_status other than confirmed so if the transaction is not confirmed will get the address of the order from the database and use the function GetBitcoinAddressBalance to get the balance and then check if the unconfirmed balance and confirmed balance are equal to zero this means the payment not paid yet
But if the balance is greater then we check if the unconfirmed balance is equal to or greater than the product price if less than the payment will be ignored! to protect the system from attacks
For example, a product pierced is 50$ and the user sends 25$ in this way we protect ourselves from losing money then we skip the transaction

If the price is greater or equal product price then will update the database and set the
Deal_status paid This means the payment is paid but not confirmed on the blockchain network

Else if the confirmed balance is equal to or greater than the product price then update the database and set the deal_status confirmed and now the payment is done and the administrator can send the product to the user

OK Close the classes file because we finished everything in this file


Open the register.php in your editor and on the top before any html code add this code
PHP: Скопировать в буфер обмена
Код:
<?php 
//4
session_start();
define("FILE_ACCESS_PERMISSION",true);
require_once("includes/php/classes.php");
require_once('includes/php/db.sql.php');
$secure = new secure();
$secure->secureLoginRegisterPage();

?>
<!DOCTYPE HTML>
<html lang="en">
    <head>
            <title>user register</title>
            <link rel="stylesheet" type="text/css" href="includes/style/main.css?v=<?php echo time(); ?>" />
    </head>
<body>
<?php    require_once('includes/php/navbar.php'); ?>
    <div id="registerLoginTable"><center>
    <form action="register.php" method="post">
        <h1>Register</h1>
        <table cellpadding="0" cellspacing="0" border="0">
            <thead colspan="2">
            <tr><th colspan="2">
                <?php 
                       if(isset($_POST["register"]))
                       {
                            $_users = new users($_POST["username"],$_POST["password"],$_POST["password2"]);
                            $_users->register();
                          
                       }
                ?>
            </tr> </thead>
            <tbody>
                <tr><th>Username : </th><td><input type="text" name="username" required/></td></tr>
                <tr><th>Password : </th><td><input type="password" name="password" required/></td></tr>
                <tr><th>Confirm Password : </th><td><input type="password" name="password2" required/></td></tr>
            </tbody>
            <tfoot>
                <tr><td><button type="submit" name="register" >Register</button></td> </tr>
            </tfoot>
        </table>
        </form>
    </center></div>
    <div id="footer">
        <center>
            <b>Coded by <a href="#">0x43rypt0n</a> </b>
        </center>
    </footer>
</body>
</html>
So we start the session define FILE_ACCESS_PERMISSION before including the classes.php file so we can use it to include the classes.php and db.sql.php

Create a new object from the class secure and use the function secureLoginRegisterPage

After the html body tag remove the navbar and add it to the navbar.php open the navbar.php
File and we need to make some changes like hide and show some pages are only be shown for registered users and some of them for admins like adding new products so we use the function $secure->IsUserLogedIn() from class secure if the user not registered show login and register page If the user registers hide the login and register page and show orders, change password, logout and inside the if we add other if to check if the user is admin and if the user is admin show the page add product also there are 1 page shown for all users type like index.php and the logo of the market
Inside the if statement on the order link we used the function CountNewOrders inherited from the class ProductSystem
PHP: Скопировать в буфер обмена
Код:
<?php 
if(!defined("FILE_ACCESS_PERMISSION"))
{
    exit('Direct access to this file is not allowed ');
}
    ?>
        <div id="nav">
        <ul>
            <li><b><a href="index.php" >Tor Market</a></b></li>
            <li><a href="index.php">Home</a></li>
            <?php 
                if($secure->IsUserLogedIn() == false)
                {
                    ?>
                        <li><a href="register.php">Register</a></li>
                        <li><a href="login.php">Login</a></li>
                    <?php 
                }
                else if($secure->IsUserLogedIn() == true)
                {
                    $_products = new ProductSystem();
                    //CountNewOrders
                    ?>
                        <li><a href="usercp.php?addproduct">Add Product</a></li>
                        <li><a href="usercp.php?orders">Orders <span style="color:#f26722"> (<?php echo $_products->CountNewOrders(); ?>)</span></a></li>
                        <li><a href="usercp.php?changepassword" >change password</a></li>
                        <li><a href="logout.php">Logout</a></li>
                    <?php 
                }
            ?>
        </ul>
    </div>
    <?php
?>

Now the navbar.php is finished we can now move back to register to php also you can now remove the navbar from all pages and include it from the navbar.php

Now in the file register.php in the table create a new object from the class users and invoke the function register and pass all the inputs this now will make the registration form are ready and new users can be registered
Same thing we need to make in the login.php but this time after creating a new instance from the class users add the function login and then pass the inputs needed like username and password
PHP: Скопировать в буфер обмена
Код:
<?php 
session_start();
define("FILE_ACCESS_PERMISSION",true);
require_once("includes/php/classes.php");
require_once('includes/php/db.sql.php');
$secure = new secure();
$secure->secureLoginRegisterPage();



?>
<!DOCTYPE HTML>
<html lang="en">
    <head>
            <title>user login</title>
            <link rel="stylesheet" type="text/css" href="includes/style/main.css?v=<?php echo time(); ?>" />
    </head>
<body>
<?php   require_once('includes/php/navbar.php');?>

    <div id="registerLoginTable"><center>
    <form action="login.php" method="post">
        <h1>Login</h1>
        <table cellpadding="0" cellspacing="0" border="0">
            <thead colspan="2">
            <tr><th colspan="2">
                <?php 
                       if(isset($_POST["login"]))
                       {
                            $_users = new users($_POST["username"],$_POST["password"]);
                            $_users->login();
                       }
                ?>
            </tr> </thead>
            <tbody>
                <tr><th>Username : </th><td><input type="text" name="username" required/></td></tr>
                <tr><th>Password : </th><td><input type="password" name="password" required/></td></tr>
            </tbody>
            <tfoot>
                <tr><td><button type="submit" name="login" >login</button></td> </tr>
            </tfoot>
        </table>
        </form>
    </center></div>
    <div id="footer">
        <center>
            <b>Coded by <a href="#">0x43rypt0n</a> </b>
        </center>
    </footer>
</body>
</html>

Close all opened files and open logout.php create a new instance from the user class and use the logout function this page will run every time a user clicks logout on the navbar and unset the session
PHP: Скопировать в буфер обмена
logout.php

PHP: Скопировать в буфер обмена
Код:
<?php 
session_start();
define("FILE_ACCESS_PERMISSION",true);
require_once("includes/php/classes.php");
require_once('includes/php/db.sql.php');
$secure = new secure();
// $secure->SecurePages();



?>
<!DOCTYPE HTML>
<html lang="en">
    <head>  
        <?php 
          $_products = new ProductSystem();
          if(isset($_GET["product_id"]))
          {
            echo "<title>Product |   ".$_products->getProductName()." </title>";
          }
          else
          {
            echo "<title>Products</title>";
          }        
        ?>
            
            <link rel="stylesheet" type="text/css" href="includes/style/main.css?v=<?php echo time(); ?>" />
    </head>
<body>


<?php  
 require_once('includes/php/navbar.php');
      
    ?>
  
  <center>
    <?php
        if(isset($_GET["product_id"]))
        {
            ?>
              <div id="display_product">
                <?php 
                    $_products->getProductData();
                ?>
                </div>
            <?php 
        }
        else
        { 
    ?>
    <div id="Products">
        
        <?php   $_products->fetch_all_products(); ?>
    </div>
    <?php      
        }
    ?></center> 
    
    
<br/><br/><div style="clear:both;"></div>
    <div id="footer" >
        <center>
            <b>Coded by <a href="#">0x43rypt0n</a> </b>
        </center>
    </footer>
</body>
</html>
The index.php has 2 objectives 1 to display all the products from the database by retrieving them from the database using the function fetch_all_products from the class ProductSystem

And the second job is to display 1 product are chosen by the user when he clicks on the product and this will hide All products and display the the product details and pay button this option shows and runs when a product_id is detected in the url
The title is dynamic, not static what do I mean? I mean if the product shows all products this will display the market name as the title but if the target chooses a product the title will be changed to the market name and product name the product name retrieved by the function getProductName

There are 2 files left on the usercp.php page and the checktransactions.php file this file will not be a direct access file or options for users or admin
This file should run every 5 minutes automatically to check the available payments status and check the transactions paid or not using the function CheckTransactionsStatus from class Payment_orders_system and to make the file run automatically we need to add it to the crontab or cronjob so everything in the system will be automatic and does not require the administrator to update it

checktransactions.php
PHP: Скопировать в буфер обмена
Код:
<?php 
session_start();
define("FILE_ACCESS_PERMISSION",true);
require_once("includes/php/classes.php");
require_once('includes/php/db.sql.php');
$_Payment_orders_system = new Payment_orders_system();
$_Payment_orders_system->CheckTransactionsStatus();             
?>




Usercp.php
PHP: Скопировать в буфер обмена
Код:
<?php 
session_start();
define("FILE_ACCESS_PERMISSION",true);
require_once("includes/php/classes.php");
require_once('includes/php/db.sql.php');

$secure = new secure();
if($secure->IsUserLogedIn() == false)
{
    header("location: login.php");
}
// $secure->SecurePages();



?>
<!DOCTYPE HTML>
<html lang="en">
    <head>
            <title>Home page </title>
            <link rel="stylesheet" type="text/css" href="includes/style/main.css?v=<?php echo time(); ?>" />
    </head>
<body>
<?php   
require_once('includes/php/navbar.php');
    $_products = new ProductSystem();
    if(isset($_GET["addproduct"]))
    {
        if($secure->SecureAdminPages() == false)
        {
            header("location: index.php");
        }
        ?>
            <div id="registerLoginTable"><center>
                <form action="usercp.php?addproduct" method="post" enctype="multipart/form-data">
                    <h1>Product Details</h1>
                    <table cellpadding="0" cellspacing="0" border="0">
                        <thead colspan="2">
                        <tr><th colspan="2">
                        <?php   
                            if(isset($_POST["addproduct"]))
                            {
                                $_products->Add_New_Product();
                            }
                        ?>
                        <!-- <h1 class="msgregistersuccess">Add new product</h1></th> -->
                        </tr> </thead>
                        <tbody>
                        <tr><th>Product Name  : </th><td><input type="text" name="product_name" required/></td></tr>
                        <tr><th>Product Description  : </th><td><input type="text" name="product_desc" required/></td></tr>
                        <tr><th>Product Price In bitcoin : </th><td><input type="text" name="product_price" required/></td></tr>
                        <tr><th>Product Image : </th><td><input type="file" name="product_image" required/></td></tr>
                
                        </tbody>
                        <tfoot>
                            <tr><td><button type="submit" name="addproduct" >Add product</button></td> </tr>
                        </tfoot>
                    </table>
                    </form>
                </center></div>

    <?php
    }
    else if(isset($_GET["orders"]))
    {
        
        ?>
    <div id="registerLoginTable"><center>
    
    <h1>Orders</h1>
    <table cellpadding="0" cellspacing="0" border="0" class="orders">
        <thead colspan="2">
        <tbody>
            <tr>
                <th>Product Id</th>
                <th>Product Name</th>
                <th>Product Price </th>
                <th>Btc Address</th>
                <th>Payment Status</th>
            </tr>
           <?php $_products->getOrdersByUser();?>
        </tbody>
    </table>
</center></div>
           
        <?php
    }
    else if(isset($_GET["changepassword"]))
    {
        
        ?>
            <div id="registerLoginTable"><center>
    <form action="usercp.php?changepassword" method="post">
        <h1>Change password</h1>
        <table cellpadding="0" cellspacing="0" border="0">
            <thead colspan="2">
            <tr><th colspan="2">
                <?php 
                       if(isset($_POST["changepassword"]))
                       {
                            $users = new users("",$_POST["password"],$_POST["password2"]);
                            $users->changepassword();
                       }
                ?>
            </tr> </thead>
            <tbody>
                <tr><th>Password : </th><td><input type="password" name="password" required/></td></tr>
                <tr><th>Confirm Password : </th><td><input type="password" name="password2" required/></td></tr>
            </tbody>
            <tfoot>
                <tr><td><button type="submit" name="changepassword" >Change Password</button></td> </tr>
            </tfoot>
        </table>
        </form>
    </center></div>
        <?php 
    }
?>
    <div id="footer">
        <center>
            <b>Coded by <a href="#">0x43rypt0n</a> </b>
        </center>
    </footer>
</body>
</html>

So in the usercp or user control panel, there are different objectives or jobs for this page 1 - password change 2- add product 3 - orders

All these functions will be used from the same php page usercp.php
At the top of the page create a new object from the class secure and initiate the function
IsUserLogedIn
To detect the current action needed or want to execute will use $_GET[“addproduct”]
For example to detect if users want to add a new product
Inside the addproduct initiate the function SecureAdminPages because this function will be only available to the administrator

Now open your terminal and type crontab -e and add this cronjob
*/5 * * * * /usr/bin/php7.4 /var/www/html/checktransactions.php

Change the php path to your php path and change the checktransactions file to your path also or the cronjob will not work

the tutorial is finished all the codes for the full project are published in tags so you can copy them ! thanks for reading and see you in new tutorial
 
Сверху Снизу