TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 10-03-2007, 11:20 PM   #1 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default Check my code

PHP Code:
<?php

    
/* 
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    Title : Schools Management
    Author : Muhammad Haris
    URL : http://www.mharis.net
    CONTACT: isharis@gmail.com
    
    Description : School list with show, add, edit or delete
    functionality.
    
    Created : 29th September 2007
    Modified : 3th October 2007
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
    */

    
include_once('../includes/includes.php');
    
    
//
    // Initiates new objects
    //
    
    
$tpl =& new Savant2();
    
$validate = new FormValidator;
    
$database = new Database;
    
$auth = new Auth;
    
$users = new Users;
    
    
    
//
    // Check if user is logged in
    //
    
    
if($auth->check() == false || $auth->admin_auth() == false){
        echo 
'Please login as administrator';
    }
    
    
// If logged in ->
    
else {
        include_once(
'navigation.php'); // Includes Navigation
        
        //
        // Assigning post values to variables
        //
        
        
$szName $_POST['name'];
        
$szURL $_POST['url'];
        
$szLocationField1 $_POST['locationField1'];
        
$szLocationField2 $_POST['locationField2'];
        
$szCity $_POST['city'];
        
$szState $_POST['state'];
        
$iZipCode $_POST['zipCode'];
        
$iAreaCode $_POST['areaCode'];
        
$szTelephoneNumber $_POST['telephoneNumber'];
        
$szUser $_POST['user'];
        
        
//
        // Validation rules
        //
        
        
if(isset($_POST['add_school'])){
            
$validate->isEmpty('szName''Please enter an username');
            
$validate->isEmpty('szURL''Please enter an URL');
            
$validate->isURL('szURL''Please enter a valid URL (www.domain.ext)');
            
$validate->isEmpty('szLocationField1''Please fill in a location field 1');
            
$validate->isEmpty('szCity''Please enter a city');
            
$validate->isEmpty('szState''Please enter a state');
            
$validate->isUSZipCode('iZipCode''Please enter correct US zip code format (00000)');
            
$validate->isUSAreaCode('iAreaCode''Please enter correct US area code format (000)');
            
$validate->isUSTelephone('szTelephoneNumber''Please enter correct US telephone number format (000-111-0000)');
        }
        
        
//
        // Fetches usernames from users table
        //
        
        
$szSQL "SELECT user FROM users WHERE rank = 2 AND assigned = 0";
        
$aResult $database->execute($szSQL);
        while(
$szRow mysql_fetch_array($aResultMYSQL_ASSOC)){
            
$aUser[] = $szRow['user'];
        }
        
$tpl->assign('aUser'$aUser);
        
        
        
//
        // Assigns errors to add school form
        //
        
        
if($validate->isError() && isset($_POST['add_school'])){
            
$tpl->assign('aError'$validate->getErrorList());
        }
        
        
//
        // Add a new school
        //
        
        
if(isset($_POST['add_school']) && $validate->isError() == false){
            
            
// Fetches ID of the selected user
            
$szSQL "SELECT id FROM users WHERE user = '$szUser' LIMIT 0,1";
            
$iResult $database->fetch($szSQL);
            foreach(
$iResult as $iUserID){
                
$iUser $iUserID;
            }
            
            
$aColumnNames = array(    
                
'name',
                
'url',
                
'locationField1',
                
'locationField2',
                
'city',
                
'state',
                
'zipCode',
                
'areaCode',
                
'telephoneNumber',
                
'user_id'
            
);
            
            
$aValue = array(
                
"'$szName'",
                
"'$szURL'",
                
"'$szLocationField1'",
                
"'$szLocationField2'",
                
"'$szCity'",
                
"'$szState'",
                
"'$iZipCode'",
                
"'$iAreaCode'",
                
"'$szTelephoneNumber'",
                
"'$iUser'",
            );
            
            
$szColumnNames '('.implode(", "$aColumnNames).')';
            
$szValues '('.implode(", "$aValue).')';

            
$szSQL "UPDATE users SET assigned = '1' WHERE id = $iUser";
            
$database->execute($szSQL);
            
$szSQL "INSERT INTO schools $szColumnNames VALUES $szValues";
            
$bResult $database->execute($szSQL);
            
            if(
$bResult == True){
                
$tpl->assign('szSuccess''Successfully added new school');
            }
            
        }
        
        
//
        // Schools table
        //
        
        
        
        //
        // School Details
        //
        
        
if($_GET['details']){
            
            
$iID $_GET['details'];
            
$szSQL "SELECT * FROM schools WHERE id= $iID";
            
$aResult $database->execute($szSQL);
            while(
$szRow mysql_fetch_array($aResultMYSQL_ASSOC)){
                
$aData = array($szRow);
            }
            
            
$tpl->assign('aSchoolDetails'$aData);
            
        }
        
        
//
        // Delete School
        //
        
        
elseif($_GET['delete']){
            
            
$iID $_GET['delete'];
            
            
$szSQL "SELECT user_id FROM schools WHERE id = $iID";
            
$iResult $database->fetch($szSQL);
            foreach(
$iResult as $iUserID){
                
$iUserID $iUserID;
            }
            
            
$szSQL "UPDATE users SET assigned = '0' WHERE id = $iUserID";
            
$database->execute($szSQL);
            
            
$szSQL sprintf("DELETE FROM schools WHERE id= %d"$iID);
            
$bResult $database->execute($szSQL);
            if(
$bResult == True){
                
$tpl->assign('szSuccess''Successfully delete the school with ID '.$iID);
            }
            
        }
        
        
//
        // Edit School
        //
        
        
elseif($_GET['edit']){
            
            
$iID $_GET['edit'];
            
            
$szSQL "SELECT user FROM users WHERE rank = 2";
            
$aResult $database->execute($szSQL);
            while(
$szRow mysql_fetch_array($aResultMYSQL_ASSOC)){
                
$editAUser[] = $szRow['user'];
            }
            
            
$tpl->assign('editAUser'$editAUser);
            
            
//
            // Assigning post values to variables
            //
        
            
$szName $_POST['edit_name'];
            
$szURL $_POST['edit_url'];
            
$szLocationField1 $_POST['edit_locationField1'];
            
$szLocationField2 $_POST['edit_locationField2'];
            
$szCity $_POST['edit_city'];
            
$szState $_POST['edit_state'];
            
$iZipCode $_POST['edit_zipCode'];
            
$iAreaCode $_POST['edit_areaCode'];
            
$szTelephoneNumber $_POST['edit_telephoneNumber'];
            
$szUser $_POST['edit_user'];
            
            
$szSQL "SELECT id FROM users WHERE user = '$szUser' LIMIT 0,1";
            
$iResult $database->fetch($szSQL);
            foreach(
$iResult as $iUserID){
                
$iUser $iUserID;
            }
            
            
            
$aFields = array(
                            array(
'field' => 'name''value' => $szName),
                            array(
'field' => 'url''value' => $szURL),
                            array(
'field' => 'locationField1''value' => $szLocationField1),
                            array(
'field' => 'locationField2''value' => $szLocationField2),
                            array(
'field' => 'city''value' => $szCity),
                            array(
'field' => 'state''value' => $szState),
                            array(
'field' => 'zipCode''value' => $iZipCode),
                            array(
'field' => 'areaCode''value' => $iAreaCode),
                            array(
'field' => 'telephoneNumber''value' => $szTelephoneNumber),
                            array(
'field' => 'user_id''value' => $iUser)
                            );
                            
            foreach(
$aFields as $iKey => $szValue){
                if(
trim($szValue['value']) !=  ''){
                    
$aDataToUpdate[$szValue['field']] = $szValue['value'];
                }
            }
            
            if(isset(
$_POST['edit_school'])){
                if(
array_key_exists('url'$aDataToUpdate)){
                    
$validate->isURL('szURL''Please enter a valid URL (www.domain.ext)');
                }
                if(
array_key_exists('zipCode'$aDataToUpdate)){
                    
$validate->isUSZipCode('iZipCode''Please enter correct US zip code format (00000)');
                }
                if(
array_key_exists('areaCode'$aDataToUpdate)){
                    
$validate->isUSAreaCode('iAreaCode''Please enter correct US area code format (000)');
                }
                if(
array_key_exists('telephoneNumber'$aDataToUpdate)){
                    
$validate->isUSTelephone('szTelephoneNumber''Please enter correct US telephone number format (000-111-0000)');
                }
                
                if(
$validate->isError()){
                    
$tpl->assign('aError'$validate->getErrorList());
                }
                else{
                    
                    foreach(
$aDataToUpdate as $szColumnName => $szValue){
                        
$szSQL "UPDATE schools SET $szColumnName='$szValue' WHERE id=$iID";
                        
$bResult $database->execute($szSQL);
                    }
                    if(
$bResult == True){
                        
$tpl->assign('szSuccess''Successfully edited the school with ID '.$iID);
                    }
                }
            }
            
        }
        
        
// Table
        
        
if(isset($_POST['find_school'])){
            
$szSQL sprintf("SELECT * FROM schools WHERE name = '%s' ORDER BY id"$_POST['name']);
        }
        else{
            
$szSQL "SELECT * FROM schools ORDER BY id";
        }
        
        
$szResult $database->execute($szSQL);
        while(
$szRow mysql_fetch_array($szResultMYSQL_ASSOC)){
            
$aSchoolID[] = $szRow['id'];
            
$aSchoolName[] = $szRow['name'];
        }
        
        
$tpl->assign('aSchoolID'$aSchoolID);
        
$tpl->assign('aSchoolName'$aSchoolName);
        
        
$tpl->display(ADMINTEMPLATE_PATH.'schools.tpl.php');
        
    }
    
?>
I would like some feedback on my code.

What is my common mistake? How can I cut down on repetitive tasks? What are the best ways to do the things I do.
Haris is offline  
Reply With Quote
Old 10-04-2007, 06:17 PM   #2 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Default

meh double post
bluesaga is offline  
Reply With Quote
Old 10-04-2007, 06:17 PM   #3 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Default

Code:
$szSQL = "SELECT id FROM users WHERE user = '$szUser' LIMIT 0,1";
Would be better as:

Code:
$szSQL = sprintf("SELECT id FROM users WHERE user = '%s' LIMIT 0,1", mysql_escape_string($szUser));
Its more secure to use that.

Code:
            if($bResult == True){
There is no need to use the "== True" just use:

Code:
               if($bResult){
Other than that, the code looks good, but i haven't looked THAT hard at it lol
bluesaga is offline  
Reply With Quote
Old 10-04-2007, 06:43 PM   #4 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

When you're checking that the visitor is authorised to view the page, if the check fails you should display the message and stop the execution of the script immediately. That way you can get rid of the else safely and know that the script will run only if logged in.

Yours
PHP Code:
    //
    // Check if user is logged in
    //
    
    
if($auth->check() == false || $auth->admin_auth() == false){
        echo 
'Please login as administrator';
    } 
Suggested alternative
PHP Code:
    //
    // Check if user is logged in
    //
    
    
if($auth->check() == false || $auth->admin_auth() == false){
        
//echo 'Please login as administrator';
        
$tpl->assign('szErrorMessage''Please log in as administrator.');
        
$tpl->display(ADMINTEMPLATE_PATH.'error.tpl.php');
        exit; 
// I don't know if $tpl->display() stops the script, so exit here.
    

I haven't looked below the first else yet, so there may be more comments to follow. :)
Salathe is offline  
Reply With Quote
Old 10-04-2007, 07:55 PM   #5 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Quote:
Originally Posted by bluesaga View Post
Code:
$szSQL = "SELECT id FROM users WHERE user = '$szUser' LIMIT 0,1";
Would be better as:

Code:
$szSQL = sprintf("SELECT id FROM users WHERE user = '%s' LIMIT 0,1", mysql_escape_string($szUser));
Its more secure to use that.

Code:
            if($bResult == True){
There is no need to use the "== True" just use:

Code:
               if($bResult){
Other than that, the code looks good, but i haven't looked THAT hard at it lol
Thanks and I thought sprintf was only used for user submitted data?

Quote:
Originally Posted by Salathe View Post
When you're checking that the visitor is authorised to view the page, if the check fails you should display the message and stop the execution of the script immediately. That way you can get rid of the else safely and know that the script will run only if logged in.

Yours
PHP Code:
    //
    // Check if user is logged in
    //
    
    
if($auth->check() == false || $auth->admin_auth() == false){
        echo 
'Please login as administrator';
    } 
Suggested alternative
PHP Code:
    //
    // Check if user is logged in
    //
    
    
if($auth->check() == false || $auth->admin_auth() == false){
        
//echo 'Please login as administrator';
        
$tpl->assign('szErrorMessage''Please log in as administrator.');
        
$tpl->display(ADMINTEMPLATE_PATH.'error.tpl.php');
        exit; 
// I don't know if $tpl->display() stops the script, so exit here.
    

I haven't looked below the first else yet, so there may be more comments to follow. :)
Thanks Salathe. Saves two bunch of lines.
Haris is offline  
Reply With Quote
Old 10-04-2007, 08:26 PM   #6 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

Quote:
Originally Posted by Haris View Post
Thanks and I thought sprintf was only used for user submitted data?
$szUser is submitted data ($szUser = $_POST['user'];). Just because you're using a SELECT here doesn't mean that a nasty user couldn't inject other code to UPDATE/DELETE/whatever.

From looking at your original post, it doesn't look like you're escaping any of the POSTed data. The validation class might help a bit (I don't know, we can't see what it does) but you should always, always use the escaping functions for all input data.
Salathe is offline  
Reply With Quote
Old 10-04-2007, 09:18 PM   #7 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Thanks for yet another tip. I thought they couldn't inject SELECT
Haris is offline  
Reply With Quote
Old 10-04-2007, 09:24 PM   #8 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Any advice how could I turn my insert query in sprintf with using the array?
Haris is offline  
Reply With Quote
Old 10-05-2007, 07:54 AM   #9 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Default

You don't have to use sprintf for everything, its simply a neater way of doing it, and forcing integers or strings.

You can do:
PHP Code:
            $aValue = array(
                
"'".mysql_escape_string($szName)."'",
                
"'".mysql_escape_string($szURL)."'",
                
"'".mysql_escape_string($szLocationField1)."'",
                
"'".mysql_escape_string($szLocationField2)."'",
                
"'".mysql_escape_string($szCity)."'",
                
"'".mysql_escape_string($szState)."'",
                
"'".mysql_escape_string($iZipCode)."'",
                
"'".mysql_escape_string($iAreaCode)."'",
                
"'".mysql_escape_string($szTelephoneNumber)."'",
                
"'".mysql_escape_string($iUser)."'",
            ); 
Has the same effect
bluesaga is offline  
Reply With Quote
Old 10-05-2007, 10:56 AM   #10 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Oh, thanks.
Haris is offline  
Reply With Quote
Old 10-21-2007, 04:16 PM   #11 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default deprecated

Another little point what version of PHP are you using, as (correct me if im wrong) i think PHP5 returns a reference from the new automatically so using =& in this context is deprecated and produces E_STRICT level message:
PHP Code:
$tpl =& new Savant2(); 
if your using PHP4 then just ignore me.
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
sketchMedia is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 06:26 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design