PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Thu Dec 14, 2017 5:13 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 14 posts ] 
Author Message
PostPosted: Sun Nov 05, 2017 8:27 pm 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
Hello all! I'm not a programmer and don't know PHP - this is the only reason I'm asking you for help. Back in 2004, I acquired a script for generating dynamic php pages for users' reviews - this the only small section of my website where PHP is employed. Since then, the standard command MySQL and functions related to it, particularly mysql_escape_string(), have been deprecated, and now I must replace them with MySQLi command and its functions. I understand that solving this issue is a simple task for most of you, but it is a "mission impossible" for me having no special education and knowledge. Could you please modify the attached code snippets? Thank you for your understanding and time!

Below are a few fragments that require modification. If something is missing and required for complete piece of code, please let me know. Also, do I have to create a special file for connecting to a database, or could I use the existing 'functions.php' file (also shown below)?


1) To get access to Admin Area:

Syntax: [ Download ] [ Hide ]
<?php
//if a session does not yet exist for this user, start one
session_start();

//if there is no username or password entered and the user has not already been validated, send user back to login page.
if ((empty($_POST["admin_username"]) || empty($_POST["admin_passtext"])) && empty($_SESSION['valid_user']))
                        {
                        Header("Location: index.php");
                        }

include ("../body_edit.php");
include ("../config.php");
include ("../functions.php");

//make sure user has been logged in.
if (empty($_SESSION['valid_user']))
        {
        // User not logged in, check database
//Check to see that the username and Password entered have admin access.
$sqlaccess = "SELECT username, passtext
                FROM admin
                WHERE username='"
. mysql_escape_string($_POST['admin_username']) . "'
                AND passtext = '"
. mysql_escape_string($_POST['admin_passtext']) . "'
                LIMIT 1
                "
;

        $resultaccess = mysql_query($sqlaccess)
        or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

        $numaccess = mysql_numrows($resultaccess);

        if ($numaccess == 0) {
BodyHeader("Access Not Allowed!");
?>
<style type="text/css">
<!--
.style1 {color: #FF0000}
.style2 {
        font-family: Arial, Helvetica, sans-serif;
        font-size: 12px;
}
.style3 {font-family: Arial, Helvetica, sans-serif; font-size: 14px; }
-->
</style>
<P>To access the Administration area you need to have approved access. The username and Password (<?php echo "$admin_username and $admin_passtext"; ?>) you entered are not approved!<br>
  <a href="index.php">Please try again</a>
  <?php
BodyFooter();  
exit;
}// if numaccess

//if the user/pass were valid create a session for the user.
$_SESSION['admin_passtext'] = $_POST['admin_passtext'];
$_SESSION['admin_username'] = $_POST['admin_username'];

//since user has been verified, set a session for checking on admin pages.
$_SESSION['valid_user'] = $_POST['admin_username'];

//set cookie so admin can save login info if logout link is not clicked.
if (empty($_COOKIE['admin_username']) && empty($_COOKIE['admin_passtext'])) {
setcookie("admin_username", $_POST['admin_username'], time() + 31536000, "/");
setcookie("admin_passtext", $_POST['admin_passtext'], time() + 31536000, "/");
}//if cookie
        }//if session

BodyHeader("$sitename Administration Menu");
           
//Get the number of reviews that are not approved.
            $result = mysql_query("SELECT COUNT(*) as total FROM review WHERE approve='n'
                AND
                review_item_id != '0'"
)
                or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

    $rows = mysql_fetch_array($result);

    $total = $rows["total"];

//Get the total number of reviews that are approved.
            $result = mysql_query("SELECT COUNT(*) as totaly FROM review WHERE approve='y'")
                or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

    $rows = mysql_fetch_array($result);
    $totaly = $rows["totaly"]; 
       
        //Get the total number of user submitted items that need to be approved.
            $result = mysql_query("SELECT COUNT(*) as totalitemuser FROM review_items_user")
                or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

    $rows = mysql_fetch_array($result);
    $totalitemuser = $rows["totalitemuser"];   

            ?>

//some code here....


<?php
        BodyFooter();
                exit;
?>
 


2) In my file functions.php:

Syntax: [ Download ] [ Hide ]
<?php

$NumReviews = 8;

$db_name = "xxxxxxxxxxxxxxxxx";

$connection = @mysql_connect("xxxxxxxxx", "xxxxxxxxxxxx", "xxxxxxxxxxxx")

        or die("Couldn't connect.");

$db = @mysql_select_db($db_name, $connection)

        or die("Couldn't select database.");

function db_errno($args=array()) {

        return @mysql_errno();

}
function db_error($args=array()) {

        return @mysql_error();

}
?>
 




Other code snippets with MySQL functions:

3)

Syntax: [ Download ] [ Hide ]
<?php
session_start();

include ("body_form.php");
include ("functions.php");
include ("config.php");

//some code here........

$sql = "SELECT * FROM
                        review_items
                        WHERE
                        item_id = $item_id"
;
               
                        $sql_result = mysql_query($sql)
                or die(sprintf("Couldn't execute query, %s: %s", db_errno(), db_error()));
               
        while ($row = mysql_fetch_array($sql_result)) {
$item_name = stripslashes($row["item_name"]);
$item_desc = stripslashes($row["item_desc"]);
$item_type = stripslashes($row["item_type"]);
}
BodyHeader("Submit review for $item_name");
?>
 



4) (in this snippet, there is also another deprecated function - preg_replace())

Syntax: [ Download ] [ Hide ]
<?php
session_start();

include ("body_form.php");
include ("functions.php");
include ("config.php");

//some code here........

//check user input and remove any reference to javascript.
$errjava = "<font color=red><BR><BR><B>No Javascript is allowed!  Please click edit and remove the offending code.<BR><BR></B></font>";

$summary = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $summary);
$review = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $review);
$source = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $source);
$location = preg_replace("'<script[^>]*?>.*?</script>'si", "$errjava", $location);

//replace bad words
$sql_filter = "select badword, goodword
from review_badwords
"
;

$sql_result_filter = mysql_query($sql_filter)
                or die(sprintf("Couldn't execute query, %s: %s", db_errno(), db_error()));

while ($filter = mysql_fetch_array($sql_result_filter)) {
                        $review = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $review);
                        $summary = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $summary);
                        $source = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $source);
                        $location = preg_replace('/'.$filter['badword'].'/i', $filter['goodword'], $location);
}

$review = nl2br($review);


//set_magic_quotes_runtime(0);
BodyHeader("Confirm $item_name Review");
?>



5) Can mysql_format() be simply replaced with mysqli_format()?

Syntax: [ Download ] [ Hide ]
$review = mysql_format($review);
$summary=  mysql_format($summary);
$source = mysql_format($source);
$location = mysql_format($location);


Top
 Profile  
 
PostPosted: Sun Nov 05, 2017 8:36 pm 
Offline
Forum Newbie

Joined: Sun Nov 15, 2015 12:57 pm
Posts: 11
This is not a modification or conversion. This will require a complete re-write of your script. You should probably make a post in the "for hire" section.


Top
 Profile  
 
PostPosted: Sun Nov 05, 2017 9:15 pm 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
benanamen wrote:
This is not a modification or conversion. This will require a complete re-write of your script. You should probably make a post in the "for hire" section.

I wish I could do that but I'm unemployed and barely make ends meet. Could you explain why this script must be re-written? Will it work if I just make appropriate MySQLi connection to database and replace all MySQL functions with MySQLi ones?


Top
 Profile  
 
PostPosted: Sun Nov 05, 2017 9:45 pm 
Offline
Forum Newbie

Joined: Sun Nov 15, 2015 12:57 pm
Posts: 11
There is so much that needs to be changed that it would end up being a re-write. You cannot just add an i and make it mysqli. It would also be best to use PDO. If you decide to try this on your own, study this tutorial first.
https://phpdelusions.net/pdo

I understand if you cannot afford to hire someone but it is not likely someone is going to do this for free. All the forums you have posted to are "Help" forums where we help you with your attempt at fixing your problem. Since you are not a programmer you can't really make an attempt at fixing it which means someone needs to do it all for you. You may get lucky and find someone that will do it, but it is not very likely.


Top
 Profile  
 
PostPosted: Mon Nov 06, 2017 11:23 am 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
Yes, I understand that and hope that there is someone who will at least make modifications to the code snippets I provided - this is all I asked for. A few people have already gave me some valuable, helpful advises - this is what any forum is for!
Thanks for the tutorial link, but I'm afraid I wouldn't understand much from it as I'm not knowledgeable in php. To take the PDO path, it will take me forever to fix everything. Unfortunately I don't have any physical time as I'm remodeling my static webpages (5k of them!) day and night to make my website mobile friendly. I think I better stay with MySQLi option since it would be easier for me to implement. Despite deprecated MySQL command and functions, the script has been working so far, so I probably wouldn't bother fixing its other flaws at the moment.


Top
 Profile  
 
PostPosted: Mon Nov 06, 2017 12:12 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13458
Location: New York, NY, US
You code's use of the mysql extension is pretty simple. Try changing "mysql_" to "mysqli_" and see what errors you get. See the documentation (http://php.net/manual/en/book.mysqli.php) to see any differences between the commands.

mysql_connect
mysql_select_db
mysql_errno
mysql_error
mysql_query
mysql_fetch_array

Also, preg_replace() is not deprecated, but does require delimiters for the regular expression. Try:
Syntax: [ Download ] [ Hide ]
 preg_replace("'/<script[^>]*?>.*?<\/script>'/si", "$errjava", $summary);

_________________
(#10850)


Top
 Profile  
 
PostPosted: Mon Nov 06, 2017 2:51 pm 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
Christopher wrote:
You code's use of the mysql extension is pretty simple. Try changing "mysql_" to "mysqli_" and see what errors you get. See the documentation (http://php.net/manual/en/book.mysqli.php) to see any differences between the commands.

mysql_connect
mysql_select_db
mysql_errno
mysql_error
mysql_query
mysql_fetch_array

Also, preg_replace() is not deprecated, but does require delimiters for the regular expression. Try:
Syntax: [ Download ] [ Hide ]
 preg_replace("'/<script[^>]*?>.*?<\/script>'/si", "$errjava", $summary);


Christopher, thank you very much for your input!
I decided to remove the "bad words" filter and the "Error java" warning from the script. With the user's input, I created this code with the preg_replace function (will it work ok?):
Syntax: [ Download ] [ Hide ]
$summary = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $summary&#41;;
$review = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $review&#41;;
$source = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $source&#41;;
$location = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $location&#41;;


I understand that when using the procedural MySQLi functions, the first argument needs to be the MySQLi link. If my database connection is stored as $link, what code I need to include into my functions.php file?


Top
 Profile  
 
PostPosted: Mon Nov 06, 2017 6:31 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13458
Location: New York, NY, US
visitor52 wrote:
I decided to remove the "bad words" filter and the "Error java" warning from the script. With the user's input, I created this code with the preg_replace function (will it work ok?):
Syntax: [ Download ] [ Hide ]
$summary = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $summary&#41;;
$review = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $review&#41;;
$source = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $source&#41;;
$location = preg_replace&#40;"/[^A-Za-z0-9- !?.,]/","", $location&#41;;

Those are close, but you need to escape special regex characters (just escape all -non-alphanum all to be sure), so:
Syntax: [ Download ] [ Hide ]
preg_replace('/[^A-Za-z0-9\-\ \!\?\.\,]/', '', $abc);

visitor52 wrote:
I understand that when using the procedural MySQLi functions, the first argument needs to be the MySQLi link. If my database connection is stored as $link, what code I need to include into my functions.php file?
You either need to pass the variable returned from connect() or for result functions you need to return the variable returned from query().

Once you get this working, you might want to then convert it to the OO syntax. It is a little easier to work with and encapsulate.

_________________
(#10850)


Top
 Profile  
 
PostPosted: Fri Nov 10, 2017 11:38 am 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
Christopher wrote:
Those are close, but you need to escape special regex characters (just escape all -non-alphanum all to be sure), so:
Syntax: [ Download ] [ Hide ]
preg_replace('/[^A-Za-z0-9\-\ \!\?\.\,]/', '', $abc);


Great! Christopher, thank you so much!
Christopher wrote:
You either need to pass the variable returned from connect() or for result functions you need to return the variable returned from query().


Did you mean something like this?
1) I changed code in my functions.php file to establish connection to a database.

Syntax: [ Download ] [ Hide ]
<?php
class DB

{
static $link;
static $dbname;
        public static function connect()
        {
                if(empty(self::$link))
                {
                  $dbhost = 'xxxxxxxxx';
                  $dbuser = 'xxxxxxxx';
                  $dbpassword = 'xxxxxxxxxxxxx';
                  $dbname = 'xxxxxxxxxxxx';

                        self::$link = @mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);
                        self::$dbname=$dbname;
                        mysqli_set_charset(self::$link, 'utf8');
                        or die("Couldn't connect.");
                }
        }
}
DB::connect();
?>


2) I converted mysql functions in admin_menu.php:

Syntax: [ Download ] [ Hide ]
<?php
//if a session does not yet exist for this user, start one
session_start();

//if there is no username or password entered and the user has not already been validated, send user back to login page.
if ((empty($_POST["admin_username"]) || empty($_POST["admin_passtext"])) && empty($_SESSION['valid_user']))
                        {
                        Header("Location: index.php");
                        }

include ("../body_edit.php");
include ("../config.php");
include ("../functions.php");

//make sure user has been logged in.
if (empty($_SESSION['valid_user']))
        {
        // User not logged in, check database
//Check to see that the username and Password entered have admin access.
$sqlaccess = "SELECT username, passtext
                FROM admin
                WHERE username='"
. mysqli_real_escape_string($_POST['admin_username']) . "'
                AND passtext = '"
. mysqli_real_escape_string($_POST['admin_passtext']) . "'
                LIMIT 1
                "
;

        $resultaccess = mysqli_query(db::$link,$sqlaccess)
        or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

        $numaccess = mysqli_numrows($resultaccess);

        if ($numaccess == 0) {
BodyHeader("Access Not Allowed!");
?>

//some code here...

<P>To access the Administration area you need to have approved access. The username and Password (<?php echo "$admin_username and $admin_passtext"; ?>) you entered are not approved!<br>
  <a href="index.php">Please try again</a>
  <?php
BodyFooter();
exit;
}

// if numaccess

//if the user/pass were valid create a session for the user.
$_SESSION['admin_passtext'] = $_POST['admin_passtext'];
$_SESSION['admin_username'] = $_POST['admin_username'];

//since user has been verified, set a session for checking on admin pages.
$_SESSION['valid_user'] = $_POST['admin_username'];

//set cookie so admin can save login info if logout link is not clicked.
if (empty($_COOKIE['admin_username']) && empty($_COOKIE['admin_passtext'])) {
setcookie("admin_username", $_POST['admin_username'], time() + 31536000, "/");
setcookie("admin_passtext", $_POST['admin_passtext'], time() + 31536000, "/");
}//if cookie
        }//if session

BodyHeader("$sitename Administration Menu");

//Get the number of reviews that are not approved.
            $result = mysqli_query(db::$link,"SELECT COUNT(*) as total FROM review WHERE approve='n'
                AND
                review_item_id != '0'"
)
                or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

    $rows = mysqli_fetch_array($result);

    $total = $rows["total"];

//Get the total number of reviews that are approved.
            $result = mysqli_query(db::$link,"SELECT COUNT(*) as totaly FROM review WHERE approve='y'")
                or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

    $rows = mysqli_fetch_array($result);
    $totaly = $rows["totaly"];

        //Get the total number of user submitted items that need to be approved.
            $result = mysqli_query(db::$link,"SELECT COUNT(*) as totalitemuser FROM review_items_user")
                or die(sprintf("Couldn't execute sql_count, %s: %s", db_errno(), db_error()));

    $rows = mysqli_fetch_array($result);
    $totalitemuser = $rows["totalitemuser"];

            ?>

      //some code here...

      <?php
              BodyFooter();
                exit;
      ?>



Christopher wrote:
Once you get this working, you might want to then convert it to the OO syntax. It is a little easier to work with and encapsulate.


Unfortunately this is what I'm yet to learn Could you please explain the OO syntax or point me to a source?


Top
 Profile  
 
PostPosted: Fri Nov 10, 2017 6:30 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13458
Location: New York, NY, US
Yes, your code looks good. For the OO syntax see the manual: http://php.net/manual/en/book.mysqli.php there is an example: http://php.net/manual/en/mysqli.examples-basic.php

_________________
(#10850)


Top
 Profile  
 
PostPosted: Tue Nov 14, 2017 8:12 am 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
Thank you, Christopher! Just one question: The PHP Code Checker gave me an error about "or die", and, with help, I changed the code in functions.php to this:

Syntax: [ Download ] [ Hide ]
<?php
class DB
{
    static $link;
    static $dbname;
    public static function connect()
    {
        if(empty(self::$link))
        {
            $dbhost = 'xxxxxxxxx';
            $dbuser = 'xxxxxxxx';
            $dbpassword = 'xxxxxxxxxxxxx';
            $dbname = 'xxxxxxxxxxxx';

            self::$link = @mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname)
                or die("Couldn't connect.");
            self::$dbname=$dbname;
            mysqli_set_charset(self::$link, 'utf8');
        }
    }
}
DB::connect();
?>


But could I go without "or die("Couldn't connect.")"? Or should I insert another line such as "or die("Couldn't select database.")" which is present in my initial code of functions.php file:
Syntax: [ Download ] [ Hide ]
<?
//Choose how many reviews per page to display
$NumReviews = 8;

//Set the name of the Table, Database, Username and Password for Mysql.
$db_name = "<span style='color:red;text-decoration:blink' title='Alert a moderator!'>grilled spam</span>";

$connection = @mysql_connect("localhost", "<span style='color:red;text-decoration:blink' title='Alert a moderator!'>grilled spam</span>", "taiga2941ut")

        or die("Couldn't connect.");

$db = @mysql_select_db($db_name, $connection)

        or die("Couldn't select database.");

function db_errno($args=array()) {

        return @mysql_errno();

}
function db_error($args=array()) {

        return @mysql_error();

}
?>


In other words, should my new code be similar to the initial code except MySQL interface or can I exclude those lines along with mysql_errno and mysql_error? I would like to have my code similar to the initial, but is it necessary?


Top
 Profile  
 
PostPosted: Tue Nov 14, 2017 7:55 pm 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13458
Location: New York, NY, US
I do not recommend using die() or exit() unless you actually want the program to terminate. Otherwise, if there is a problem, you should generate a proper error page. Nothing wrong with if() statements. For your DB class, you could also have isError() and errorMessage() methods.

Syntax: [ Download ] [ Hide ]
<?php
class DB
{
    static $link;
    static $dbname;
    public static function connect()
    {
        if(empty(self::$link))
        {
            $dbhost = 'xxxxxxxxx';
            $dbuser = 'xxxxxxxx';
            $dbpassword = 'xxxxxxxxxxxxx';
            $dbname = 'xxxxxxxxxxxx';

            self::$link = @mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);
            if (self::$link) {
                self::$dbname=$dbname;
                mysqli_set_charset(self::$link, 'utf8');
                return self::$link;
            }
            return null;
        }
    }
}
DB::connect();
?>

_________________
(#10850)


Top
 Profile  
 
PostPosted: Sat Nov 18, 2017 9:00 pm 
Offline
Forum Newbie

Joined: Sun Nov 05, 2017 3:20 pm
Posts: 7
Christopher, thank you very much for your constructive input! It took me a few days to modify my old script and fix all errors shown in the PHP code checker, but now the script is working just fine! (and I didn't have to re-write it completely as one AH strongly suggested!) All I had to do was really just to establish a MySQLi link to a database and then replace all MySQL functions with their MySQLi equivalents according to the PHP Manual. With help from you and other good people, I could do it, and it was not an impossible task even for a noob like myself! The problem has been solved!


Top
 Profile  
 
PostPosted: Tue Nov 21, 2017 12:03 am 
Offline
Site Administrator
User avatar

Joined: Wed Aug 25, 2004 7:54 pm
Posts: 13458
Location: New York, NY, US
Congratulations on solving your problem. Good work.

_________________
(#10850)


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 14 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: Google [Bot], Yahoo [Bot] and 19 guests


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

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