PHP Functions every beginner should know.

riversiderocks

RiversideRocks

Posted on August 8, 2020

PHP Functions every beginner should know.

PHP is one of the most popular languages for building websites. In fact, you probably used it today if you visited a Wordpress site or Facebook.

Here are a few useful built in PHP functions every developer should use more often.

1 - htmlspecialchars

The htmlspecialchars function is better than than using only using echo for one main reason: it prevents XSS. For example:

<?php

echo htmlspecialchars("<script>console.log('XSS!');<script>");
Enter fullscreen mode Exit fullscreen mode

Output:

&lt;script&gt;console.log('XSS!');&lt;script&gt;gt;
Enter fullscreen mode Exit fullscreen mode

2 - exec

This function allows you to run code on the command prompt or terminal, depending what OS you use to host/test. While this function is a bit more advanced, it is very useful. Example:

<?php

exec("mkdir files");
Enter fullscreen mode Exit fullscreen mode

Upon running this code, a folder will be created called files. This is a very powerful command, and user input NEVER be allowed in this function.

3 - header

HTTP headers are very useful online, they tell your browser what to do when a website is loaded. You can use PHP to set headers in seconds. This code will set the 302 Found header, creating a redirect to riverside.rocks:

<?php
header("Location: https://riverside.rocks");
die();
Enter fullscreen mode Exit fullscreen mode

Upon viewing this with cURL, we can see it worked.
Alt Text

Note: The die() function is used to end the code, it is not necessary, but good to use to ensure no more code is executed after the redirect.

This is an example of a 404:

<?php
header("HTTP/1.1 404 Not Found");
Enter fullscreen mode Exit fullscreen mode

4 - file_get_contents

This function retrieves the HTML contents of a website. If you ever work with APIs in PHP, you will have to use this function quite a bit. This example gets and echos the HTML contents of riverside.rocks:

<?php
echo file_get_contents("https://riverside.rocks");
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed reading and keep coding!

~ Riverside Rocks

💖 💪 🙅 🚩
riversiderocks
RiversideRocks

Posted on August 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related