Three Simple Yet Effective PHP Tips and Tricks

Working on some freelance projects and personal projects recently, I found myself needing to do some simple things in PHP that actually had some great value in the end. I share these now in hopes that they will help someone else.

  1. Adjusting Case Sensitivity – You can use the following code to take any string and perform an initial caps on it. The outer function ucfirst performs the first letter capitalization, while the strtolower will automatically convert the entire string to lower case first. This allow any string with mixed case to be converted to initial caps on the first word.

  2. $myString = "HellO TheRE";
    echo ucfirst(strtolower($value));
    ?>

  3. More Case Sensitivity – instead of using just ucfirst, why not take a look at ucwords. This nifty little built-in PHP function will take and perform an initial cap on every word of a given string. Again, we would probably want to run the string through strtolower to ensure only the initial caps was performed. This may cause issues, however, if you are converting strings that contain acronyms or other words that are generally in all caps.

  4. $myString = "cool PHP";
    echo ucfirst($myString);
    ?>

    The output will be: Cool PHP

    However using it this way, you can see how it would change the output:

    $myString = "cool PHP";
    echo ucfirst(strtolower($myString));
    ?>

    The out of that last one will become Cool Php.

  5. File Uploads – When you allow file uploads, say for web site owners to upload images, it is best to check to see if the file exists first and if so remove the old version first. In this short example a filename is being dynamically built, but that is another discussion in another post.

    First, we build our file name – the second thing we do, since we are renaming and files to a standard naming convention is to check to see if the file exists. In this case we used a unique ID, an underscore and the image file name being passed into this function. You can use what ever you need to name your files. Second, the if statement checks for the existence of the file, and if true it deletes it using the PHP unlink function, then copies the new file over and finally reports any errors. If the file does not exist, the function simply moves to the else block and copies the new file.


  6. $fileName = “images/”.$id.”_”.$image;
    if(file_exists($fileName))
    {
    unlink($fileName);
    $copied = move_uploaded_file($_FILES['form_element_name]['tmp_name'], $fileName);
    if(!copied)
    {
    echo “upload failed for image “.$fileName.” or you didn’t upload that file
    “;
    }
    }
    else
    {
    $copied = move_uploaded_file($_FILES['form_element_name']['tmp_name'], $fileName);
    if(!copied)
    {
    echo “upload failed for image “.$fileName.” or you didn’t upload that file
    “;
    }
    }