DEV Community

Ricardo Sawir
Ricardo Sawir

Posted on • Originally published at ricardosawir.Medium

9 Useful PHP Tips and Code Snippets That Get The Jobs Done

Hi friends, my name is Ricardo Sawir. Follow and subscribe if you like to get more updates on what I make:

Okay, I think that's enough 😁 I collect these tips and code snippets mostly from the awesome communities in StackOverflow. This code snippets and advice works but not limited from PHP 5 to PHP 8. I curate this myself and use it firstly for my job.

I don't claim any of these code snippets or tips written here as mine. The credits goes to the respective authors. All of these tips and code snippets are collected by me that I see as "useful" for me and I hope you find them useful, too.

If you find any errors, probably a typo from me, please let me know at my email (you can find at the bottom).

So, let's jump directly to our 1st tip!

1. Use Prepared Statements if you are working with database to prevent SQL injection

Source: https://stackoverflow.com/a/60496/9478774

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute([ 'name' => $name ]);

foreach ($stmt as $row) {
    // Do something with $row
}
Enter fullscreen mode Exit fullscreen mode

This is to set up the connection, you can copy paste this:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Enter fullscreen mode Exit fullscreen mode
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');

$preparedStatement->execute([ 'column' => $unsafeValue ]);
Enter fullscreen mode Exit fullscreen mode

2. Prepared Statements for dynamic queries? Restrict the possible values by using if else

Source: https://stackoverflow.com/a/60496/9478774

if (empty($dir) || $dir !== 'DESC') {
   $dir = 'ASC';
}
// only 2 possible options
Enter fullscreen mode Exit fullscreen mode

3. Check if a string contains a specific word

Source: https://stackoverflow.com/a/4366748/9478774

// @ver below 8
$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo TRUE;
}

// @ver 8
if (str_contains('How are you', 'are')) {
    echo TRUE;
}
Enter fullscreen mode Exit fullscreen mode

4. Handle undefined index/offset with array_key_exists() or isset()

Source: https://stackoverflow.com/a/4261200/9478774

//isset()
$value = isset($array['my_index']) ? $array['my_index'] : '';
//array_key_exists()
$value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
Enter fullscreen mode Exit fullscreen mode

5. When you want to get the value of $_POST or $_GET or $_REQUEST, you can use isset() or !empty()

Source: https://stackoverflow.com/a/4261200/9478774

$value = isset($_POST['value']) ? $_POST['value'] : '';
//empty()
$value = !empty($_POST['value']) ? $_POST['value'] : '';

//for PHP 7 and later
$value = $_POST['value'] ?? '';
Enter fullscreen mode Exit fullscreen mode

6. Display Error in PHP

Source: https://stackoverflow.com/a/21429652/9478774

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
Enter fullscreen mode Exit fullscreen mode

7. Always remember require_once() 99,99%

Compared to include(), require() function will handles errors differently, it will stop the script execution while include() will still continue the script despite the error.

8. Helper functions if you want to redirect

Source: https://stackoverflow.com/a/768472/9478774

function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}
Enter fullscreen mode Exit fullscreen mode

9. Return JSON with this script

Source: https://stackoverflow.com/a/4064468/9478774

<?php
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
Enter fullscreen mode Exit fullscreen mode

And.. there are 41 more points to go.

I hope you find this useful for your work. I hope the best for you!

if you want see the rest, you may want to buy at https://gumroad.com/l/50phpcode/blackfriday
P.S. It is Black Friday deals, so you may want to grab this rare opportunity fast 😁👍🏻

Also, if you have any feedback, please send to my email at sawir.ricardo@gmail.com

I want to thank you again, you are the best!

Top comments (3)

Collapse
 
dakujem profile image
Andrej Rypo

Well... Let me give you a give you a guidance.

Don't ever deal with POST, GET or REQUEST, use a library for that. Search for PSR-7 and PSR-17.

Use the PSR implementation to manipulate headers (redirection, content type), cookies and body of the request.

Do not echo anything, again, use templates to generate HTML content (Plates, Twig or Latte). Use serializers to generate JSON.

Do not require scripts, write OOP code and use Composer with autoloading.

Only ever use prepared statements with PDO or use a library for that (like DBAL, dibi) or an ORM.

Use a micro framework if you want to keep it tiny (like Slim) or a do yourself a favor and study a full framework like Symfony or Laravel for any HTTP request handling. Use something like Symfony Console for CLI tasks.

And learn to write tests right at the beginning, it will improve your coding skill greatly.

Sorry for preaching. Bare with me. 🐻

Collapse
 
ricardosawir profile image
Ricardo Sawir

Thank you Andrej, I also agree with those points 👍🏻

Collapse
 
dakujem profile image
Andrej Rypo

You are welcome. I wish somebody told me that when I was beginning 😆
But there was no PSR back then IIRC. 🤔😁