Tutorials PHP Custom PHP functions

Custom PHP functions

Today you will learn how to create your own custom PHP functions.

Create your own function

PHP reads from top to bottom. The actual function has to be above whatever you're calling. To create a custom function, you need to create a custom variable for the function to use; this variable will be whatever you send to the function. When you're finished with the function, you need to return the variable which is the result.

function preventxss($content) {
  $content = htmlEntities($content, ENT_QUOTES);
  return $content;

$content = '<script>alert("I hacked your site!");</script>';
$content = preventxss($content);

// Produces &lt;script&gt;alert(&quot;I hacked your site!&quot;);&lt;/script&gt;
echo $content;

What can I do in functions?

Anything you can do with the default PHP. You can trim, replace, match and anything else that's available in PHP. You can even call a custom function from another custom function that's below it.

Why do I need this when I can do it with default PHP?

It's like an included file to keep things simple. You might need to filter your content or have something against injections. Wouldn't it be simpler if you could keep them all in one place? It prevents redundent code that you would otherwise have to type again and again.

Anything to look out for?

Don't assign a function name that already exists. If you create a function called htmlEntities, PHP might get confused. PHP will probably use your function, but it might still create errors.

That ends today's lesson. Add a few functions that you regularly use, put it in an included file, and put it at the top of every page that will use those functions. See you all next time.

Posted by on . Category: PHP


No comments posted yet

You need to register or login to post new comments.