1
\$\begingroup\$

Right now I'm finishing my very first web application, and I will buy my first domain name in my life shortly. My project is about a personal website that I'm going to upload every application I program on it. Right now I only have an accounting system and a program used by the market researchers.

The PHP file that I need your help with is the heart and soul of my whole web application. I include this file at the top of every single other PHP file.

This included.php file has these things in it:

  • The global variables referenced almost in every other PHP file
  • the empty templates pages of my site
  • Definitions of the functions referenced almost in every other PHP file

This included.php file also do some work for every request come to my application, this file does that work:

  1. It checks the connection to the main database , if not exist stop everything
  2. Manage sessions. it prepares $session[] array that has every data about that request which is needed everywhere in my applications(the accounting app, and the market researchers app, and the website itself)
  3. If the application is working in "LOG ALL" mood or "LIGHT LOG" mood, the request data is going to be recorded in request table for later debugging if something wrong happened
  4. If the application is working in "LIGHT LOG" mood only, the response data is not going to be saved
  5. If the application is working in "LOG ALL" mood, the response body(HTML DOCUMENT) will be saved on the storage, and it's path will be inserted in response table
  6. If any error happened anywhere in the application, the $forcelog flag will be raised, So when the shutdown function is called it will check this flag and log everything no matter "LOG ALL" or "LIGHT LOG" moods is turned on or not

This is the included.php file that is included at the top of every single other php file. according to the help I tried to keep my code in it's "native habitat" , So forgive me for the misspellings and the weird comments I did to myself in the source file. I kept everything in the file as it is, except the username and password variables and there are also at the end of the file a section for general functions definitions I have removed them , as I need the reviews right now to be focused on my most important file in my applications.

INCLUDED.PHP

<?php
define("DEBUG",false); // althought now I have a logs table inside my data base , I still sometimes need to echo some outbut in case of debug, this flag will be raised to let the code echo some information to the screen
define("LLOG",false); // light log, log everything but not response body(request headers, request body,response headers)
define("LOGALL",true); // if true the application will log every request and response including the headers and bodies and save them in the database. the request logging is done inside the getsessionenirounment function
// note: if some error happened in any area of the application the application will raise $forcelog flag to let the shuting down function know that tthis request and reponse must be logged no matter LLOG or LOGALL flags are on or not
define("root","c://xampp/htdocs/"); //must be changed on the server
define("emergency","c://xampp/htdocs/samea/logs/emergency.log");//emergency file to log errors in case the website database is not exist
//chdir(root);// uncomment to make every file in the project act as it is in the root directory
$forcelog = false; //this flag will be raised by lg() function to force request and response logging if they did not logged and that is in case of logs like errors or hack attempts
$request = array(); // this array is to hold a memory copy of every request , to save it later in the database if it is needed
$session = array(); //this is the heart array of my applications, it holds data abput the current request , this data is needed in every other page of the application
$hn = 'localhost'; $webdb = 'website'; $accountingdb='accdb'; $un = '******'; $pw = '******';
//<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
//empty tembelte page
$tembletepage ="<!DOCTYPE html><html><head><title>pagetitleplaceholder</title><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script><script src='/samea/js.js'></script><link rel='stylesheet' type='text/css' href='/samea/css.css'>
<script type='text/javascript'>$(document).ready(function(){var bodyheight =  window.innerHeight - $('div#footer')[0].offsetHeight - $('div#header')[0].offsetHeight-20;$('div#body')[0].style.minHeight = bodyheight + 'px';
    pagereadyscriptplaceholder});\r //secondscriptplaceholder\r</script><style type='text/css'>pagestyleplaceholder div.applicationbtn {background: #751c32;} div.applicationbtn:hover{border-top-color:#ffffff;background:#ffffff;color: #000000;} div.bluebutton{background:#99ff66;color:black;text-shadow:none;}</style>\r<!--headplaceholder-->\r</head>   <body>
<div id='header'><div id='buttons'> <a href='/samea/'><div class='button'>Home</div></a> <a href='/samea/applications/'><div class='button'>Applications</div></a>
<a href='/samea/about.php'><div class='button'>About</div></a> <a href='/samea/contact.php'><div class='button'>Contact</div></a> profileplaceholder </div></div><div id='body'> pagebodyplaceholder </div><!--end of div#body-->
<div id='footer'><div style='padding-top:10px;'>Programmed by Me</div></div></body></html>";

//the upper part of the tempelete bage (other pages echo it then echo their own content then echo the down part of the tempelete)
$tembletepageup="<!DOCTYPE html><html><head><title>pagetitleplaceholder</title><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script><script src='/samea/js.js'></script><link rel='stylesheet' type='text/css' href='/samea/css.css'>
<script type='text/javascript'>$(document).ready(function(){var bodyheight =  window.innerHeight - $('div#footer')[0].offsetHeight - $('div#header')[0].offsetHeight-20;$('div#body')[0].style.minHeight = bodyheight + 'px';
    pagereadyscriptplaceholder});\r //secondscriptplaceholder\r</script><style type='text/css'>pagestyleplaceholder div.applicationbtn {background: #751c32;} div.applicationbtn:hover{border-top-color:#ffffff;background:#ffffff;color: #000000;} div.bluebutton{background:#99ff66;color:black;text-shadow:none;}</style>\r<!--headplaceholder-->\r</head>   <body>
<div id='header'><div id='buttons'> <a href='/samea/'><div class='button'>Home</div></a> <a href='/samea/applications/'><div class='button'>Applications</div></a>
<a href='/samea/about.php'><div class='button'>About</div></a> <a href='/samea/contact.php'><div class='button'>Contact</div></a> profileplaceholder </div></div><div id='body'> pagebodyplaceholder";
//the down part of the tempelete bage
$tembletepagedown="</div><!--end of div#body--><div id='footer'><div style='padding-top:10px;'>Programmed by Me</div></div></body></html>";


/*red container*/$errormessage = "<div id='message' style='background-color:#ffb3b3;color:black;width:390px;border-radius:30px;padding:15px;left:50%;position:relative;margin-left: -210px;text-align:center'>placeholder</div><br>";
/*green container*/$successmessage = "<div id='message' style='background-color:#99ff33;color:black;width:390px;border-radius:30px;padding:15px;left:50%;position:relative;margin-left: -210px;text-align:center'>placeholder</div><br>";
/*yellow container*/$warningmessage = "<div id='message' style='background-color:#ffff66;color:black;width:390px;border-radius:30px;padding:15px;left:50%;position:relative;margin-left: -210px;text-align:center'>placeholder</div><br>";
//messages
/*$errormesg = $areamesg = "<b style='size:130%'>Restricted Area</b><br>We apologize for this inconvenience. you need to sign in to enter this area<br>
    <span style='font-size:90%'><i>Note: If you changed the default settings of your browser and turned the Cookies off ,
    our system has no way to recognize you :(</i></span>";
*/
$inactivemsg = "<b style='size:130%'>Logged out for inactivity !</b><br>Sorry for this inconvenience. you need to sign in again to enter this area<br>
    <span style='font-size:90%'><i>Note: logging out for inactivity is for your protection. you can change your stteings</i></span>";
$noprivilagemsg = "<b style='size:130%'>Restricted Area</b><br>Sorry for this inconvenience. you need to sign in with a privileged account to enter this area";
$wrongurlmsg = "<b style='size:130%'>Wrong URI</b><br><b style='color:red'>\"".$_SERVER['REQUEST_URI'] ."\"</b><br>you have requested a wrong URI. Please make sure you have requested the correct uri<br>";

$correct = "<img src='/samea/media/correct.png' style='vertical-align:middle'>";
$incorrect = "<img src='/samea/media/incorrect.png' style='vertical-align:middle'>";
$warning = "<img src='/samea/media/warning.png' style='vertical-align:middle'>";


//==============================================================================================================
//=======================================E.N.D O.F V.A.R.I.A.B.L.E.S============================================
//==============================================================================================================

//========================================START EVERY SCRIPT WORK===============================================
ob_start();
$websiteconn = $wconn = @new mysqli($hn, $un, $pw, $webdb);
if ($websiteconn->connect_error){
    $handle = fopen(emergency,"ab");fwrite($handle,"cant connect to database,".date("Y-m-d H:i:s").",mysql-error:".$websiteconn->connect_error.",IP:".$_SERVER['REMOTE_ADDR']."\r\n");
    $tembletepageup = str_replace("profileplaceholder","",$tembletepageup); $tembletepageup = str_replace("pagebodyplaceholder","<span style='color:red;'>We apologize for this inconvenience. We are currently out of service, please try again later</span>",$tembletepageup);
    fclose($handle);die($tembletepageup . $tembletepagedown );
};
register_shutdown_function('mexit');
$websiteconn->set_charset('utf8mb4');

getsessionenirounment($websiteconn); // this is the main functoin of my web application

if($session['error']){$erid=lg("INCLUDED-016","getsessionenirounment function failed",2,2);mdie("Error-id=$erid");};//function session faild
if($_SERVER['REQUEST_METHOD'] == "GET"){$get=true;$post=false;}elseif($_SERVER['REQUEST_METHOD'] == "POST"){$get=false;$post=true;}else{$get=false;$post=false;};//for shorter code later
$mquery = new mquery;$gerid;//myquery , global error id var
//========================================END EVERY SCRIPT WORK===============================================

//========================================FUNCTIONS DEFINITIONS START===============================================
// functions store start , no more code to execute

//=======tembeletes functions family start
//gettemblete functions family are going to be called by every other page depending on their needs
//remember to remove ,pagetitleplaceholder, pagereadyscriptplaceholder,pagestyleplaceholder,pagebodyplaceholder
//get the whole tembelete page
function gettemblete(){
    //now this function can deside if to get signedin page or not
    global $session;
    global $tembletepage;
    if($session['id'] && $session['username']!='guest' && $session['active'] ){
        //signedin
        $signedinbuttons = "<a style='margin-left:20px;' href='/samea/profile.php?u=".$session['userid']."'><div class='button bluebutton'>Profile</div></a>
        <span style='margin-left:3px;font-size:50%;'><a href='/samea/signin.php?signout=".$session['userid']."'>sign out</a></span>";
        if($session['accountinguser']){
            $signedinbuttons .= "<a style='margin-left:40px' href='/samea/applications/accounting-software/'><div class='button applicationbtn'>Accounting APP</div></a>";
        };
        if($session['mciuser']){
            $signedinbuttons .= "<a href='/samea/applications/saudi-market-researcher/'><div style='margin-left:5px' class='button applicationbtn'>KSA Market</div></a>";
        };
        $tembletepage = str_replace("profileplaceholder",$signedinbuttons,$tembletepage);
    }else{
        $signinsignup = "<span style='margin-left:20px;font-size:50%;'><a href='/samea/signin.php'>sign in</a> <a style='margin:15px' href='/samea/signup.php'>sign up</a></span>";
        $tembletepage = str_replace("profileplaceholder",$signinsignup,$tembletepage);
    }

    return $tembletepage;

};
//get the upper part of the tembelete page
function gettembleteup(){
    global $session;
    global $tembletepageup;

    if($session['id'] && $session['username']!='guest' && $session['active'] ){
        //if signedin build the signed in buttons for him
        $signedinbuttons = "<a style='margin-left:20px;' href='/samea/profile.php?u=".$session['userid']."'><div class='button bluebutton'>Profile</div></a>
        <span style='margin-left:3px;font-size:50%;'><a href='/samea/signin.php?signout=".$session['userid']."'>sign out</a></span>";
        if($session['accountinguser']){//if he is an accounting app client , give him the accounting app button
            $signedinbuttons .= "<a style='margin-left:40px' href='/samea/applications/accounting-software/'><div class='button applicationbtn'>Accounting APP</div></a>";
        };
        if($session['mciuser']){//if he is an mci app client , give him the market app button
            $signedinbuttons .= "<a href='/samea/applications/market-researcher-app/'><div style='margin-left:5px' class='button applicationbtn'>Market APP</div></a>";
        };
        $tembletepageup = str_replace("profileplaceholder",$signedinbuttons,$tembletepageup);
    }else{
        $signinsignup = "<span style='margin-left:20px;font-size:50%;'><a href='/samea/signin.php'>sign in</a> <a style='margin:15px' href='/samea/signup.php'>sign up</a></span>";
        $tembletepageup = str_replace("profileplaceholder",$signinsignup,$tembletepageup);
    }
    return $tembletepageup;
};
//get the down part of the tembelete page
function gettembletedown(){
    global $tembletepagedown;
    return $tembletepagedown;
};

// getsigningpage function :  this function are going to be called from other scripts if the request is trying to get a restricted area while he is not signed in
//message types : error , success ,warning
//$urlto (the url to go to after authinticate)
function getsigningpage($message,$messagetype,$urlto){
    $pagetitle = "sign in";
    $pagereadyscript="";
    $pagestyle="div.signin{background-color:rgb(210,210,210);width:390px;border-radius:30px;padding:15px;left:50%;position:relative;margin-left: -210px;} td.frmtext{text-align:left;vertical-align:top;width:120px;}
    td.inputs{text-align:center;vertical-align:top;width:250px;} td input,textarea,select {width:100%}";
    $pagebodypart = "
    <div class='signin' style='color:black;text-align:left;'><h3 style='display:inline'>Sign in.</h3><br>
    some applications/functionalities require the user authentication in order to use them <br><br><hr>
    <form method='post' action='/samea/signin.php'><table>
    <tr><td class='frmtext'>User name : <span style='color:red'>*</span></td><td class='inputs'><input name='username' type='text' maxlength='25' required></input></td></tr>
    <tr><td class='frmtext'>Password: <span style='color:red'>*</span></td><td class='inputs'><input name='password' type='password' maxlength='12' required></input></td></tr>
    <tr><td></td><td><input type='submit' value='sign in' style='width:80px'></input><label><input style='width:auto;' type='checkbox' name='remember' value='1'><span style='font-size:80%'>Remember my device</span></input></label></td></tr>
    <tr><td></td><td><span style='font-size:90%;float:right;'>or <a href='/samea/signup.php'>sign up</a></span></td></tr></table>
    <input type='hidden' name='location' value = '$urlto'></input>
    </form></div>";
    global $tembletepage;
    global $session;

    $tembletepage = gettemblete();
    if($message !== ""){
        global $successmessage; global $errormessage; global $warningmessage;

        if($messagetype =='success'){$messagepart = str_replace("placeholder",$message,$successmessage);}
        else if($messagetype =='error'){$messagepart = str_replace("placeholder",$message,$errormessage);}
        else{$messagepart = str_replace("placeholder",$message,$warningmessage);};
    }else{$messagepart = "";}
    $pagebody = $messagepart . $pagebodypart;
    $page = str_replace("pagetitleplaceholder",$pagetitle,$tembletepage);
    $page = str_replace("pagereadyscriptplaceholder",$pagereadyscript,$page);
    $page = str_replace("pagestyleplaceholder",$pagestyle,$page);
    $page = str_replace("pagebodyplaceholder",$pagebody,$page);
    return $page;
};
//=======tembeletes functions family END

//========logging functions family START
/*

*/

//this function is a key player in the application , it records the requests data if the application is running in LOG ALL mood or LIGHT LOG mood, or if some error happened and the $forcelog flag is raised
//it has 2 options 
//first: "prepare" (will get the request data in a memory copy and return it in  $request array).
//second: "log" will actually save the data in the database from the passed second arg(mostly will be $request global variable)
function insertrequest($options,$request){ // the second arg is an name indexed array to log it in case of log and has has no use in case of prepare
    global $websiteconn;
    global $session;
    switch($options){
        case "prepare":
        $returnedrequest = array();
            $returnedrequest['ip'] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ""; $returnedrequest['ip'] =  $websiteconn->real_escape_string($returnedrequest['ip']);
            $returnedrequest['loggerfile'] = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : "";  $returnedrequest['loggerfile'] =  $websiteconn->real_escape_string($returnedrequest['loggerfile']);
            $returnedrequest['sessionid'] = $session['id']; $returnedrequest['sessionid'] =  $websiteconn->real_escape_string($returnedrequest['sessionid']);
            $returnedrequest['sessionid'] = ($session['id'] === '') ? "NULL" : "'".$returnedrequest['sessionid']."'";  
            $returnedrequest['port'] = isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : "";  $returnedrequest['port'] =  $websiteconn->real_escape_string($returnedrequest['port']);
            $returnedrequest['host'] = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : "";  $returnedrequest['host'] =  $websiteconn->real_escape_string($returnedrequest['host']);
            $returnedrequest['refer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";  $returnedrequest['refer'] =  $websiteconn->real_escape_string($returnedrequest['refer']);
            $returnedrequest['uri'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : "";  $returnedrequest['uri'] =  $websiteconn->real_escape_string($returnedrequest['uri']);
            $returnedrequest['clientagent'] = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";  $returnedrequest['clientagent'] =  $websiteconn->real_escape_string($returnedrequest['clientagent']);
            $returnedrequest['method'] = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : "";  $returnedrequest['method'] =  $websiteconn->real_escape_string($returnedrequest['method']);

            $returnedrequest['header'] = json_encode(getallheaders());$returnedrequest['header'] =  $websiteconn->real_escape_string($returnedrequest['header']);
            $returnedrequest['POSTjson'] = json_encode($_POST,1);$returnedrequest['POSTjson'] =  $websiteconn->real_escape_string($returnedrequest['POSTjson']);
            $returnedrequest['GETjson'] = json_encode($_GET,1);$returnedrequest['GETjson'] =  $websiteconn->real_escape_string($returnedrequest['GETjson']);                
            $returnedrequest['cookies'] = json_encode($_COOKIE,1);$returnedrequest['cookies'] =  $websiteconn->real_escape_string($returnedrequest['cookies']);             

        return $returnedrequest;
        break;


        // save in database
        case "log":
        if(!$session['requestid']){ // in case the current request has been logged before somewhere in the code , to make sure that the request is logged only one time in db
            $query="insert into request (request_ip,loggerfile, session_id, request_port, request_host, request_refer,request_uri,
            request_clientagent, request_method, request_rowheader, POSTjson,GETjson,request_cookies) values('".$request['ip']."','".$request['loggerfile']."',
            ".$request['sessionid'].",'".$request['port']."','".$request['host']."','".$request['refer']."','".$request['uri']."',
            '".$request['clientagent']."','".$request['method']."','".$request['header']."','".$request['POSTjson']."','".$request['GETjson']."','".$request['cookies']."');";


            $result = $websiteconn->query($query); if(!$result){lg("INCLUDED-007",sqlerror($query,$wconn->error));return false;};
            $session['requestid'] = $websiteconn->insert_id;
        };

            return $session['requestid'];
        break;  
    };
};
//this function will get the data in the output buffer and log it in the data base so be sure you call this function at the end of the outbut

//3- this function is to insert the request friendly data like the nickname like "mainpage from outside" , "upload a picture" , edit profile
function rqdata($incodesign,$nickname,$ajax,$category="website",$subcategory="NULL",$extradata="NULL"){
    //category
    //  1-website
    //  2-applications
    global $session;global $websiteconn;
    if(!$category){$category="website";};
    //requestdata table , column names: //incodesign,nickname,category, subcategory, extradata, request_id
    if($session['requestid']){
        if($subcategory !="NULL"){$subcategory = "'$subcategory'";}if($extradata !="NULL"){$extradata = "'$extradata'";}
        $query = "insert into requestdata (incodesign,nickname,ajax,category, subcategory, extradata, request_id)
        values('$incodesign','$nickname','$ajax','$category', $subcategory, $extradata, '".$session['requestid']."')";
        $result = $websiteconn->query($query);if(!$result){
        lg("inc-501",sqlerror($query,$websiteconn->error));
        }
    }else{
        lg("inc-502",sqlerror($query,$websiteconn->error));
    };
    //
};

//lg() function  a VERY HEAVY CALLED function in my application
//log something :, error , attack, invalid input, strange-client , crash
//since the lg() function is called too much with mysql errors so I made mysql errors logs are the default situation i'm going to call lg() function for
function lg($incodesign,$extradata="NULL",$log_category="error",$log_subcategory="mysql-error"){
    //log table columns: id, request_id, log_category, log_subcategory, log_time, extradata, incodesign
    //columns used by the function: incodesign, extradata, log_category, log_subcategory
    //current log_category : error , invalid-input
    //current log_subcategory : error.mysql-error, error.function-fail - invalid-input.normal, invalid-input.strange-client,
    global $session;global $websiteconn;global $request;
    if($extradata == ""){$extradata = "NULL";};
    if($extradata != "NULL"){$extradata = "'$extradata'";};
    //resolve category if they are in numberss
    switch($log_category){ //invalid inputs are the logs for any type of invalid inputs(requests);
        case "1":$log_category = "invalid-input";
            if($log_subcategory ==1){$log_subcategory = "normal";};// e.g invalid email in an email field
            if($log_subcategory ==2){$log_subcategory = "strange-client";};// e.g not supported radio button value, or not number value on a number field (any type of input that is not supprted by my javascript code)
            if($log_subcategory ==3){$log_subcategory = "wrong-uri";};
            if($log_subcategory ==4){$log_subcategory = "restricted-area";};
            if($log_subcategory ==5){$log_subcategory = "active-timeout";};
            break;
        case "2":$log_category = "error";
            if($log_subcategory ==1){$log_subcategory = "mysql-error";}; // this is the default case I'm using lg() function for, I even made it the default paramters fot the 3ed and 4th paramters of the lg() function
            if($log_subcategory ==2){$log_subcategory = "function-fail";};//internal function failed
            if($log_subcategory ==3){$log_subcategory = "system";}; // system data inconsistency, for example a request that has more than 1 response , 
            break;
    }

    if($log_subcategory == ""){$log_subcategory = "NULL";}else{$log_subcategory = "'$log_subcategory'";}

    //force request response log for these cases if did not log
    if($log_category == "error"  || $log_subcategory == "strange-client"){
        if(!$session['requestid']){
            $forcelog = true; //act like LOGALL to force log request and response with response body 
            $session['requestid'] = insertrequest("log",$request);
        }
    }

    $query = "insert into log (request_id, log_category, log_subcategory, extradata, incodesign)
    values('".$session['requestid']."', '$log_category', $log_subcategory, $extradata, '$incodesign');";
    $result = $websiteconn->query($query);
    if(!$result){
        //emergency log
    }else{return $websiteconn->insert_id;};
    return 0;
};

//
function insertresponse(){
    global $websiteconn;
    global $session;
    $request_id = isset($session['requestid']) ? $session['requestid'] : "";
    $query = "insert into response (request_id) values('$request_id');";
    $result = $websiteconn->query($query);if(!$result){if(DEBUG){echo "====DEBUG INFO=====" .$websiteconn->error;};return false;};
    if(LOGALL || $forcelog){
        //log response body also (save the file on it's location on logs/response_rowbody/5.mlog) file format is type:"responserowbodyid",id:id;<DOCTYPE HTML>...
        $id = $websiteconn->insert_id;

        $responsebody = "type:\"responserowbodyid\",id:$id;".ob_get_contents();
        ob_flush();//send output then write the file , (a little optimization)
        $response_rowbody = "samea/logs/response_rowbody/$id.mlog";//
        //$fhandle = fopen($companyfolder."backups/.htaccess","wb");
        $fhandle = fopen($response_rowbody,"wb");if(!$fhandle){if(DEBUG){echo "====DEBUG INFO===== can't open file";};return false;}
        if(!fwrite($fhandle,$responsebody)){if(DEBUG){echo "====DEBUG INFO===== can't write to file";};return false;}
        $response_bodysize = strlen($responsebody);
        $query = "update response set response_rowbody='$response_rowbody',response_bodysize='$response_bodysize',documentexist='1' where id='$id';";
        $result = $websiteconn->query($query);if(!$result){if(DEBUG){echo "====DEBUG INFO=====" .$websiteconn->error;};return false;};
        fclose($fhandle);
    }
    flush();
    $response_rowheader = $websiteconn->real_escape_string(json_encode(apache_response_headers()));
    $query = "update response set response_rowheader='$response_rowheader' where id='$id';";
    $result = $websiteconn->query($query);if(!$result){if(DEBUG){echo "====DEBUG INFO=====" .$websiteconn->error;};return false;};
    return;
};


//function to build a sql query and it's error . designed to reduce code when logging mysqlerrors
// example :  lg("PURCHASE-219",sqlerror($query,$conn->error));
function sqlerror($query,$error){
    global $websiteconn;
    return $websiteconn->real_escape_string(json_encode($errorarray = array("query"=> $query,"error"=>$error)));
};

//========logging functions family END

//function to real_escape_string by reference , and return the escaped string also to make the code smaller. now you can code reals($string) insted of $string = $websiteconn->real_escape_string($string);
function real_s(&$string){global $websiteconn;$string = $websiteconn->real_escape_string($string);return $string;}
//this function is registered to be called when shutting down to handle any funcitionality I need to do on exit , right now only log response
function mexit(){
    global $forcelog;
    chdir(root);//register_shutdown_function changes the current directory , so we must change it back
    if(LOGALL || LLOG || $forcelog){insertresponse();};
};




//my die function , die scripts in cusom tembeletes
function mdie($message,$temblete = 10,$buildtemblete = true,$cleanbuffer=false){
    global $errormessage;global $warningmessage;global $successmessage; // tembeltes with colors
    global $errormesg; global $inactivemsg; global $noprivilagemsg; global $wrongurlmsg; // messages
    // tembelete from 0 to 1 are tembeltes with no text message, just styled embty containers , from 10 and above are messages with tembelte text , like wrong uri
    switch($temblete){
        case 1: //error style(red box)
            $contents = $message;
            $contents = str_replace("placeholder",$contents,$errormessage);
        break;
        case 2: //warning style(yellow box)
            $contents = $message;
            $contents = str_replace("placeholder",$contents,$warningmessage);
        break;
        case 10: // error
        case "error":
            $contents = "<b>General Error!</b><br>We apologize for this inconvenience. This is an error, it has been recorded and we are proccessing it. You can try again later, or go <a href='#' onclick='window.history.back()'>back</a>.<br>
            You can also <a href='\samea\contact.php?subject=reporterror' target='_blank'>contact us</a><hr><b>Technical Details</b><br>$message";
            $contents = str_replace("placeholder",$contents,$errormessage);
        break;
        case 13: //wrong url
        case "uri":
            $contents = str_replace("placeholder","placeholder<hr><b>Technical Details</b><br>$message",$warningmessage);
            $contents = str_replace("placeholder",$wrongurlmsg,$contents);
        break;
        case 21: //span error with icon
            $contents = "<span style='background-color:#ffb3b3;color:black;display:inline-block;border-radius:30px;padding:2px;text-align:center'><img style='vertical-align:middle' src='/samea/media/incorrect.png'>$message</span>";
        break;
        case 22: //span error with icon
            $contents = "<span style='background-color:#ffff66;color:black;display:inline-block;border-radius:30px;padding:2px;text-align:center'><img style='vertical-align:middle' src='/samea/media/warning.png'>$message</span>";
        break;
        default:$contents = $message;
    };

    if($cleanbuffer){ob_clean();}
    if($buildtemblete){
        ob_clean();
        $page = gettemblete();
        $page = str_replace("pagetitleplaceholder","error",$page);
        $page = str_replace("pagereadyscriptplaceholder","",$page);
        $page = str_replace("pagestyleplaceholder","",$page);
        $page = str_replace("pagebodyplaceholder",$contents,$page);
    }else{$page = $contents;};
    echo $page;
    exit;
}
//echo styled error message , usally used to echo errors in ajax calls
// my echo function , echo things in tembeletes
function mecho($message,$temblete = "error"){

    global $errormessage;global $warningmessage;global $successmessage;


    switch ($temblete){
        case"error":
            $contents = "<span style='background-color:#ffb3b3;color:black;display:inline-block;border-radius:2px;padding:1px;text-align:center'><img style='vertical-align:middle' src='/samea/media/incorrect.png'>$message</span>";
        break;

        case "warning":
        case 2:
        $contents = "<span style='background-color:#ffff66;color:black;display:inline-block;border-radius:2px;padding:1px;text-align:center'><img style='vertical-align:middle' src='/samea/media/warning.png'>$message</span>";
        break;

    };
    echo $contents; 
}


//function mquery->query() to make query and lg the error if it happened , started to work with it since 10-08-2016
//now I can code my queries like this $mquery->query($websiteconn,"delete from user where id='5';","included.phpscript-15244125")
//instead of $result = $conn->query("delete from user where id='5';"); if(!4result){lg(""included.phpscript-15244125"",sqlerror($query,$conn->error));}
//if something wrong happened with the query it will be logged inside the function
class mquery{
    public $erid;
    public function query($conn,$query,$incodesign){
        global $gerid;
        $result = $conn->query($query);
        if($result){
            return $result;
        }else{
            $this->erid= $gerid = lg($incodesign,sqlerror($query,$conn->error));
            return false;
        }  
    }
}

function userid($conn, $name){ //return 0 if the user is not exist
    $query = "select id from user where name='$name';";
    $result = $conn->query($query); if(!$result){return "make sql error";};
    if($result->num_rows === 0){return 0;};
    $row = $result->fetch_array(MYSQLI_ASSOC);
    return $row['id'];
};

//===================== sessions and security functions and variables  - START

//get an array of the current request envirounment
// id, userid, username, usertype, useractive, ip, lastactive
//if user is an accountant app client , I'm gonna need these data {dbid,dbname,dbconnpw,dbcompanyname,dbcompanylogo }
//if the session id provided is not exist in the sessions table the $session['id'] is set to "" embty string
//session posibilities are( no session not existed session id , guest session , (accounts session) , (not active accounts session) )
function  getsessionenirounment($websiteconn){
    global $session; global $request;
    //start session definitions

    $session['ip'] = null;  // session ip that is stored in the database when the session was created
    $session['currentip']=null; // the current request ip
    $session['lastactive'] = null;  // session last active date
    $session['elpasedminutes'] = null;  // elpased minutes since his last action
    $session['active'] = null;  //true if the elpasedminutes < minutestologout, to save if statments in the program and use it directly
    // user table data
    $session['userid'] = null;   // user id
    $session['username'] = null; // user name
    $session['userpassword'] = null;
    $session['usersalt'] = null;
    $session['usertype'] = null; // user type (ENUM('accounting','mci'))
    $session['useractivated'] = null; // the activation code used by the user , it might be null;
    $session['minutestologout'] = null; // prefered minutes to log out after due to inactivity
    $session['displayname'] = null;
    $session['phonenumber'] = null;
    $session['email'] = null;
    $session['createdatetime'] = null;

    //my commercials applications data 
    $session['activated'] = null;
    $session['accountinguser'] = null; // does the user has accounting user
    $session['activeaccountinguser'] = null; // is the user active or the activation days is ended
    $session['accountinguserremaindays'] = null; // remaining days to deactiveate the user
    $session['mciuser'] = null; // does the user has mci app licence

    $session['accountingusertype'] = null;  // accounting user type ENUM admin, user
    $session['caneditbusiness'] =  null; 
    $session['caneditaccounting'] =  null; 
    $session['canquery'] =  null; 
    $session['canbackup'] =  null; 

    $session['dbid'] = null; // db.id table
    $session['dbname'] = null; // db.name (for connecting to the user database)
    $session['dbhost'] = null;
    $session['dbconnun'] = null; //db.connun  , data base connection username
    $session['dbconnpw'] = null; //db.connpw  , data base connection password
    $session['dbcompanyname'] = null; //db.companyname  , data base company name , to echo in the accounting pages
    $session['dbcompanylogo'] = null; //db.companylogo  , data base company logo link, to echo in the accounting pages
    $session['dbcompanyfolder'] = null;
    $session['dballowednumofusers'] = null;
    $session['dbcurrentnumofusers'] = null;
    $session['dballowednumofbkps'] = null;
    $session['dbhaserror'] = null;
    $session['dbhomemessage'] = null;
    //mci market application data
    $session['mciexpirydate'] = null;
    $session['activemciuser'] = null;
    $session['mcitodayremainusage'] = null;
    $session['mcitotalremainingusage'] = null;
    $session['mciimptodayremainusage'] = null;
    $session['mciimptotalremainingusage']  = null;
    $session['mcilastdayofusage'] = null;
    $session['mcitodaynumofusage'] = null;
    $session['mciimplastdayofusage'] = null;
    $session['mciimptodaynumofusage'] = null;
    $session['error'] = false;


    //end session definitions ================================================ 
    //start function work


    $sessionid = isset($_COOKIE['sessionid']) ?  $_COOKIE['sessionid'] : $sessionid = "";
    //session table data
    $session['id'] = $sessionid; // session id
    $session['requestid'] = null;
    $request = insertrequest("prepare",""); // get a memory copy of the current request data and save it in the global variable $request
    if(LOGALL || LLOG){$session['requestid'] = insertrequest("log",$request); if(!$session['requestid']){lg("INCLUDED-008","insertrequest function faild",2,2);$session['error']=true;return;};};

    //if the sessionid is not in the pattern , it's probably ahack attempt, log it as strange client
    if(preg_match("/[^a-f0-9]/u",$sessionid) || (strlen($sessionid) >0 && strlen($sessionid) < 30)){real_s($sessionid);lg("INCLUDED-009","sessionid=$sessionid",1,2);$session['error']=true;return;};
    //check if the provided 32 hex session id is exist and valid and not ended or not
    $query = "select session.*,session.id as sessiontable_id ,user.*,user.id as usertable_id,user.name as usertable_name,user.type as usertable_type,
    user.createdatetime as usertable_createdatetime ,accountinguser.*,accountinguser.type as accountingusertable_type,accountinguser.active as accountingactive, db.*,db.id as dbtable_id,db.name as dbtable_name,db.expirydate as dbtable_expirydate, activationcode.*,mciuser.* from session inner join user on session.user_id=user.id 
    and session.id='$sessionid' and session.ended != true left join accountinguser on user.id = accountinguser.user_id left join db on accountinguser.db_id = db.id left join activationcode on user.activated=activationcode.activationcode left join mciuser on user.id=mciuser.user_id;";
    $result = $websiteconn->query($query); if(!$result){lg("INCLUDED-010",sqlerror($query,$wconn->error));$session['error']=true;return;};

    if($result->num_rows !==1){
        $session['id'] = ""; // if the user entered a session that is not exist change his session and embty it "", to protect the program later from failing;
        $sessionid = createguestsession($websiteconn); if($sessionid === false){lg("INCLUDED-011","createguestsession function faild",2,2);$session['error']=true;return;};
        setcookie("sessionid",$sessionid,time() + (86400 * 30),"/");
        return;
    }; // result = 0.  the client is sending a non exist session id or ended session, propably sign out , or inactive sign out or a hack attempt, unless you clear the session table
    // now we have a valid session , lets work on it (check it's validity and get it's user data)
    setcookie("sessionid",$sessionid,time() + (86400 * 30),"/"); // renew the cookie life
    $row = $result->fetch_array(MYSQLI_ASSOC);
    //var_dump($row); echo "========================================================";
    //echo $row['lastactive'];
    $elpasedminutes = comparedatetime(date('Y-m-d H:i:s'),$row['lastactive'],'i');
    if($elpasedminutes === false){lg("INCLUDED-012","comparedatetime function faild",2,2);$session['error']=true;return;}// something wrong in the function calling
    $session['ip'] = $row['ip'];
    $session['currentip'] = $_SERVER['REMOTE_ADDR'];
    $session['lastactive'] = $row['lastactive'];
    $session['elpasedminutes'] = $elpasedminutes;
    $session['userid'] = $row['usertable_id'];
    $session['username'] = $row['usertable_name'];
    $session['userpassword'] = $row['password'];
    $session['usersalt'] = $row['salt'];
    $session['usertype'] = $row['usertable_type']; 
    $session['useractivated'] = $row['activated'];
    $session['minutestologout'] = (int)$row['minutestologout'];
    $session['displayname'] = $row['displayname'];
    $session['phonenumber'] = $row['phonenumber'];
    $session['email'] = $row['email'];
    $session['createdatetime'] = $row['usertable_createdatetime'];
    //new vars active
    $session['activated'] =  $row['activated']; // last activation code used by the user
    if($session['activated']){ //the integerty of the data inside the activationcodes-like the db_id correctness- is the responsibility of the code who builds activationcodes(control room)
        //all next data is being set by the activation code, if the user don't have activation code it means it is a basic user and  all next data will still null
        $session['accountinguser'] = $row['accountinguser']; // does the user has accounting user
        $session['activeaccountinguser'] =  $row['accountingactive'];
        $session['mciuser'] = $row['mciuser']; // does the user has mci user
        //
        $session['accountingusertype'] = $row['accountingusertable_type'];
        $session['caneditbusiness'] = $row['caneditbusiness'];
        $session['caneditaccounting'] = $row['caneditaccounting'];
        $session['canquery'] = $row['canquery'];
        $session['canbackup'] = $row['canbackup'];

        $session['dbid'] = $row['dbtable_id'];
        if($session['dbid']){
            $query = "select count(user_id) as count from accountinguser where db_id='".$session['dbid']."';";
            $result = $websiteconn->query($query);if(!$result){lg("INCLUDED-013",sqlerror($query,$wconn->error));$session['error']=true;return;};
            $row2 = $result->fetch_array(MYSQLI_ASSOC);$session['dbcurrentnumofusers'] = $row2['count'];
            $session['dbname'] = $row['dbtable_name'];
            $session['dbhost'] = $row['connhost'];
            $session['dbconnun'] = $row['connun'];
            $session['dbconnpw'] = $row['connpw'];
            $session['dbcompanyname'] = $row['companyname'];
            $session['dbcompanylogo'] = $row['companylogo'];
            $session['dbcompanyfolder'] = $row['companyfolder'];
            $session['dballowednumofusers'] = $row['allowednumofusers'];
            $session['dballowednumofbkps'] = $row['allowednumofbkps'];
            $session['dbexpirydate'] = $row['dbtable_expirydate'];
            $session['dbhaserror'] = $row['haserror'];
            $session['dbhomemessage'] = $row['homemessage'];
            //depreciated - now use the expirydate column of the db to calculate the user remaining accounting days and to deactive all the db users
            //$elpaseddays = floor(comparedatetime(date("Y-m-d"),$row['dateofactivation'],"d"));
            //$session['accountinguserremaindays'] = ($elpaseddays < $row['accountinguserdays']) ? $row['accountinguserdays']- $elpaseddays: 0; // remaining days to deactiveate the user
            $remainingdays = floor(comparedatetime($row['dbtable_expirydate'],date("Y-m-d"),"d"));if(!$remainingdays){lg("INCLUDED-014","comparedatetime function faild",2,2); $session['error']=true;return;};
            $session['accountinguserremaindays'] = $remainingdays ? $remainingdays : 0;
        };
        if($session['mciuser']){
            $session['activemciuser'] =  $row['active'];
            $session['mciexpirydate'] = $row['mciexpirydate'];  
            //factories
            if($row['lastdayofusage'] == date("Y-m-d")){$session['mcitodayremainusage'] = $row['mcimaxusageperday'] - $row['todaynumofusage'];}
            else{$session['mcitodayremainusage'] = $row['mcimaxusageperday'];}
            $session['mcitotalremainingusage'] = $row['mcitotalmaxusage'] - $row['totalnumofusage'];
            $session['mcilastdayofusage'] = $row['lastdayofusage'];
            $session['mcitodaynumofusage'] = $row['todaynumofusage'];
            //imports and exports
            if($row['implastdayofusage'] == date("Y-m-d")){$session['mciimptodayremainusage'] = $row['mciimpmaxusageperday'] - $row['imptodaynumofusage'];}
            else{$session['mciimptodayremainusage'] = $row['mciimpmaxusageperday'];}
            $session['mciimptotalremainingusage'] = $row['mciimptotalmaxusage'] - $row['imptotalnumofusage'];
            $session['mciimplastdayofusage'] = $row['implastdayofusage'];
            $session['mciimptodaynumofusage'] = $row['imptodaynumofusage'];
        };
    }

    if($session['elpasedminutes'] < $session['minutestologout']){
        $session['active'] = true;
        if(!updatesessionlastactive($websiteconn,$session['id'])){lg("INCLUDED-014","updatesessionlastactive function faild",2,2);$session['error']=true;return;}
    }else{
        $session['active'] = false;
        $query = "update session set ended =true where id='".$session['id']."';";
        $result = $websiteconn->query($query); if(!$result){lg("INCLUDED-015",sqlerror($query,$wconn->error));$session['error']=true;return;};
        $sessionid = createguestsession($websiteconn); if($sessionid === false){lg("INCLUDED-014","createguestsession function faild",2,2);$session['error']=true;return;};
        setcookie("sessionid",$sessionid,time() + (86400 * 30),"/");
    }
    //var_dump($session);die();
    //if(DEBUG){var_dump($session);};
    //return false;
    return;
};


function createguestsession($websiteconn){
    $sessionid = substr(md5(rand()), 0, 30);
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_id = userid($websiteconn, "guest"); if(!$user_id || $user_id ==  "make sql error"){return false; die("included file-Error-002 Please call DB admin.");};
    $query = "insert into session(id,user_id,ip,lastactive,ended)values('$sessionid',$user_id,'$ip','".date('Y-m-d H:i:s')."',false);";
    $result = $websiteconn->query($query);if(!$result){return false; die("included file-Error-003, please try again later and call DB admin,");}; // the id may duplicate-posibility 0.0000000000001%
    return $sessionid;
};

function updatesessionlastactive($websiteconn,$id){
    $query = "update session set lastactive='".date('Y-m-d H:i:s')."' where id='$id';";
    $result = $websiteconn->query($query); if(!$result){return false;/*die("Error-006, Please call DB admin");*/};
    return true;
};


//the function do the neccessery updates in the system when a user uses an activation code, or when you activate a user by an activation code from the cr
//this function will check the validety of the activation code , you can call it ubon non existing codes and it will return false
// WARNING you must valid the activation code if it contains non allowed chars for security.
//the function will make the changes in a transaction 
function activateuser($websiteconn,$activationcode,$user_id){
    //right now I don't need reviews on this function 
    //it had about 20 lines of code
};
//===================== sessions and security functions and variables  - END



function buildbkpfromsql($sqlfile,$destination){

    //right now I don't need reviews on this function 
    //it had about 40 lines of code


};
//return 2 if it is not a suportted bkp file (no header sign , or file size is not equals)
//return 1 if some other error
//return 0 if everything is good
function buildsqlfrombkp($bkpfile,$distenation){
    //header size is 54 decimal , file starts from byte number 54 (counting from 0)
    //header format is :(24bytes the fixed sign)\xEF\xBB\xBFbkp.filesize= + (30bytes)(the file size in chars in foxed 30 bytes) + ???bytes the file

    //right now I don't need reviews on this function 
    //it had about 40 lines of code
};

//this function is called in misc.php file , if the summary found a echeck error it will stop the db till debugging to prevent more data changing
function stopdb($conn,$id){
    //right now I don't need reviews on this function 
    //it had about 40 lines of code
}

//==============================================
//    GENERAL FUNCTIONS - START
//==============================================

//check if it is a valid date , currently the function is not supporting validate ranges and does no support different ranges
function isdate($date,$from="0001-01-01",$to="9999-12-31",$format="Y-m-d"){
    //right now I don't need reviews on this function 
    //it had about 50 lines of code
};
//this function return the total different time between 2 dates in seconds's' , minutes'i' , and hours'h'
// the function has been tested on the ISO datetime formats only YYYY-MM-DD hh:mm:ss
function comparedatetime($date1,$date2,$unit){
    //right now I don't need reviews on this function 
    //it had about 10 lines of code
};

function delTree($dir) {
    //right now I don't need reviews on this function 
    //it had about 10 lines of code
} 

//==============================================
//    GENERAL FUNCTIONS - END
//==============================================

?>

This is a typical other file showing how I use the included.php file. Please note that this file is just a sample, almost all of its code has been omitted totally.

PROFILE.PHP (omitted)

<?php //profile page
require_once 'data/included.php';rqdata("profile-001","profile",0);
if(!$session['id'] || $session['username']=='guest'){lg("profile-014","",1,4);$page = getsigningpage($noprivilagemsg,"error","/samea/profile.php");die($page);};
if(!$session['active']){lg("profile-015","",1,5);$page = getsigningpage($inactivemsg,"warning","/samea/profile.php");die($page);};
//  everything is ok. the session is for an active account (not , guest session , not anonymos, not inactive account), start the page work
if($get){
    $pageup = gettembleteup();
    $pagedown = gettembletedown();
    echo $pageup;
    //code has been ommited
    echo $pagedown;
}elseif($post){
    //some profile page fuctionalities
}
?> 

Note: As for using a $session array variable while not using php $_SESSION: when I started learning PHP I wanted to control and learn everything to learn what is going on behind the scenes. So, I wanted to have a session table inside my database that I change and control by myself. Later, I started to build everything over it, and now I'm in a situation that changing $session array is going to change almost everything and every file everywhere in my applications. But I certainly need your comments and opinions about it.

\$\endgroup\$
  • 2
    \$\begingroup\$ You should strive as much as possible to put html inside of html files and/or templates and not store it in php variables. There are a lot of examples on the web on how to have html templates. \$\endgroup\$ – Zack Macomber Nov 17 '16 at 14:43
  • 2
    \$\begingroup\$ It's well worth the effort to correct spelling mistakes. They can make it harder to maintain/understand the code in the future. \$\endgroup\$ – Zack Macomber Nov 17 '16 at 14:45
  • \$\begingroup\$ @ZackMacomber thank you so much for your feed back. as for the spilling I never thought that someone else might read my code one day, I program alone in a cave, but now I'm going to add the dictionary add-on to notepad++ to correct the spellings mistakes..........and for keeping the HTML outside the variables. I know It looks ugly, but is there any other advantage that I can get by keeping my HTML outside a variable other than the beauty of the code ? \$\endgroup\$ – Accountant م Nov 17 '16 at 15:09
  • 1
    \$\begingroup\$ @Accountantم Even the lone programmer should program like they are in a team. That means learning to use source control, spelling, format, etc. If you program like "eh, nobody is ever going to read this" then you don't strive for self-improvement. Try to write everything like your next employer is going to evaluate it for a job... \$\endgroup\$ – Ron Beyer Nov 17 '16 at 16:18
  • 1
    \$\begingroup\$ @Accountantم You might find yourself doing weird formatting of your HTML when it's stored in variables. Check out tech.myemma.com/javascript-templates-clean-dynamic-html for ideas on using HTML templates via JavaScript. You don't need to use jQuery but that option is available if you so desire. \$\endgroup\$ – Zack Macomber Nov 17 '16 at 19:24
3
\$\begingroup\$

I messed up so much, right ?

You did. But that's ok, everybody had to start at some point, and writing good code is difficult and requires a lot of practice.

Formatting

Formatting and coding standards are extremely important. There is so much wrong here that it would take a while to list, so I'll concentrate on the things that will improve the code the most.

I would also strongly suggest that you:

  1. Read code other people wrote.
  2. Use an IDE. It will format code for you, and it will have some sort of lint program hinting at common errors and standard violations.
  3. Check out PHP coding standards such as PSR.
  4. Rewrite your code - or maybe a smaller project - using the suggestions you will get here and then post another question to receive some more specific tips

Regarding your code:

  • You do way too much on one line. One line should contain one statement, not an entire block of code (that's what functions are for). This goes for PHP code as well as HTML code.
  • Your variable names are impossible to read. I would suggest using camelCase.
  • A file containing 800 lines is almost always too large (it depends on the specific thing the file does, but do try to keep it small and focused on one thing). And if your code would be properly formatted, your file would be even larger.

Structure

Your file does way too many things. If you ever want to change some specific functionality, you will have a hard time finding the correct places to change your code. One file should concern itself with one thing.

A file should also either contain functions, or code that will be executed/displayed. If it contains both, it's impossible to reuse the functions without triggering the code.

You might also want to look into OOP and MVC. You don't have to get it correct right away, but reading about it will give you some ideas about seperation of concerns and how you may want to structure your code.

It also really helps to draw the structure of your program first, either using some UML program, or just pen and paper.

Security

You should read up on web security. OWASP Top 10 are a good starting point.

  • You should use prepared statements. I have no idea if you are vulnerable to SQL injection or not, but looking at the code, my guess would be that you are. It's impossible to tell which variables are safe to put in queries and which are not. You will not have this problem with prepared statements.
  • You should encode variables when you output them. Again, I don't know if you are currently vulnerable to XSS, but you probably are.
\$\endgroup\$
  • \$\begingroup\$ Thank you very much for your really helpful recommendations and suggestions... as for the 1 statement per line, I was doing that but I found my codes are getting really big, that grouping a block of logically related to each other statements would make it easier for me to scroll up and down in the file. My problem Is I never see how a real production php application would be like, every thing out there is tutorials. I read them , and run. \$\endgroup\$ – Accountant م Nov 17 '16 at 20:47
  • \$\begingroup\$ I know that this included.php file is going to be really weird because it's unique task among my other files. I'm going to post my contact.php file which is much more smaller and showing how do I deal with client inputs. So Please I need your reviews If you have enough time \$\endgroup\$ – Accountant م Nov 17 '16 at 20:47
  • \$\begingroup\$ There are many real production quality php applications you can download and read that are free software. I don't comment on their quality, but off the top of my head they include: mediawiki, phpunit, wordpress, drupal, laravel, phpmyadmin, symfony. \$\endgroup\$ – bdsl Nov 22 '16 at 20:53
  • \$\begingroup\$ tim. thank you so much for helping me on this please tell me your opinion on this when you have time. thaaaank you tim so much for helping me. mvc and oop made programming much easier as you told me :) \$\endgroup\$ – Accountant م Jan 6 '17 at 16:45
4
\$\begingroup\$

I'm afraid there are several problems with your code...

1.) do NOT include html inside a php code. You should always try to separate layers as much as possible.

2.) if you need to comment every single line, you can be 100% sure you're doing something wrong.

3.) lack of some native php functions.. You don't need to hardcode values like directory, it's a very bad practice and never necessary. Let PHP do the work for you.

4.) ignoring multiple coding standards. donotwritecodelikethisbecauseyouwillregretitsoon

5.) css in html code (while itself is in php, which makes it even worse). As said earlier, separate, separate, separate.

6.) numerous spelling mistakes

7.) using global variables

8.) procedural style

9.) concatenating SQL commands

10.) ...

Honestly, it's ok you're trying to find your own style, but don't try to reinvent the wheel. You obviously lack the necessary knowledge and experience, so you would be much better off if you started with a framework. After you learn the basics and proper programming techniques, then you can try to write your own solution (if you will still think it's necessary). I don't think you should buy a hosting/domain at this stage.

Edit: Reaction to comments:

1). how do I separate HTML from php , since php is about building html? do you mean for big HTML blocks, like the templates ? if so, is this what you mean ?

Yes, something like that. For instance the code that retrieves the data from the database shouldn't know anything about "how" the data is being presented to the user. For that we usually divide our project into several files. One of the architectural patterns that tries to solve the problem is called MVC (model-view-controller). Try to do some research on the topic, it will make your life much easier. Html with presentation logic should be in separate files (templates) and should only be concerned about how to display the data to the user, not how to get the data. It's the same with mixing css and html. We try to avoid that whenever possible. Css rules should be in separate files.

3) which line exactly of hard-coded directory I could have used a native php function in it ?

For instance here:

define("root","c://xampp/htdocs/"); //must be changed on the server
define("emergency","c://xampp/htdocs/samea/logs/emergency.log");

Your code should never be reliant on things like this. What if it runs on a shared hosting that runs linux? There's no "C" in linux... This is really unnecessary as we have function like dirname(__FILE__). Why hardcode a value pointing to C drive?

7) in some situation I guess global variables can be more easier than the local variables, specially when I control them and when they are really, really global, meaning that every single php file is going to use them! , like the flag variables for example. if some error happened in any part of the code in any file I can just say $forcelog=ture; letting the shutting down function to log the request and response data for debugging.....

For this we have config files. There you define all your static variables, but in code you deal only with abstractions. I know you're just starting with PHP, but getting bad habits can result in big problems later. You should learn a thing or two about testing and how to write your code so it's testable. Everything should be divided into small chunks, OOP helps with this too. At the current state, can you be 100% sure your global variables are holding the correct values and behave exactly as you think? Can you be sure 1 year from now?

9) where did I concatenate sql command ? and how to do it without concatenating ?

For instance here:

$query="insert into request (request_ip,loggerfile, session_id, request_port, request_host, request_refer,request_uri,
            request_clientagent, request_method, request_rowheader, POSTjson,GETjson,request_cookies) values('".$request['ip']."','".$request['loggerfile']."',
            ".$request['sessionid'].",'".$request['port']."','".$request['host']."','".$request['refer']."','".$request['uri']."',
            '".$request['clientagent']."','".$request['method']."','".$request['header']."','".$request['POSTjson']."','".$request['GETjson']."','".$request['cookies']."');";

We don't do that, because it can easily introduce a vulnerability called "SQL injection". Instead you should always use parameterizied queries (sometimes called prepared statements). Both mysqli and PDO support this.

Can you suggest a framework to start with ? ......and for reinventing of the wheel, do you see any wheel I have reinvented beside the $session wheel ? can you please tell me which line has that wheel ?

Usually the best frameworks for beginners are those which are most popular, because you can easily find help. For instance Laravel, CakePHP, Codeigniter, Symfony... Choose whichever you like the most and try to understand how it works and why it works like that. You don't need to agree with everything, but you need to understand the "why" behind it first to make a good decision. Your whole code is what we call "a custom solution". You're not using any PHP framework, so you need to manage session, security, buffers, routing.. Everything. That's not good, especially for a beginner. Even many more experienced programmers would probably struggle with that, because it gets too complex soon and it's easy to get lost. For example, are you sure you've taken care of every security vulnerability? ;)

\$\endgroup\$
  • \$\begingroup\$ Thank you very much for your advises, and please let me ask more about some of the points to improve my self more. for 1). how do I separate HTML from php , since php is about building html? do you mean for big HTML blocks, like the templates ? if so, is this what you mean ? ..... 3) which line exactly of hard-coded directory I could have used a native php function in it ? ........ \$\endgroup\$ – Accountant م Nov 17 '16 at 19:16
  • \$\begingroup\$ ......7) in some situation I guess global variables can be more easier than the local variables, specially when I control them and when they are really, really global, meaning that every single php file is going to use them! , like the flag variables for example. if some error happened in any part of the code in any file I can just say $forcelog=ture; letting the shutting down function to log the request and response data for debugging......4) that one is really the best one :) ......9) where did I concatenate sql command ? and how to do it without concatenating ? .. thank you so much :) \$\endgroup\$ – Accountant م Nov 17 '16 at 19:21
  • \$\begingroup\$ Can you suggest a framework to start with ? ......and for reinventing of the wheel, do you see any wheel I have reinvented beside the $session wheel ? can you please tell me which line has that wheel ? \$\endgroup\$ – Accountant م Nov 17 '16 at 19:25
  • 1
    \$\begingroup\$ @Accountantم, please see the updated answer. Hopefully that answers your questions :) \$\endgroup\$ – walther Nov 17 '16 at 21:11
  • \$\begingroup\$ Thaaaank you so much. that new edit helped me much, as for concatenating the sql, I escape every single thing that might come from the client, am I still vulnerable to SQL injection attacks? because I remember that I have read somewhere on stackoverflow that If I escaped the client variables using the right database charset I'm protected from SQL injection attacks, is that wrong?. I'm also going to post my contact.php file which is smaller that this file and deals with clients inputs, please give it a look when you have time. thanks :) \$\endgroup\$ – Accountant م Nov 17 '16 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.