Jump to content

Altec

Members
  • Posts

    91
  • Joined

  • Last visited

    Never

Posts posted by Altec

  1. I've started redesigning my site and I started working on a more robust (haha) error handler, more so than I usually do. I'm trying to distinguish between the different error levels using switch(). This is what I have:

     

    function error_handler($error_lvl,$error_msg,$error_file,$error_line)
    {
        switch($error_lvl)
        {
            case E_USER_NOTICE:
                $level = 'Notice';
            break;
            case E_USER_WARNING:
                $level = 'Warning';
            break;
            case E_USER_ERROR:
                $level = 'Error';
            break;
            default:
                $level = 'Unknown: '.$error_lvl;
        }
        $date = '['.date('d/m/y H:i P').'] ';
        $pad = floor((strlen($date) / 2));
        $error_msg = preg_replace('/ \[<a.*>\]/i','',$error_msg);
        
        $error = $date.$level."\n";
        $error .= str_repeat(' ',$pad).wordwrap('Message: '.$error_msg,75,"\n".str_repeat(' ',$pad+9))."\n";
        $error .= str_repeat(' ',$pad).wordwrap('File: '.$error_file,75,"\n".str_repeat(' ',$pad+6))."\n";
        $error .= str_repeat(' ',$pad).wordwrap('Line: '.$error_line,75,"\n".str_repeat(' ',$pad+6))."\n\n";
        
        echo '<div class="fatal_error">Uh Oh! Something terrible has happened! We\'ve dispatched our in-house monkey to take a look at things.</div></body></html>';
        @file_put_contents('../pyg.log.txt',$error,FILE_APPEND);
        exit;
    }

    I'm initiating the error like so:

     

    $db_handle = @mysql_connect('localhost','root','notmypassword');
    if( !$db_handle )
    {
        trigger_error('MySQL: '.mysql_error(),E_USER_ERROR);
    }

    Obviously I'm passing a bad password to mysql_connect. Anyway, I trigger the error at E_USER_ERROR which should return a value of 256 (caught by case E_USER_ERROR) but instead returns E_ERROR (integer value 2), as shown in the log:

     

    [28/02/10 03:28 -06:00] Unknown: 2
                Message: mysql_connect(): Access denied for user 'root'@'localhost'
                         (using password: YES)
                File: /home/root/public_html/projects/inc/init.php
                Line: 5

     

    Custom error handlers should NOT handle E_ERROR level errors as they are initiated before script execution:

     

    The following error types cannot be handled with a user defined    function: E_ERROR' date=' [b']E_PARSE[/b],    E_CORE_ERROR, E_CORE_WARNING,    E_COMPILE_ERROR,    E_COMPILE_WARNING, and    most of E_STRICT raised in the file  where    set_error_handler() is called.

    What's going on? Is it a problem with my PHP configuration?

  2. Whoaoohahahaha (or whatever an evil laugh looks like in writing)...

     

    Anyway, I assume you know die() for error handling is frowned upon?

     

    I count 7 of them. But, without having seen any code from MyBB, I imagine it is a big fat mess as well.

     

    Actually, I started MyBB development a while after that post and the development standards drastically changed my personal style. The actual MyBB code is actually pretty clean, although a majority of it goes against their own development standards. :P

  3. Welcome to the phpfreaks, grammer nazi, Altec ;)

     

    Glad to see some people who are not lazy in writing and actually care about how they present themselves. Granted, by divulging that you have OCD and will rewrite poor code, you've done two things; a) run the risk of driving yourself nuts as there is plenty of poor code to go around, and b) in essence painted a large target on your back for those who are knowledgeable enough in good coding practices and have read this thread. Something tells me you'll be watched more closely now (as Dan mentioned). No pressure. lol

     

    In any case, I'm sure you'll fit in nicely here.  :D

     

    Cheers

     

    Thanks. :D I hope people don't kill me too much.

  4. PHP at 11 huh? Something tells me this was more along of declaring variables and adding them together type PHP? Aka, you didn't really know what you were doing?

     

    My compliments if you understood what you were doing at 11 though. I know I never would have been able to.

     

    haha, from what I remember it wasn't anything special; just experimentation. I'll hit up the archives of the forum I was on at that time and see if I can find what the hell I was doing. :D

     

    Ha... you better watch out now. I'll hunt your topics with comments on your code style and quality :anim_reading:

     

    Anyways, welcome :hail_freaks:

     

    haha, I'll be sure to tailor my practices just for you. ;)

     

    Thanks everyone!

  5. A torrent file is not plain text, it's in a special format. I think there is a PHP class to parse them but I can't remember the name of it.

     

    Also, just a quick FYI, seeders and leachers are not listed in the torrent file. It simply holds a session hash that the torrent client sends to the tracker. The tracker is what responds to the torrent client with the seeders and leachers list.

  6. Hello everyone,

     

    I've never formally introduced myself, and what with this new style and all I figured I'd take the opportunity and say hello. I've been a forum stalker for a while now and have only posted when my other communities draw a blank.

     

    First, my name is Steven. I'm a 16 year old self-taught web developer from Colorado, USA. I have 5 years with (X)HTML and CSS, and almost 5 with PHP. I never really succeed at getting a decent site up and maintaining it, so I generally let my server sit around and do nothing but store random files for me. :D I've most recently become addicted to MyBB development, and I've been wasting a fair amount of hours developing plugins and other random stuff for it.

     

    I have OCD and will probably rewrite your code if you have horrendous code practices, even if I have nothing to contribute. I'm a pretty big Grammar Nazi as well. I hope I'll fit in somewhere here. ;)

     

    With all due respect,

    Steven

  7. I'm having a bit of bad luck with sessions. In the past they have worked fine for me, but this time around I'm having terrible luck. Basically, I made the crappiest login system ever. I'm using sessions to store three bits of information: 1) metadata which consists of the username, password, and salt; 2) database row id; 3) username.

     

    Here is my code to login/out the user:

    <?php
    /**
    * Copyright 2009 Steven
    */
    
    session_start();
    session_regenerate_id();
    
    define('IN_VOCAB',true);
    require('init.php');
    
    // Get POST values
    foreach( $_POST as $key => $value )
    {
        $$key = clean($value,true);
    }
    
    switch( $_SERVER['QUERY_STRING'] )
    {
        case 'login':
            // MD5 password
            $password = md5($password);
            
            // Validate user exists
            $user_val_query = $db->query("SELECT * FROM `users` WHERE `username`='{$username}' AND `password`='{$password}' LIMIT 1");
            if( mysql_num_rows($user_val_query) > 0 )
            {
                // User exists; set sessions
                $salt = substr(md5(date('F')),;
                
                $user = mysql_fetch_assoc($user_val_query);
                
                $_SESSION['steven_vocab.user.meta'] = $username.$password.$salt;
                $_SESSION['steven_vocab.user.id'] = $user['id'];
                $_SESSION['steven_vocab.user.name'] = $user['username'];
                
                // Logged in
                echo message('You have been successfully logged in as '.$username.'!','success');
                echo '<a href="',$site_url,'">Go to main site</a>.';
                show('footer.php');
            }
            else
            {
                fatal_error('Incorrect username and/or password. <a href="'.$site_url.'">Please try again</a>.');
            }
        break;
        
        case 'logout':
            // Make sure user is logged in
            require($sys_inc_path.'user_check.php');
            
            // Unset session vars
            unset($_SESSION['steven_vocab.user.meta'],$_SESSION['steven_vocab.user.id'],$_SESSION['steven_vocab.user.name']);
            echo message('You have been successfully logged out.','success');
            echo '<a href="',$site_url,'">Go to main site</a>.';
            show('footer.php');
        break;
        
        default:
            fatal_error('Invalid request.');
    }
    
    ?>
    

     

    And here is my code to check and validate the user:

    <?php
    /**
    * Copyright 2009 Steven
    */
    if( !defined('IN_VOCAB') )
    {
        echo 'Direct access to this file is not allowed.';
        exit;
    }
    
    // Check for session
    if( !isset($_SESSION['steven_vocab.user.meta']) || !isset($_SESSION['steven_vocab.user.id']) || !isset($_SESSION['steven_vocab.user.name']) )
    {
        show('login_form.html',null,true);
    }
    
    // Session exists; validate
    $salt = substr(md5(date('F')),;
    $id = $_SESSION['steven_vocab.user.id'];
    $meta = $_SESSION['steven_vocab.user.meta'];
    
    $user_info_query = $db->query("SELECT * FROM `users` WHERE `id`='{$id}' LIMIT 1");
    if( mysql_num_rows($user_info_query) > 0 )
    {
        // User exists, check username and password
        $user = mysql_fetch_assoc($user_info_query);
        if( ($user['username'].$user['password'].$salt) != $meta )
        {
            // User invalid; unset session and exit
            unset($_SESSION['steven_vocab.user.meta'],$_SESSION['steven_vocab.user.id'],$_SESSION['steven_vocab.user.name']);
            fatal_error('Invalid session metadata. <a href="'.$site_url.'">Please login again</a>.');
        }
    }
    else
    {
        // User invalid; unset session and exit
        unset($_SESSION['steven_vocab.user.meta'],$_SESSION['steven_vocab.user.id'],$_SESSION['steven_vocab.user.name']);
        fatal_error('User cannot be found. <a href="'.$site_url.'">Please login again</a>.');
    }
    
    // The user is logged in and validated; check IP address
    $user_ip = $_SERVER['REMOTE_ADDR'];
    $check_ip_query = $db->query("SELECT `ip` FROM `users` WHERE `id`='{$user['id']}' LIMIT 1");
    if( mysql_num_rows($check_ip_query) > 0 )
    {
        $stored_ip = mysql_result($check_ip_query,0,'ip');
        
        // Check if empty
        if( empty($stored_ip) )
        {
            // Update IP
            $ip_update_query = $db->query("UPDATE `users` SET `ip`='{$user_ip}' WHERE `id`='{$user['id']}' LIMIT 1");
        }
        else
        {
            // Check if current IP is same
            if( $stored_ip != $user_ip )
            {
                // Send me a text and log it
                $ip_log_data = time().' - Username "'.$user['username'].'" accessed site from IP "'.$user_ip.'" while stored IP is "'.$stored_ip.'" : ID'.$user['id'];
                file_put_contents($sys_inc_path_admin.'ip_log.txt',$ip_log_data."\n\n",FILE_APPEND);
                @mail('5555555555@vtext.com','IP Confliction: Vocab',$ip_log_data);
            }
        }
    }
    
    // Output info
    $username = $_SESSION['steven_vocab.user.name'];
    echo '<div id="user_meta">Welcome back, ',$username,'!<br />» <a href="',$site_url,'user.php?logout">Logout</a> «</div>';
    
    ?>
    

     

    When I log in, everything runs smoothly and it works perfectly. I can log in as anyone and I always have the proper access level, etc. However, when anyone else tries to log in, he or she gets the Invalid metadata message (check code). I've been swapping code in and out all day and nothing seems to fix their problems, except it works fine for me. Can anyone see anything blatantly obvious in the above code?

  8. To anyone who is afraid of attachments, they're clean. I just risked my 0s and 1s for you. :D

     

    Anyway, I'm scratching my head as to what exactly you want to accomplish. I think by including too many details you confused everyone and as a result everyone gets stuck. Break down the project into pieces and work towards them step by step, expanding and changing as you go. An otherwise easy project will explode into a huge mess of problematic code.

  9. I'm attempting some form of expandable/modular administration panel for my site. I finally got the code nailed down after a few tries. I go to load the page and:

     

    Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 33292286 bytes) in index.php  on line 53

     

    I have never run across this before. My code to build the menu (of which is causing this error) is:

    $menu = (string) null;
    $modules_dir = ADMIN_ROOT.'modules';
    $dir = opendir($modules_dir);
    while( ( $module = readdir($dir) ) !== false )
    {
    if( is_dir($modules_dir.'/'.$module) && !in_array($module,array('.','..')) && file_exists($modules_dir.'/'.$module.'/module_meta.php') )
    {
    	include($modules_dir.'/'.$module.'/'.'module_meta.php');
    
    	$meta_function = $module.'_meta';
    	$menu_init = $meta_function();
    	$count = count($menu_init) - 1;
    
    	$menu .= '<h2>'.$menu_init[0].'</h2><ul>';
    	for($i = 1; $i != $count; $i++)
    	{
    		$menu .= '<li><a href="'.$menu_init[$i]['link'].'">'.$menu_init[$i]['title'].'</a></li>';
    	}
    	$menu .= '</ul>';
    }
    }
    closedir($dir);
    
    echo output_page(ADMIN_ROOT.'inc/template.html',array('{MENU}'),array($menu));
    

    Line 53 is the one line inside the for() loop. An example *_meta() function is:

    function quicklinks_meta()
    {
    $menu_items = array(
    	'Quick Links',
    	array('id' => 'home','title' => 'ACP Home','link' => 'index.php?module=home'),
    	array('id' => 'newpost','title' => 'New Blog Post','link' => 'index.php?module=newpost'),
    	array('id' => 'newpage','title' => 'New Page','link' => 'index.php?module=newpage')
    );
    }
    

    Anyone?

  10. I figured it out:

    <?php
    
    $numquotes = count($quotes);
    $quotesperpage = 15;
    $totalpages = ceil($numquotes / $quotesperpage);
    
    if(isset($_GET['pagenum']) && is_numeric($_GET['pagenum'])) {
    	$page = (int) $_GET['pagenum'];
    } else {
    	$page = 1;
    }
    
    if($page > $totalpages) {
    	$page = $totalpages;
    }
    if($page < 1) {
    	$page = 1;
    }
    
    $start = ($page - 1) * $quotesperpage;
    $stop = $start + $quotesperpage;
    $currentquote = $start;
    
    echo '<ul id="pagination" style="margin-bottom: 1.4em;">'."\n";
    
    if($page > 1) {
    	$previous = $page - 1;
    	echo '<li class="pagination-prev"><a href="'.$url.'/quotes/page/'.$previous.'">Previous</a></li>'."\n";
    }
    
    if($page != $totalpages) {
    	$next = $page + 1;
    	echo '<li class="pagination-next"><a href="'.$url.'/quotes/page/'.$next.'">Next</a></li>'."\n";
    }
    
    echo '</ul>'."\n",'<table class="data_table">'."\n";
    
    foreach($quotes as $quote) {
    	static $i = 0;
    
    		if($currentquote == $stop || empty($quotes[$currentquote])) {
    			break;
    		}
    		$rowbg = ($i % 2 == 1) ? ' class="even"' : '';
    		echo '<tr'.$rowbg.'><td>'.$quotes[$currentquote].'</td></tr>'."\n";
    
    	$currentquote++;
    	$i++;
    }
    
    echo '</table>'."\n".'<ul id="pagination">'."\n";
    
    if($page > 1) {
    	$previous = $page - 1;
    	echo '<li class="pagination-prev"><a href="'.$url.'/quotes/page/'.$previous.'">Previous</a></li>'."\n";
    }
    
    if($page != $totalpages) {
    	$next = $page + 1;
    	echo '<li class="pagination-next"><a href="'.$url.'/quotes/page/'.$next.'">Next</a></li>'."\n";
    }
    
    echo '</ul>'."\n";
    ?>
    

  11. I currently have an array of quotes that I rotate throughout my site. I want to have on epage to list them all. I currently use this:

        echo '<table class="data_table">';
        foreach($quotes as $quote) {
            static $i = 0;
            $row = ($i % 2 == 1) ? ' class="even"' : '';
            echo '<tr'.$row.'><td>'.$quote.'</td></tr>'."\n";
            $i++;
        }
        echo '</table>';
    

    Which works fine except that I have a lot of quotes. I want to paginate the array with, say, 15 quotes per page.

     

    I've searched Google but I can only find classes and snippets. When I do find a tutorial, often it doesn't explain things very well or it is geared towards MySQL database pagination, which confuses me to no end.

     

    I'm wondering if someone has a link to a tutorial or can explain pagination. Thanks!

  12. To avoid a notice (undefined index) check to see if they even have the page in the url.

    $pages = array('home','scripts','media','archives','contact','about');
    $page = (isset($_GET['page']) && in_array($_GET['page'],$pages)) ? $_GET['page'] : 'home';
    if($page) {
        require('./pagecontent/'.$page.'.php');
    }

     

    Also, I put in 'home' as the default if it isn't in the array or not selected, but you could always change that to another page.

     

    Using this the if() check isn't even necessary, correct?

  13. I'm currently re-developing my personal site. Instead of using Wordpress, Joomla, or even a custom CMS, I'm using a really basic include() system. I'm using this code:

    <?php
    
    $pages = array('home','scripts','media','archives','contact','about');
    $page = (in_array($_GET['page'],$pages) && !empty($_GET['page'])) ? trim(stripslashes(strip_tags($_GET['page']))) : 'naughty';
    if($page != 'naughty') {
        require('./pagecontent/'.$page.'.php');
    }
    
    ?>

    After the correct page is required I then run grabmenu() and grabcontent() which are functions inside the included page file that output the menu and the content, respectively, for that page.

     

    What I'm concerned about is the require function that includes the page file. I've heard to never use such a technique because hackers could potentially include files form their server. As it is, I don't see a hole that would cause that to happen. However, I'm wondering if someone more knowledgeable than me spots a problem. :)

     

    EDIT: I should also mention I'm using this inside the included files:

    if(!defined('SITE')) {
        die('You cannot access this content directly.');
    }
    

  14. I'm using this code to pull random slogans to display on my site:

    <?php
    
    $slogans = array(
         'rawr1',
         'rawr2',
         'rawr3'
    );
    
    echo $slogans[floor(rand(0,count($slogans)))];
    
    ?>

    However, sometimes it doesn't return anything (nothing is echo'd out). Why is that, and is there a better way to do this?

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.