SitePoint Sponsor

User Tag List

Page 5 of 8 FirstFirst 12345678 LastLast
Results 101 to 125 of 186
  1. #101
    SitePoint Member codergurl's Avatar
    Join Date
    Jun 2003
    Location
    Houston, Tx, USA
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by cyborg from dh
    Of course you could go:

    PHP Code:
    print 'There is a newline between this text
    and this text
    '

    (Not saying it's better, lol, just pointing it out.)
    you could also do:

    PHP Code:
    <?php
    define
    ('NL'"\n");
    echo 
    'first line' NL 'second line';
    ?>
    PHP is almost as sexy as me!!

  2. #102
    SitePoint Addict Clete2's Avatar
    Join Date
    Mar 2002
    Location
    Columbia, South Carolina
    Posts
    304
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This isn't really much help, but I find this page really hard to find. It lists all predefined variables that you can use...

    http://us4.php.net/manual/en/languag...predefined.php

  3. #103
    ¿uʍop ǝpısdn ʎɥʍ velocd's Avatar
    Join Date
    Aug 2002
    Location
    California
    Posts
    449
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jeff Lange
    PHP Code:
    echo 'Hello'$_POST['name'], ', and welcome.'
    You'll have to excuse me if this question is completely foolish , but do all these rules with concatenation and speed improvement only apply with when a string when evaluated through an output command like echo, or is time improved by microseconds in all cases of this also:
    PHP Code:
    $string 'My name is ' $username ', what is yours?'
    And then if this variable were placed into HTML. (and the 'comma' probably would have to be replaced with a 'dot' also *I think*, since it's not being echo'd.....)

  4. #104
    Database Jedi MattR's Avatar
    Join Date
    Jan 2001
    Location
    buried in the database shell (Washington, DC)
    Posts
    1,107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It only works on echo.

    P.S. the 'performance' increase is so low it probably isn't worth worrying about.

  5. #105
    Non-Member Icheb's Avatar
    Join Date
    Mar 2003
    Location
    Germany
    Posts
    1,474
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It only works with echo because echo supports multiple arguments.
    If you use

    PHP Code:
    echo 'bla' 'bla2' 'bla3'
    it just outputs the three strings one after the other.

    However, if you use

    PHP Code:
    echo 'bla' 'bla2' 'bla3'
    it first concatenates (combines) the strings into one and then sends them to the browser. This is useless processor overhead, so the first approach is faster.

    By the way, I don't understand the purpose of this argument of yours:

    $string = 'My name is ' , $username , ', what is yours?';

    And then if this variable were placed into HTML. (and the 'comma' probably would have to be replaced with a 'dot' also *I think*, since it's not being echo'd.....)
    This can't work, the string has to be concatenated in order to store it. The purpose of the variable's content doesn't matter. And with the sentence

    "and the 'comma' probably would have to be replaced with a 'dot' also" ,

    you are "disarming" your own argument, because you realized it wouldn't work.

  6. #106
    ********* Member website's Avatar
    Join Date
    Oct 2002
    Location
    Iceland
    Posts
    1,238
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah well, old post, outdated, I do use a database class now that I pass around to those objects that need it which are infact incredebly few.

    Off Topic:

    Object orianted programming really is the best way to program (I have seen the light). And adding custom syntax to templates is just really cool


    And now small tip in the end so this post won't be deleted:
    Try not to put queries into loop, with proper use of mysql joins and other functions you can almost always avoid it.
    - website

  7. #107
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    New to Database Design and Anaylsis ? Unsure on what Database Normalisation means ?

    Umm... Learn the basic 3 forms of database normalisation by reading this PDF file from OReilly; Fair enough it's Java though Database Design and Analysis is platform neutrol folks...

    http://www.oreilly.com/catalog/javad...apter/ch02.pdf

    Enjoy

  8. #108
    SitePoint Evangelist Daijoubu's Avatar
    Join Date
    Oct 2002
    Location
    Canada QC
    Posts
    454
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I got mixed results when using Turck MMCache and single/double quotes...
    Double is sometimes faster when there's less variables (like 1 or 2)
    If anyone have PHPA, Zend Optimizer/Perf Suit, Turck MMCache, could you please run this:
    PHP Code:
    <table border="1" cellspacing="1" cellpadding="3">
    <tr><td>function</td><td>ttime</td><td>avg</td></tr>
    <?php
    set_time_limit
    (0);
    function 
    getmicrotime() {
        
    $mtime explode (' 'microtime());
        return 
    $mtime[1] + $mtime[0];
    }
    function 
    endtimer($name$starttime) {
        global 
    $limit;
        
    $endtime getmicrotime();
        
    $ttime $endtime $starttime;
        echo 
    '<tr><td>',$name,'</td><td>',sprintf('%.4f'round($ttime4)),'</td><td>',sprintf('%.10f'round(($ttime/$limit), 10)),"</td></tr>\n";
    }
    $limit 400000;
    $test '';
    $var1 'foo';
    $var2 'bar';
    $var3 'foobar';
    echo 
    'Iterations: ',$limit," times\n";

    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf '.$var1;
    }
    endtimer('\'asdf \'.$var1'$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf $var1";
    }
    endtimer('"asdf $var1"'$start);
    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf '.$var1.' '.$var2;
    }
    endtimer('\'asdf \'.$var1.\' \'.$var2'$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf $var1 $var2";
    }
    endtimer('"asdf $var1 $var2"'$start);
    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf '.$var1.' '.$var2.'
    '
    ;
    }
    endtimer('\'asdf \'.$var1.\' \'.$var2.\'<br>\''$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf $var1 $var2\n";
    }
    endtimer('"asdf $var1 $var2\n"'$start);
    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf '.$var1.' '.$var2.' '.$var3;
    }
    endtimer('\'asdf \'.$var1.\' \'.$var2.\' \'$var3'$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf $var1 $var2 $var3";
    }
    endtimer('"asdf $var1 $var2 $var3"'$start);
    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf 10$ '.$var1;
    }
    endtimer('\'asdf 10$ \'.$var1'$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf 10$ $var1";
    }
    endtimer('"asdf 10$ $var1"'$start);
    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf 10$ '.$var1.' '.$var2;
    }
    endtimer('\'asdf 10$ \'.$var1.\' \'.$var2'$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf 10$ $var1 $var2";
    }
    endtimer('"asdf 10$ $var1 $var2"'$start);
    //=========================================================
    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test 'asdf 10$ '.$var1.' '.$var2.'
    '
    ;
    }
    endtimer('\'asdf 10$ \'.$var1.\' \'.$var2.\'<br>\''$start);

    $start getmicrotime();
    for (
    $i=0$i<$limit$i++) {
        
    $test "asdf 10$ $var1 $var2\n";
    }
    endtimer('"asdf 10$ $var1 $var2\n"'$start);
    //=========================================================
    ?>
    </table>
    And post back the results
    I attached my results with PHP4.3.3, Turck MMCache2.3.23 under a P3 667Mhz

    Edit: Dmitry answered over here
    Attached Files Attached Files
    Last edited by Daijoubu; Sep 1, 2003 at 05:46.

  9. #109
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Good first post. This answers very many beginner's questions.

    I'm not sure if it's good to recommend E_ALL & E_NOTICE though - although I note you only say this is a minimum.

    & E_NOTICE doesn't catch undefined variable/index errors, which can be a big security risk with reg globs on (in a shared environment you might be stuck with that).

    If a hacker has bombarded your script with a bunch of vars which are declared with reg globs there are three options.

    One: these variables aren't native to your script. They sit around doing nothing.

    Two: the hacker has guessed some valid var names and his hacked vars are declared right at the start of the script. A few lines down, the script declares your own values for the vars, overwriting the hacked values. Once again, they do nothing.

    Three: you have undefined vars/indexes. You're porked.

    Always E_ALL for development..

  10. #110
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by voostind

    By the way, more often than not you can't use foreach, even though it seems nice. When
    doing this:

    PHP Code:
    foreach ($array as $key => $value) { ... } 
    $key and $value become copies of the current array element that changes at each
    iteration of the loop. The problem arises when you store objects (or references) inside an
    array. With foreach you get a copy of every object, and not a reference to it, so
    calling a method on an object that changes its state has no effect. E.g.:

    PHP Code:
    foreach ($objects as $object)
    {
      
    $object->setSomeVariable('someValue');

    This doesn't work! It's extremely sad, but that doesn't make it less true.

    Vincent
    I may not have understood your post fully, but I think you can run a method on an array of objects using a foreach loop:

    PHP Code:
    // test class
    class Test
    {
        var 
    $str// a string
        
        
    function Test()
        {
            
    $this->str 'text';
        }

        function 
    addText()
        {
            
    $this->str .= ' & more text';
        }
    }

    $ob = new Test();
    echo 
    'before foreach $ob->str == ' $ob->str '<br />';

    // assign key/value with referencing ( =>& )
    $array = array('ob'=>&$ob);

    foreach (
    $array as $key=>$value)
    {
        
    // $value->addText(); won't change the original object but this will (if the object $array element was assigned by reference):
        
    $array[$key]->addText();
    }

    echo 
    'after foreach $ob->str == ' $ob->str '<br />'

  11. #111
    SitePoint Member
    Join Date
    Sep 2003
    Location
    St. Louis, MO
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DR_LaRRY_PEpPeR
    use nl2br() to convert newlines to HTML <br /> tags
    The time of nl2br has passed: it provides no structure to the content it transforms. What we need now is a line2p function.

  12. #112
    SitePoint Evangelist Daijoubu's Avatar
    Join Date
    Oct 2002
    Location
    Canada QC
    Posts
    454
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have found something
    strstr is faster than strpos is the strinf can't be found (tested with a 1787bytes long string)
    So...use strpos if most of the time it returns true and strstr if false
    (Also make sure to use !== false, === true doesn't have the same behavior)

  13. #113
    masquerading Nick's Avatar
    Join Date
    Jun 2003
    Location
    East Coast
    Posts
    2,215
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great thread, I have one question about the line breaks, though. I have been using nl2br() to insert BR before the data gets inserted in the DB, which worked well, but posed a problem when wanting to edit data. How do I use nl2br() to place <br> when displaying the data, but not actually inserting <br> into a DB table?

    Thanks!

    EDIT: Or if you think /n or something else is more appropiate, then use that.

  14. #114
    SitePoint Evangelist Daijoubu's Avatar
    Join Date
    Oct 2002
    Location
    Canada QC
    Posts
    454
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Keep in mind that nl2br adds <br /> to newlines and doesn't replace them
    Speed & scalability in mind...
    If you find my reply helpful, fell free to give me a point

  15. #115
    ********* Member website's Avatar
    Join Date
    Oct 2002
    Location
    Iceland
    Posts
    1,238
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The newlines will be in the database, don't worry about that.
    To display it, I suppose you do something like:
    PHP Code:
    echo $text 
    right?
    Well, if so, then simply add the nl2br() around it, something like this:
    PHP Code:
    echo nl2br($text); 
    Off Topic:

    And new line is \n not /n
    - website

  16. #116
    SitePoint Member Anguz's Avatar
    Join Date
    Dec 2003
    Location
    Taxco, Mexico
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    to echo big chunks of html with vars in the middle using single quotes, instead of double quotes (slower) or jumping in and out of php, even if using shorthand, I do it like this

    PHP Code:
    echo '
       Hello,<br />
       My name is '
    ,$name,' ',$lastname,' and am ',$age,' years old.<br />
       I live in '
    ,$city,', ',$country,' since I was born.<br />
       You can contact me at '
    ,$email,' or by phone at ',$phone,'<br />
       Regards,<br />
       '
    ,$name,' ',$lastname,'<br />
    '

    it's very shorthand and fast... it can be very comfortable to use in a simple php template system

    ---

    regarding strpos(), remember to use it with !== false for positive and === false for negative, it not, it can behave incorrectly for you... example

    PHP Code:
    if(strpos('abc''a'))
       echo 
    'true';
    else
       echo 
    'false'
    it'll echo false because 'a' is in position 0, which computes as false... if you use (strpos('abc','a') !== false) it works correctly

    ---

    to avoid globalizing variables inside functions and also not have specify each var in the function call, use only one, but make it an array... like this

    PHP Code:
    $arr['var1'] = $var1;
    $arr['var2'] = $var2;
    $arr['var3'] = $var3;
    myFunction($arr); 
    if you want to pass more vars to the function in the future, it's very easy to add more elements to the array, and easier to read and you don't have to remember the order in which you input the vars

    ---

    I'm still learning php, so if I'm wrong in any of those, please correct me! I'm eager to learn

  17. #117
    ********* Member website's Avatar
    Join Date
    Oct 2002
    Location
    Iceland
    Posts
    1,238
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Anguz
    to avoid globalizing variables inside functions and also not have specify each var in the function call, use only one, but make it an array... like this

    PHP Code:
    $arr['var1'] = $var1;
    $arr['var2'] = $var2;
    $arr['var3'] = $var3;
    myFunction($arr); 
    if you want to pass more vars to the function in the future, it's very easy to add more elements to the array, and easier to read and you don't have to remember the order in which you input the vars

    ---

    I'm still learning php, so if I'm wrong in any of those, please correct me! I'm eager to learn
    Well, I never put all the variables inside an array before I pass them to the function mainly because of two things:
    Then it is more complicated to put some default value to the variables and
    If I forget to pass a variable to function it results in error, if I would put the variables inside an array I would have to check every element to see if it is set etc.

    Then I disagree with what you say that it becomes more readable. I think it becomes unclear what variables the function needs if you place all variables inside an array.

    Then again you seldom need to pass so many variables to a function that the code becomes hard to read.

    Feel free to disagree...
    - website

  18. #118
    SitePoint Member Anguz's Avatar
    Join Date
    Dec 2003
    Location
    Taxco, Mexico
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, I never put all the variables inside an array before I pass them to the function mainly because of two things:
    Then it is more complicated to put some default value to the variables and
    If I forget to pass a variable to function it results in error, if I would put the variables inside an array I would have to check every element to see if it is set etc.

    Then I disagree with what you say that it becomes more readable. I think it becomes unclear what variables the function needs if you place all variables inside an array.

    Then again you seldom need to pass so many variables to a function that the code becomes hard to read.

    Feel free to disagree...
    hmm.. I see what you mean... but I don't really feel that checking that all the needed array elements are there, is harder than checking you're passing all the variables separately, or globalizing them all inside... it's just different

    what's more, you won't have a change in names because the vars inside are different than the var names outside... also if there's some vars you frequently used, you can have them already in an array and then copy the array and add the missing ones for the particular function you will use it

    I don't know how to set a default value for an array element if it's not passed, but if there isn't a way, then, I'd use the array and another variable for that

  19. #119
    SitePoint Enthusiast JoeRags's Avatar
    Join Date
    Jan 2004
    Location
    Delete Account
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by torrent
    I think it should be noted that you cannot single quote escaped characters you want the parser to recognise. For example
    PHP Code:
    <?php
    print "There is a newline between this text\nand this text\n";
    print 
    'Now see what happens\nwhen you do this!';
    ?>
    I agree it is good practice to use single-quotes where possible, although find it slightly more difficult to believe the performance difference in everyday PHP programming is really that noticeable.
    Very true.

    You can try:

    PHP Code:
    print chr(9) . 'tab followed by a ' chr(10) . ' new line.'
    http://www.asciitable.com/

  20. #120
    SitePoint Enthusiast JoeRags's Avatar
    Join Date
    Jan 2004
    Location
    Delete Account
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try not to use useless comments.

    For example:

    PHP Code:
    // Connect to MySQL database
    $link mysql_connect('host''user''password');

    // Select database
    mysql_select_db('database'$link);

    $result mysql_query('SELECT id, name FROM employees'$link);

    // Loop through each row and print the contents
    while ($row mysql_fetch_row($result))
    {
      print 
    'Name: ' $row[1] . '<br />Title: ' $row[2] . '<br /><br />';
    }

    // Close database connection
    mysql_close($link); 
    The above comments aren't necessary.

    Regular expressions are one area that I think commenting is useful. Unfortunately it seems like some kind of trend to comment like above while leaving the following code without comments.

    For example, instead of:

    PHP Code:
    $expression '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$'
    Try:

    PHP Code:
    $expression '^' ;
    // One or more underscore, alphanumeric, or hyphen characters.
    $expression .= '[_a-z0-9-]+';
    // Followed by zero or more sets consisting of a period and one or more 
    // underscore, alphanumeric, or hyphen characters.
    $expression .= '(\.[_a-z0-9-]+)*';
    // Followed by an 'at' character.
    $expression .= '@';
    // Followed by one or more alphanumeric or hyphen characters.
    $expression .= '[a-z0-9-]+';
    // Followed by one or more sets consisting of a period and two or more 
    // alphanumeric or hyphen characters.
    $expression .= '(\.[a-z0-9-]{2,})+';
    $expression .= '$'

  21. #121
    Non-Member Icheb's Avatar
    Join Date
    Mar 2003
    Location
    Germany
    Posts
    1,474
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excessive comments is indeed a problem. The idea is to explain what a code block does, the idea behind it, and not a single command, because those can be looked up in reference manuals. Of course, the exception of regular expressions is valid, because they combine an idea and a single command.

  22. #122
    SitePoint Wizard samsm's Avatar
    Join Date
    Nov 2001
    Location
    Atlanta, GA, USA
    Posts
    5,011
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by JoeRags
    Regular expressions are one area that I think commenting is useful.
    ...
    You are correct, and there is actually a feature built into perl regex (preg_whatever) to deal with this which might be less cumbersome than combining strings. Use /x at the end of the expression and whitespace and comments are ignored.
    PHP Code:
    $expression '
    /^          
    [_a-z0-9-]+        # One or more underscore, alphanumeric, or hyphen characters.
    (\.[_a-z0-9-]+)*   # zero or more sets consisting of a period and one or more 
                       # underscore, alphanumeric, or hyphen characters.
    @                  # at character
    [a-z0-9-]+         # one or more alphanumeric or hyphen characters
    (\.[a-z0-9-]{2,})+ # one or more sets consisting of a period and 
                       # two or more alphanumeric or hyphen characters.
    $/x                # end
    '
    ;

    if ( 
    preg_match($expression$whatever) ) // the /x thing doesn't work with ereg
    { } 
    One advantage to this is that you can swap lines around really easily.

    There's all kinds of indenting that can be done too...

    Code:
    (				# begin grouping
    	\.			# one period
    	[_a-z0-9-]+		# one or more \d
    )*   				# end group; match zero or more of group
    Good times. In an article about ideas for Perl 6, Larry Wall mentioned that /x should be default in future regex implementations.
    Using your unpaid time to add free content to SitePoint Pty Ltd's portfolio?

  23. #123
    SitePoint Member joshg678's Avatar
    Join Date
    Jun 2004
    Location
    Home
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if you get errors when including a page it may be the way your doing it, i have had different results with different includes, ex:
    PHP Code:
    <? inlucde "file"?>
    <? 
    include 'file'?>
    <? 
    include('file'); ?>
    I some times get different results when useing different ones, depends on the script, or file your includeing, same goes for requires, and require_once
    PHP Code:
    <? require 'file'?>
    etc
    http://www.thrillnerds.com
    http://www.joshrcc.com
    http://kazaa.joshrcc.com

  24. #124
    SitePoint Enthusiast
    Join Date
    Jun 2004
    Location
    Montreal
    Posts
    88
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In regard to joshq678's post : you should *always* use the parenthesised and double quoted versions of include, include_once, require and require_once, especially on windows installations where these bugs occur.

    Quick tips :
    Never forget to use mysql_escape_string() when storing data into a database, to avoid SQL injection attacks:
    Code:
    $sql="SELECT * FROM table WHERE username='";
    $sql.=mysql_escape_string($username)."'";
    What are sql injection attacks ?
    Remember that a malicious user can change any input to anything (number, string, etc). Many sites have some type of user login (username password) and they check it against a database of usernames and passwords with a mysql query like this:
    Code:
    "SELECT COUNT(*) FROM USERLIST WHERE USER='$user' AND PASS='$password'";
    If the result is 0, the login fails, if the result is 1, the login passes. What would happen if $user contained "admin';#"'. The query would now read
    Code:
    "SELECT COUNT(*) FROM USERLIST WHERE USER='admin';# AND PASS='$password'";
    The semicolon denotes the end of a query, and the # means the rest of the line is a comment. Thus, it doesn't matter what password was entered, the query returns 1 row - access granted.

    Worse yet, what if user contained the string "';$query="DROP DATABASE db" (all data deleted) :
    Code:
    $query="SELECT COUNT(*) FROM USERLIST WHERE USER='admin'"; $query="DROP DATABASE db";
    The easy way to prevent this is to use the mysql_escape_string() function to prevent strings from breaking out of the query and doing damage.
    Ful explanation : http://www.sitepoint.com/article/794

    Also, a lot of begginers wonder how to have VARIABLE variable names (variable who's naming depends on another variable).
    This is achieved by doing the following :
    Code:
    $var_name="louis";
    $$var_name="Variable content.";
    
    //This will set $louis="Variable content."
    
    $var_name="supervar";
    $$var_name="Variable content.";
    
    This will set $supervar="Variable content."
    You can also have variable function names :
    Code:
    $funct_name="louis";
    function $funct_name {
    //...
    }
    
    //This is the same as :
    
    function louis {
    //...
    }
    As stated on the first page, consider using str_replace instead of the preg_replace or ereg_replace functions. The only reason why you would use preg_replace or ereg_replace functions would be that you REALLY need to use regular expressions. Also, as of PHP 4.0.5, every parameter in str_replace() can be an array, so theres no excuse to use preg or ereg fucntions when replacing simpel strings anymore.

    A useful use of str_replace() :
    Code:
    $string="The quick brown fox jumps over the lazy dog.";
    $patterns[0] = "quick";
    $patterns[1] = "brown";
    $patterns[2] = "fox";
    
    $replacements[0] = "slow";
    $replacements[1] = "black";
    $replacements[2] = "bear";
    
    $string=str_replace($patterns, $replacements, $string);
    
    //$string="The slow black bear jumps over the lazy dog."
    SESSIONS
    A lot of beginners complain that their session variables don't get passed from page to page.
    Always use session_start(); at the beginning of each page to be able to retrieve session vars from the superglobal array $_SESSION

    HEADERS
    Consider the following:
    Code:
     <?php
    header("Location: index.html");
    ?>
    This will output a warning: headers already sent.
    Where's the mistake ?
    Look closer.
    Closer!
    It's the little blank space before the <?php tag ! Always send headers at the VERY beginning of the page.

    GLOBALS
    Remember that variables that are not in a function may NOT be accessed by a function unless you explicitly declare it as global with the global keyword :
    Code:
    // WRONG !
    $tax = 0.05;
    
    function compute_price( $price )
    {
    return ($price + ($price * $tax));
    }
    
    // right !
    $tax = 0.05;
    
    function compute_price( $price )
    {
    global $tax;
    return ($price + ($price * $tax));
    }
    OPTIMIZATION TIPS :
    1) Don't use a regex if you don't have to, instead, use PHP’s string manipulation functions. For example:

    Code:
    BAD: <? $new = ereg_replace("-","_",$str); ?>
    
    GOOD:<? $new = str_replace("-","_",$str); ?>
    
    BAD: <? preg_match('/(\..*?)$/',$str,$reg);?>
    
    GOOD:<? substr($str,strrpos($str,'.')); ?>
    2) No references. Usually it is not faster to use references because of PHP's copy-on-write nature.

    3) Use Persistent Database connections. Some databases are slower than others at establishing new connections, and the slower the database, the more of an impact using persistent connections will have. Keep in mind, however, that persistent connections will use resources even when not in use.

    4) Take a look at MySQL unbuffered query. If you’re using MySQL, check out mysql_unbuffered_query(). You use it exactly like you would mysql_query(), the difference is that instead of waiting for the entire query to finish and storing the result in the client API, an unbuffered query makes results available as soon as possible and they are not allocated in the client API. You get access to your data quicker and use a lot less memory. But you can't use mysql_num_rows() on the result resource and it is likely to be slightly slower for small selects.

    5) Keep it simple. Don't over-architect things. If your solution seems complex to you, there is probably a simpler and more obvious approach.

    Happy PHP'ing

  25. #125
    SitePoint Member joshg678's Avatar
    Join Date
    Jun 2004
    Location
    Home
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if your making a wehosting company, and would like to let the users know what your server load is and how long the server has been up you can use these codes that work

    server load
    PHP Code:
    <?php
        $loadavg_array 
    explode(" "exec("cat /proc/loadavg"));
        
    $loadavg $loadavg_array[2];
        print(
    "[ Server load: " $loadavg " ]");
    ?>
    Uptime
    PHP Code:
    <?php 

    $uptime 
    shell_exec("cut -d. -f1 /proc/uptime"); 
    $days floor($uptime/60/60/24); 
    $hours $uptime/60/60%24
    $mins $uptime/60%60
    $secs $uptime%60

    echo 
    "This server has been up $days days $hours hours $mins minutes and $secs seconds"

    ?>
    http://www.thrillnerds.com
    http://www.joshrcc.com
    http://kazaa.joshrcc.com


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •