Category: PHP Toggle Comment Threads | Keyboard Shortcuts

  • Jay Versluis 9:26 am on May 25, 2018 Permalink | Reply  
    Categories: PHP   

    How to declare Classes in PHP 

    Since PHP 5 we can use object oriented features in PHP. This allows us to not only use functions and variables, but also write classes and create instances of them in our code.

    Here’s quick rundown on how to do it.

    Writing and instantiating a Class

    Creating classes is very similar to writing functions. Here’s an example of a class with one method and one variable:

    // creating a basic class with one method
    
    class Test {
      var $testValue = 47;
      function sampleFunction() {
      echo "Hello from the Sample Function!\n";
      }
    }

    Once declared, we can instantiate our class like this:

    // instantiating the class
    
    $myTest = new Test();

    Accessing variables and methods

    Now we can access any variables in our instance using the -> operator like this:

    // accessing a class variable
    
    echo $myTest->testValue;

    The same principle is true for calling methods in our instance.

    // calling a method
    
    $myTest->sampleFunction();

    Constructor Methods

    A method is nothing other than a function really, but when a function is part of a class, we call it method. I guess that’s done to differentiate it from a “classic” function that’s declared outside of a class.

    There’s a special method we can declare inside our classes called a constructor method. It works just like a regular method, with the only difference that the constructor is called automatically when the class is instantiated. This is useful if we want something to happen as soon as our class is used the first time.

    Constructors have a special name (__construct); here’s an example:

    // creating a class with a constructor method
    
      class Test {
        function __construct() {
          echo "Hello from the Test Constuctor!\n";
      }
    }

    Extending a Class

    Classes can inherit functionality from other classes. When we do that we create an exact duplicate of an existing class. This is useful if we want to change the behaviour of a class, for example by overwriting existing methods or values.

    Here’s how we can extend a class:

    // extending a class
    
    class MegaTest extends Test {
      function __construct() {
      parent::__construct();
      echo "And Hello again from the extended class constructor.\n";
      }
    }

    Overwriting methods and variables is as easy as simply re-declaring them using their original names. Extended classes can be extended again, but a class can only ever inherit from another single class.

    Notice the use of the parent:: keyword in our constructor method. When our extended class is instantiated, our constructor method is called. If our parent class also has a constructor method (which is optional), we must call this before doing anything else to make sure that any functionality that is setup is being kicked off.

    In essence, anything prefixed with the parent:: keyword will call the related function “one level up”.

    Now we can create an instance of our extended class as described above:

    // instantiate the extended class
    
    $myMegaTest = new MegaTest();




     
  • Jay Versluis 9:44 am on May 19, 2018 Permalink | Reply
    Tags:   

    Categories: PHP   

    How to update legacy constructor methods in PHP 7 

    When I was fiddling with my P2 Categories theme last week, debug mode generated several warnings when run in PHP 7.2.1. That’s because class methods are no longer allowed to have the same name as the class itself.

    This was allowed in PHP 5 and earlier, but from what I gather it’s no longer the way to do things. Back then such methods were used as constructors, or in other words, methods that would be run automatically when the class is instantiated.

    Let’s take an example from the P2 theme. Here’s the beginning of the P2 class as of version 1.5.8:

    class P2 {
    	// ...
    	function P2() {
                // ...
    

    This will work just fine in PHP 5, but will generate a warning in PHP 7 (even though the code will execute). To update this, all we need to do is change our function name to __construct (notice the two underscores at the beginning of the name):

    class P2 {
    	// ...
    	function __construct() {
                // ...
    

    Anything inside the __construct() function is executed as soon as an instance of the class is created.

    When updating legacy code, there is the risk that the previous function name is called during instantiation. Consider this:

    class P2_Post_List_Creator extends P2_List_Creator {
    	var $form_action_name = 'p2-post-task-list';
    
    	function P2_Post_List_Creator() {
    		parent::P2_List_Creator();
                    // ...
    

    Here a class extends another class and calls a constructor method of the parent class by name. If we had just patched the parent class with _construct(), the child class would throw an “undefined function” error.

    To avoid this we’ll also have to update any calls made to the original constructor method, like so:

    class P2_Post_List_Creator extends P2_List_Creator {
    	var $form_action_name = 'p2-post-task-list';
    
    	function P2_Post_List_Creator() {
    		parent::__construct();
                    // ...
    

    And that’s really all there’s to it.





     
  • Jay Versluis 9:24 am on May 15, 2018 Permalink | Reply
    Tags:   

    Categories: Linux ( 101 ), PHP   

    How to install PHP 7.x on a CentOS LAMP Stack 

    By default, CentOS 7 comes with support for PHP 5.4. Sadly that version has reached the end of its life in 2015and is no longer updated by the developers. If we want to stay up to date with the latest software, we may want to upgrade (if our applications are working with newer versions of PHP).

    For CentOS users this either means to compile cutting edge versions from source and tweaking lots of scary system configurations – or dipping into the power of Software Collections. These are official pre-compiled packages by the software vendor, designed to run newer versions of software alongside those that are provided by default.

    At the time of writing, PHP 7.2 is available but it’s not part of the software collections yet, so we’ll use  PHP 7.1 with FPM support under Apache (as it’s the recommended way to do so).

    Let’s begin! (More …)





     
  • Jay Versluis 10:44 pm on November 29, 2016 Permalink | Reply
    Tags:   

    Categories: Linux ( 101 ), PHP   

    How to install PHP from source on CentOS 

    PHP-IconI have recently installed PHP 7 from source on a fresh minimal CentOS 7 box. No previous version of PHP was installed, and I thought I’d give 7 a spin. There were a few pitfalls I hadn’t come across before, so here’s what worked for me.

    Downloading and extracting the source code

    It sounds crazy, but this was the hardest part of the whole installation! There were two problems I’ve encountered here.

    The first was that PHP offer downloads via a mirror. A direct link may look something like this: http://php.net/get/php-7.0.12.tar.bz2/from/this/mirror. This means that if we were to download this file using wget, it would be saved as “mirror”. Now what we want.

    So instead we can ask wget to give the download a different name using the -O parameter, like so:

    wget -O php7.tar.bz2 http://php.net/get/php-7.0.12.tar.bz2/from/this/mirror

    This will save our file as php7.tar.bz2 instead. So far so good. Unpacking this file seems to be impossible. From what the internet tells me, this should be the correct way of extracting a tar.bz2 file:

    tar -jxvf php7.tar.bz2

    But that didn’t work, not matter how hard I tried. All I ever got was a “non-recoverable” error. Which sucks. In the end I extracted the file on my Mac, created a ZIP archive and downloaded that instead. Unnecessarily cumbersome and idiotic, but worked. Finally I had them on my CentOS box.

    Building the source code

    Jumping into the extracted directory, the configure command can prepare the build. At this stage I encountered an error:

    configure: error: xml2-config not found. Please check your libxml2 installation.

    This can be fixed by installing the libxml2-devel package (NOT libxml2 as the error would have you believe). Let’s do that and run configure again:

    yum install libxml2-devel
    ./configure

    Now we can run make, followed by make test to see if the installation is going to go well. This will take a few minutes.

    make
    make test

    Feel free to skip “make test” if you’re in a hurry. In my case, after over 10.000 tests, PHP told me this:

    You may have found a problem in PHP.
    This report can be automatically sent to the PHP QA team at
    http://qa.php.net/reports and http://news.php.net/php.qa.reports
    This gives us a better understanding of PHP's behavior.
    If you don't want to send the report immediately you can choose
    option "s" to save it. You can then email it to qa-reports@lists.php.net later.

    Perplexed yet unfazed, I continued on and installed PHP anyway:

    make install

    And only moments later, PHP 7 was running on my CentOS system.

    php -v
    
    PHP 7.0.12 (cli) (built: Nov  8 2016 06:59:14) ( NTS )
    Copyright (c) 1997-2016 The PHP Group
    Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

    Not sure what else to tell you.





     
  • Jay Versluis 12:11 pm on June 11, 2016 Permalink | Reply  
    Categories: PHP, WordPress ( 144 )   

    How to set WordPress Categories depending on the Post Title 

    I was working on a project the other day that required to determine which category a new post would go into, depending on the post title. This was important because posts were automatically acquired without the web interface, and in this workflow there was no way to pick a category other than the default.

    In our case we wanted to use a post fix in the title to determine which category was to be picked: for example, if a post title would end with “_ONE”, it should end up in Category 1, and if it ends up with “_TWO” it would end up in Category 2.

    Thankfully there’s a hook called save_post that is called every time a post is updated. At this point we can check what the post title is, determine the post fix, and set the correct category. Here’s a function that does just that:

    function set_my_categories($post_ID) {
    	
    	// grab the current title
    	$title = get_the_title($post_ID);
    	
    	// set the category depending on the last four characters of the title
    	// _ONE = Category 1
    	// _TWO = Category 2
    	$postfix = substr($title, -4);
    	if ($postfix == '_ONE') {
    		wp_set_post_categories($post_ID, array(1));
    	}
    	if ($postfix == '_TWO') {
    		wp_set_post_categories($post_ID, array(2));
    	}
    }
    add_action('save_post', 'set_my_categories');
    

    If a post fix is not present, the categories will not be changed.

    For this example I’m assuming that my categories are actually 1 and 2 on the system, something that’s not really the case. To determine the correct value set under wp_set_post_categories, I usually head over to Posts – Categories, select the category I want to use and check the URL of what WordPress gives me. Say the URL looks like this:

    http://domain.com/wp-admin/term.php?taxonomy=category&tag_ID=366&post_type=post

    then the tag_ID parameter hints that my category has an ID of 366, and that’s the value we need to use.

    And if a post needs to go into two categories, separate the category IDs with a comma like so:

    wp_set_post_categories($post_ID, array(2,3));

    Removing the post fix before the title is displayed

    Since our post fix is for internal purposes only, we may not want it to appear as part of the actual post title on the front page. But we also don’t want to remove it from every post once the category has been set and still have a reference in the admin interface. So the way to do it is to simply suppress it before out theme prints it out.

    The following code will do just that: if a post fix is present, curb the title. If not, leave the title unchanged.

    // curb title if we have a post fix
    $title = get_the_title();
    $postfix = substr($title, -4);
    if ($postfix == '_ONE' || $postfix == '_TWO') {
    	$title = substr($title, 0, -4);
    }
    // use echo $title to print the post title in your theme
    

    And there we have it. The same principle can be used if your title contains a certain keyword and you want to use it to add the post to a particular category automatically.





     
  • Jay Versluis 10:00 am on December 4, 2014 Permalink | Reply  
    Categories: PHP   

    How to create a redirect in PHP 

    Say you had domain.com/folder, and you’d like it to automatically redirect to domain.com/otherfolder, do the following:

    
    

    Add the above to a file called index.php in domain.com/folder. As soon as someone visits your location, the browser redirects to the new URL.

    Courtesy of the Stackoverflow community:





     
  • Jay Versluis 8:50 am on March 20, 2014 Permalink | Reply
    Tags:   

    Categories: PHP   

    How to switch between several PHP versions in MAMP 2.x 

    mamp logoSometimes you need to test your projects against multiple versions of PHP.

    If you’re using MAMP that’s fairly easy to do: head over to the MAMP Start Screen, select Preferences and see two versions to choose from.

    Here I’m using MAMP 2.2 (even though 3.x has been released already) and I have PHP 5.2.17 and PHP 5.5.3.

    When I switch to the other version MAMP restarts and I can refresh my browser to see my project running on the other PHP version.

    Screen Shot 2014-03-20 at 08.31.06

    Screen Shot 2014-03-20 at 08.31.12

    That’s all good if I actually needed either version – but sadly 5.2.x is too old for me, and 5.5.x doesn’t quite work and is a bit too cutting edge. I need it to reflect my production environment.

    So what is a boy to do?

    (More …)





     
    • pepperstreet 6:37 pm on November 21, 2015 Permalink | Reply

      Hello, anyone tried to update and use PHP > 5.5.3 in MAMP 2.2 ?
      Would like to keep MAMP 2.2 and add a newer PHP version on my older laptop/OSX.
      Thanks in advance.

      • Jay Versluis 10:41 pm on November 21, 2015 Permalink | Reply

        Hi pepperstreet, I’ve only tried older versions and they worked a treat, 5.5.3 came pre-installed with MAMP and also worked well. I can also tell you that when you install MAMP 3, it will install itself alongside MAMP 2 so if you want to try even newer versions of PHP, see if MAMP 3 works for you (and if not, simply keep using MAMP 2).

        Hope this helps!

    • Philipp 4:08 am on January 5, 2016 Permalink | Reply

      This doesn’t seem to work with PHP 7. Checkbox is grayed out.

      • Jay Versluis 10:00 pm on January 5, 2016 Permalink | Reply

        Is this on Mamp 2 or 3?

    • Philipp 2:14 pm on January 6, 2016 Permalink | Reply

      I updated to MAMP 3.5 and it’s working now. Was previously on MAMP 3.2.1.

  • Jay Versluis 10:59 am on March 18, 2014 Permalink | Reply
    Tags: filesize, round   

    Categories: PHP   

    How to check the size of a file in PHP 

    PHP-IconPHP has a handy function called filesize() which can help us display how big a file is.

    It does this in bytes by default, but with a bit of tinkering we can easily convert this into kilobytes or megabytes.

    Let’s first see how this works in bytes:

    $file = '/path/to/your/file';
    $filesize = filesize($file);
    
    echo "The size of your file is $filesize bytes.";
    

    Converting bytes into kilobytes works by dividing the value by 1024. PHP is very accurate and will give you 12 decimal digits – perhaps a little overkill. To avoid this we can make use of the round() function and specify how many digits of accuracy we’d like to display:

    $file = '/path/to/your/file';
    $filesize = filesize($file); // bytes
    $filesize = round($filesize / 1024, 2); // kilobytes with two digits
    
    echo "The size of your file is $filesize KB.";
    

    To display the value in megabytes we’ll simply divide by 1024 twice:

    $file = '/path/to/your/file';
    $filesize = filesize($file); // bytes
    $filesize = round($filesize / 1024 / 1024, 1); // megabytes with 1 digit
    
    echo "The size of your file is $filesize MB.";
    




     
    • Lorenz 5:47 am on August 6, 2017 Permalink | Reply

      You are the boss – i found the same script but 10 times longer! Super easy and compact thanks a lot!

  • Jay Versluis 10:00 am on March 18, 2014 Permalink | Reply
    Tags: pathinfo, scandir   

    Categories: PHP   

    How to list a directory in PHP and only show ZIP files 

    web-find-iconI wanted to list a directory in PHP. At the same time, I wanted to make sure only files are listed – not subdirectories or dot directories.

    More specifically, I only wanted to include files with the ending .zip.

    Two tools come to the rescue here:

    • scandir() to list the directory and give us an array
    • and the super handy pathinfo() to check a file extension

    Here’s how I did it

    function list_zipfiles($mydirectory) {
    	
    	// directory we want to scan
    	$dircontents = scandir($mydirectory);
    	
    	// list the contents
    	echo '
      '; foreach ($dircontents as $file) { $extension = pathinfo($file, PATHINFO_EXTENSION); if ($extension == 'zip') { echo "
    • $file
    • "; } } echo '
    '; }

    Call the function with the directory of your choice – give it a full path like /var/your/directory. Next scandir() creates an array of files and directories which we iterate over with a foreach loop. I’m also formatting the output as an unordered list, hence the presence of some HTML elements in the echo statements.

    The first thing we’ll do in the loop is to have a look at each file’s extension. If it is in fact “zip” then we’d like to list it. Other elements won’t show up.

    I hope it helps 😉





     
  • Jay Versluis 7:30 pm on March 17, 2014 Permalink | Reply  
    Categories: PHP   

    How to test which HTML form button was pressed in PHP 

    execImagine you have a HTML form with several values and two buttons at the bottom. One could say “Do This” and the other “Do That”. How do you know which one was pressed by the user?

    It’s fairly easy – but I keep forgetting this time and time again. We do this by accessing the name attribute of the HTML button in PHP.

    Consider this HTML form:

    The button classes are WordPress standard “blue” and “grey” button layouts, and the value is what’s written on the button. The secret sauce however is in the name fields here.

    Back in PHP when the form is submitted we can access the $_POST variable which an array of values we’re getting back from the form. We can access them like this:

    if (isset($_POST['button1'])) {
      // Do This was pressed
    } else if (isset($_POST['button2'])) {
      // Do That was pressed
    }
    

    You can access the rest of your form’s elements in the same way (i.e. tick boxes, select options, text fields, etc).





     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel