...

View Full Version : Most useful PHP built in function



funnymoney
05-08-2009, 11:50 AM
Almost any PHP programmer knows that thing which makes PHP so beautiful is it's vast collection of predefined functions. After one who is learning PHP figures out how to handle basic control structures like if, switch, for, while, etc.., he is ready to write his first fun and useful code blocks.

Most of the time code blocks include PHP built in functions. Those built in functions allow programmer to avoid writing code for some of the usual problems, like knowing length of string (for registration validation), knowing array values, or just simple data manipulation with using explode or implode.

Even though most of these predefined function can be written by programmer, usually writing them is just silly waste of time.

I wrote this post to see what are those predefined functions you find most useful, and to write and explain some of those that i find irreplaceable. Order of functions has nothing to do with their "values".

function_exists() - is used to check weather a called function exists. it is very nice to use it when you have some kind of script that calls function based on some variable value (eg. $_GET or $_POST vars). something that brings this function to action is when using it with variable functions, then it shines like you crazy diamond..
eg code:

function callFunc($var, $funcneeds) {
if (function_exists($var)) {
return $function($funcneeds);
}
else {
return 0;
}
}
Above code is simple function that check weather function named $var exists, and if it does it calls it, if it doesn't exist function returns false

in_array() - arrays, arrays, arrays.. can't do nothing without arrays. this function checks weather certain variable exists in certain array, in case it does it returns true. eg, checking for cookie val


$cookies = array();
$cookie = $_COOKIE['user']; $i=0;
while ($row = mysql_fetch_assoc($result)) {
$cookies[$i] = $row['salt'];
$i++;
}
if (in_array($cookie, $cookies)) {
return 1;
}
else {
return 0;
}
above function checks weather cookie your user has is salt you need to use to login to your website ;)

strlen() - strlen returns string lenght. it's most useful when you need to check for some posted value.. nobody wants usernames shorter than 3 chars, so you can use this function to check it

eg

$username = $_POST['username'];
if (strlen($username) < 3) {
return "Username not valid";
}


header() - headers are great for redirecting users to certain pages. headers are quite hard to handle (at first) but when you get a hang of it you can use them to redirect users if there has been something that requires redirection. eg, a login to your website was successful and you want to redirect user to their profile page


if ($login == TRUE) {
header("Location: index.php");
}
else {
header("Location: login.php?error=1");
}

preg_(replace, match) - people are sometimes nervous. they get cranky and annoyed by boredom, wife or alcohol. web addicts then go to different pages and act like children, cursing and insulting users. also, some people don't have a life so the spam, and spam until you die. to easily avoid those situations you can use preg_(replace, match) functions.



$userpostedvalue = $_POST['textareavalue'];
if (preg_match("/viagra/", $userpostedvalue)) {
return "For some reason i hate viagra and i forbid you to even mention it";
}


error_reporting() - last but not less valuable is error reporting. please, turn it on if you want to save yourself bunch of hours trying to figure out why your page turns out blank, and it really really should be new twitter ;).


Well, that's all i have to say for now. What are your most usefull PHP built in functions? :)

abduraooft
05-08-2009, 12:07 PM
echo/print() :)

funnymoney
05-08-2009, 12:46 PM
echo/print() :)

what's that :eek:

Iszak
05-08-2009, 12:48 PM
echo/print() :)
As much as I'd like to say that, echo and print are language construct not functions.

funnymoney
05-08-2009, 12:54 PM
As much as I'd like to say that, echo and print are language construct not functions.

it's a string function :D

what would be the "real" difference between a construct and a function?

edit:
php man says

echo() is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo() (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo(), the parameters must not be enclosed within parentheses.

Fou-Lu
05-08-2009, 07:45 PM
Constructs cannot be used as function pointers.

For what you have here, strlen is the most useful function.
function_exists can be avoided by using mutors / suppressors on the function calls.
header is useful only in a specific stream context.
preg_* are useful, but can be handled with standard looping (man that would be a nightmare)
And finally, error reporting can be controlled from the ini or htaccess, so is unnecessary from the PHP script.

Hmm, actually I can't change my votes, but I guess they would be between the strlen and preg_*.

kbluhm
05-08-2009, 08:03 PM
var_dump() as a write-in.

funnymoney
05-10-2009, 02:35 AM
dunno about you guys but it seems to me that you are really more willing to talk about real problems ppl ask here then just chatting about PHP..

Fou-Lu is only one here that answered about funcs i mentioned here.

I just don't understand. What is up with any forum i visit, ppl just aren't friendly as they were before..

Dunno :(

Why don't we just chat a bit, is that to hard??

funnymoney
05-10-2009, 02:40 AM
...

since you are only one here that tried to answer about my doubts, i'll ask you a question..

How can you avoid using preg_match or header.. Just now i'm writing custom CMS, and i use $_SERVER['SOME_VARS_THAT_CAN_HELP_YOU_USE_HTTP_LINKS _TO SHOW CONTENT'], and when that var isn't set properly i just use header to send user to error page...

It doesn't help about 301 or whatever you might have errors, but at least when user types something in http:// that has no sense with page content it sends it to error page..

dunno how to avoid it without using header..

Fou-Lu
05-10-2009, 05:18 AM
Think of PHP more abstract than just the internet.
Passing a 301 from a command line will have no effect. You can also get by without using a header (for this example) by using a meta tag. In other words, header is only really useful in the http context.
Don't get me wrong, header's are quite handy to use, but are by no means required. You can just as easily add a simple error output that states 'Oops, something went wrong, please click back and try again', or something like that. I'd also use the header myself just to clarify that you should by no means avoid using it.

What I was getting at is more along the lines of the approach. The strlen only has one other route to get the length of the string, and thats by counting the char's in the array. This is why I wanted to change my vote to also include the preg_* ones, because it wouldn't be practical to do most of the matching with loops. The other functions have work arounds to avoid if you didn't want to use them.

I didn't mean to get at you shouldn't use these. By no means, in fact I consider strlen, preg_* and header to be some of the most useful built in functions. But if I could only choose two to live with from the ones above, they would be strlen and preg_*.

There are thousands of functions in PHP, and I would consider at minimum at least a hundred of them to actually be indispensable.
Offhand, these are a few I use often (just functions, we'll ignore objects and methods):

is_callable
count, next, reset
substr
call_user_func[_array]
explode / implode
fopen, fread, fwrite, fclose, fseek

and a number of others.
The only ones I probably couldn't live without are the call_user_func_array, file handling and count. Everything else has a fairly easy work around.


Oh yeah, forgot to mention. I left out any constructs as well, so our print's, issets, etc. Those are inherently indispensable.

sea4me
05-10-2009, 06:45 PM
I choose header....

Same reason as funnymoney...:)

funnymoney
05-11-2009, 02:30 PM
sorry guys, i didn't comment this post, friend i know had accident and he's gone now. :( but, anyway it's cycle of life, we come and go, and then who knows.. but to get back on topic..


Think of PHP more abstract than just the internet.
Passing a 301 from a command line will have no effect. You can also get by without using a header (for this example) by using a meta tag. In other words, header is only really useful in the http context.

io looked at the meta tag under w3schools, and see no way how can you use it to avoid 301 errors. and i don't mean about maybe accidentally broken links, but on purpose typed in http:// address ment to generate some kind of error in order to figure out how to hack a website. i also saw .htaccess method on redirecting 301 and other server generated errors, but still would like to make it just PHP


Don't get me wrong, header's are quite handy to use, but are by no means required. You can just as easily add a simple error output that states 'Oops, something went wrong, please click back and try again', or something like that. I'd also use the header myself just to clarify that you should by no means avoid using it.

i use it mostly for "estetic" purposes, so that user who comes to some sort of page that doesn't exist still has a feeling he's on a same website, rather then sending it to some other page that has different look than main website he visited.

only fear i have about using header and i don't know how reasonable that fear is, is when you maybe type in very very long http address, is it possible to somehow "overflow" header and then gain access to something "hacker" shouldn't have access to. maybe htpasswrd or similar things that could couse problems..


What I was getting at is more along the lines of the approach. The strlen only has one other route to get the length of the string, and thats by counting the char's in the array. This is why I wanted to change my vote to also include the preg_* ones, because it wouldn't be practical to do most of the matching with loops. The other functions have work arounds to avoid if you didn't want to use them.

also, like with header, if user inputs something in text field that is controlled by strlen, and like you said strlen is counting chars in array, then when user would input zillions of chars in that field, maybe built in strlen would generate famous "memory to low" (even when memory is 1GB or even more), and while PHP would try to calculate strlen of zillion chars, maybe no other user could have access to website because server is just to busy calculating that array lenght


I didn't mean to get at you shouldn't use these. By no means, in fact I consider strlen, preg_* and header to be some of the most useful built in functions. But if I could only choose two to live with from the ones above, they would be strlen and preg_*.

somehow i feel that even when you limit eg. usernames to have least 3 chars, and someone tries to hack with above scheme typing zillions of chars to couse memory problems, then maybe i could try limiting max chars by using preg_* with those {20}, or similar regular expression so when text field has more than 20 chars it fails same as when it has less then 3.

i'm wondering, again, if somone would type zillions of chars in controlled text field or just input field would PHP then parse whole string and then calculate how long is it, or would it just go, 1,2,3 till 20, and when 20 is reached it would just drop anything more there is there.

also i know there is javascript way, and i think even HTML way of limiting input fields(i'm not sure about HTML way), but even when you ignore those two ways of protection (someone has javascript disabled, or browser doesn't know that input is limited by HTML), will PHP manage to solve that zillion chars long string...


There are thousands of functions in PHP, and I would consider at minimum at least a hundred of them to actually be indispensable.
Offhand, these are a few I use often (just functions, we'll ignore objects and methods):
nice, next(), never used it, but i can see how it could make me pagination script much simpler :)

others you mentioned i used often except call_user_func[_array]. i took a peek at PHP manual, but can't see real life problem where i could use it. probably my app(s) didn't get so far.

and about classes, methods, and objects, and their constructs i did use construct, just on this last project. i used it to load language and template, but then i had to save that project on server that was powered by PHP 4.?.? and of course, had few days delay when server admins had to change to php 5, and then again problems appeared because now i have to use .php extension couse when i don't use it and rewrite it, server uses PHP 4.. Odd problem i must admit, but they have no idea how to fix it (by they i mean one guy who is contact support, admin, seller, programmer, and designer), lol..

rest about classes and objects i can say is that i do use them, but i don't see that much advantages, because my projects start with classes to load templates, and template dynamic info like meta data, title, css etc. but when it comes to loading content, this function_exists built in function is "switch" to procedural functions to load data. maybe i don't think abstract enough to create fully OOP project, maybe i don't have that much experience, but creating procedures is a bit simpler to me then creating extended classes and stuff that should be done when programming OOP way.

although i did started to see patterns in those procedures, and most of them are SQL calls, that differ only in names of tables and fields procedure should use.

i did read this IBM going dynamic with PHP (http://www.ibm.com/developerworks/xml/library/os-php-flexobj/) article, and it states that same problem i have. and that is dynamic class i would like to create for my php projects so i can create and extend them faster then writing SQL code again and again for any feature project has, but when i tried to figure it out, i just can't.. maybe a bit help..

author did state this

Before I get into all that, however, here's a word of caution: This article is about the use of very advanced OOP features in PHP V5 -- the kind of features you won't necessarily need in every application. Also, the kind of features that will be difficult to understand if you don't have a solid grounding in OOP and at least a beginner's knowledge of PHP object syntax.

Fou-Lu
05-11-2009, 04:44 PM
o.O
Reading that may have given me a stroke.

I wouldn't worry too much about you're overflow problems. I have a feeling that the browser would take the brunt of the beating, not to mention that PHP is generally limited in the amount of memory its allocated to consume. I never said that strlen was used for user input btw, for that you should look at other options like sscanf. You can also implement post limits through PHP and apache (I assume IIS as well, but I cannot confirm on that, sorry), to help with floods.
call_user_func_array is a very convenient function. Unlike using variable functions (ie, function pointing with: $result = $myFunc($arg1);), when tossing a func_get_args() call to a variable function, its interpreted as an actual array for a single parameter. You have to push it into the call_user_func_array to keep the variable (as in changing, not a programming variable) parameters available.

Thats all for now. That long post is making me fall asleep after work >.<. Make the next one shorter please :D



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum