you could also do:Originally Posted by cyborg from dh
PHP Code:<?php
define('NL', "\n");
echo 'first line' . NL . 'second line';
?>
| SitePoint Sponsor |
you could also do:Originally Posted by cyborg from dh
PHP Code:<?php
define('NL', "\n");
echo 'first line' . NL . 'second line';
?>
PHP is almost as sexy as me!!


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



You'll have to excuse me if this question is completely foolishOriginally Posted by Jeff Lange
, 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:
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.....)PHP Code:$string = 'My name is ' , $username , ', what is yours?';





It only works on echo.
P.S. the 'performance' increase is so low it probably isn't worth worrying about.![]()
Matt - Sybase DBA / PHP fanatic
Sybase/MySQL/Oracle | I don't like MySQL
Download Sybase | DBForums.com - for all your RDBMS talk
It only works with echo because echo supports multiple arguments.
If you use
it just outputs the three strings one after the other.PHP Code:echo 'bla' , 'bla2' , 'bla3';
However, if you use
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.PHP Code:echo 'bla' . 'bla2' . 'bla3':
By the way, I don't understand the purpose of this argument of yours:
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$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.....)
"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.





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





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![]()



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:
And post back the resultsPHP 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($ttime, 4)),'</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>
I attached my results with PHP4.3.3, Turck MMCache2.3.23 under a P3 667Mhz
Edit: Dmitry answered over here![]()
Last edited by Daijoubu; Sep 1, 2003 at 05:46.





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..





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:Originally Posted by voostind
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 />';
The time of nl2br has passed: it provides no structure to the content it transforms. What we need now is a line2p function.Originally Posted by DR_LaRRY_PEpPeR



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)





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.



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





The newlines will be in the database, don't worry about that.
To display it, I suppose you do something like:right?PHP Code:echo $text
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
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
it's very shorthand and fast... it can be very comfortable to use in a simple php template systemPHP 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 />
';
---
regarding strpos(), remember to use it with !== false for positive and === false for negative, it not, it can behave incorrectly for you... example
it'll echo false because 'a' is in position 0, which computes as false... if you use (strpos('abc','a') !== false) it works correctlyPHP Code:if(strpos('abc', 'a'))
echo 'true';
else
echo 'false';
---
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
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 varsPHP Code:$arr['var1'] = $var1;
$arr['var2'] = $var2;
$arr['var3'] = $var3;
myFunction($arr);
---
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:Originally Posted by Anguz
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
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 differentWell, 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...
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
Very true.Originally Posted by torrent
You can try:
http://www.asciitable.com/PHP Code:print chr(9) . 'tab followed by a ' . chr(10) . ' new line.';
Try not to use useless comments.
For example:
The above comments aren't necessary.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);
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:
Try:PHP Code:$expression = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$';
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 .= '$';
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.





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.Originally Posted by JoeRags
One advantage to this is that you can swap lines around really easily.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
{ }
There's all kinds of indenting that can be done too...
Good times. In an article about ideas for Perl 6, Larry Wall mentioned that /x should be default in future regex implementations.Code:( # begin grouping \. # one period [_a-z0-9-]+ # one or more \d )* # end group; match zero or more of group
Using your unpaid time to add free content to SitePoint Pty Ltd's portfolio?
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:
I some times get different results when useing different ones, depends on the script, or file your includeing, same goes for requires, and require_oncePHP Code:<? inlucde "file"; ?>
<? include 'file'; ?>
<? include('file'); ?>
etcPHP Code:<? require 'file'; ?>
http://www.thrillnerds.com
http://www.joshrcc.com
http://kazaa.joshrcc.com
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:
What are sql injection attacks ?Code:$sql="SELECT * FROM table WHERE username='"; $sql.=mysql_escape_string($username)."'";
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:
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 readCode:"SELECT COUNT(*) FROM USERLIST WHERE USER='$user' 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.Code:"SELECT COUNT(*) FROM USERLIST WHERE USER='admin';# AND PASS='$password'";
Worse yet, what if user contained the string "';$query="DROP DATABASE db" (all data deleted) :
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.Code:$query="SELECT COUNT(*) FROM USERLIST WHERE USER='admin'"; $query="DROP DATABASE db";
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 :
You can also have variable function names :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."
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.Code:$funct_name="louis"; function $funct_name { //... } //This is the same as : function louis { //... }
A useful use of str_replace() :
SESSIONSCode:$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."
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:
This will output a warning: headers already sent.Code:<?php header("Location: index.html"); ?>
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 :
OPTIMIZATION TIPS :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)); }
1) Don't use a regex if you don't have to, instead, use PHP’s string manipulation functions. For example:
2) No references. Usually it is not faster to use references because of PHP's copy-on-write nature.Code:BAD: <? $new = ereg_replace("-","_",$str); ?> GOOD:<? $new = str_replace("-","_",$str); ?> BAD: <? preg_match('/(\..*?)$/',$str,$reg);?> GOOD:<? substr($str,strrpos($str,'.')); ?>
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![]()
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
UptimePHP Code:<?php
$loadavg_array = explode(" ", exec("cat /proc/loadavg"));
$loadavg = $loadavg_array[2];
print("[ Server load: " . $loadavg . " ]");
?>
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