Category: PHP Toggle Comment Threads | Keyboard Shortcuts

  • Jay Versluis 7:13 pm on March 17, 2014 Permalink | Reply
    Tags: zip   

    Categories: PHP   

    How to create a recursive ZIP Archive from a directory in PHP 

    PHP-IconI’ve just realised how (relatively) easy it is to make PHP create a ZIP Archive from a directory and its sub directories.

    Previously I had relied on the Linux Shell Command zip or tar to do this which is a convenient one liner. I had assumed that in PHP we had to go through each directory and add the files manually – until I’ve discovered the RecursiveIterator class variants.

    In this example I’m defining a root path and a file name for my archive (change at will), then iterate through each file in each directory (and if thats’ a directory too, we’ll go one level deeper). The result of which is an array of files. We’ll get their full paths and add them to the ZIP archive.

    // define some basics
    $rootPath = './';
    $archiveName = 'zipfile.zip';
    
    // initialize the ZIP archive
    $zip = new ZipArchive;
    $zip->open($archiveName, ZipArchive::CREATE);
    
    // create recursive directory iterator
    $files = new RecursiveIteratorIterator (new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
    
    // let's iterate
    foreach ($files as $name => $file) {
    	$filePath = $file->getRealPath();
    	$zip->addFile($filePath);
    }
    
    // close the zip file
    if (!$zip->close()) {
    	echo '

    There was a problem writing the ZIP archive.

    '; } else { echo '

    Successfully created the ZIP Archive!

    '; }

    The above will produce a ZIP file which will contain references to the absolute full paths of each file. That’s great if you’d like to unzip those files later in exactly the same location – but it’s not so cool if you’re just interested in the content and the idea of 11 sub folders strikes you as “less funny”.

    Help is at hand, thanks to the way we can add files to the archive – namely by creating a new local filename. Here’s an example of how this works on Linux systems:

    // let's iterate and create a new local file name
    foreach ($files as $name => $file) {
    	$new_filename = substr($name,strrpos($name,'/') + 1);
    	$zip->addFile($file, $new_filename);
    }
    

    No more references to absolute full paths in your ZIP file.





     
  • Jay Versluis 5:23 pm on March 13, 2014 Permalink | Reply  
    Categories: PHP   

    How to add elements to an array in PHP 

    PHP-IconIt’s extremely easy to add elements to an existing array in PHP – so easy in fact that I regularly forget how to do it!

    I’m used to initialising and setting up my variables from Objective C, but PHP is so much easier and deals with it on the fly. Here we do it – ideal for loops:

    // create the array
    $myArray = array();
    
    // add three elements to it
    $myArray[] = 'Hello';
    $myArray[] = 'I must';
    $myArray[] = 'be going';
    
    // loop through all elements
    foreach ($myArray as $item) {
      echo $item;
    }




     
  • Jay Versluis 5:54 pm on February 21, 2014 Permalink | Reply
    Tags: ,   

    Categories: PHP   

    Getting Started with ZEND Server 6 on Mac OS X 

    ZEND_logo

    I’ve just installed ZEND Server 6.3 on my MacBook running Mavericks 10.9.1. Needless to say I’m sill a little shaken up from the huge amount of brain pain this adventure has caused.

    Because once downloaded and installed on your system, you may ask yourself a vital question: Now What?

    Let’s find out. This article is Work in Progress – bear with me while I flesh it out.

    The Basics

    ZEND Server on Mac is located here:

    • /usr/local/zend/

    Your web files live here:

    • /usr/local/zend/apache2/htdocs

    To open this directory in Finder you can navigate there with a Terminal session and open it, like so:

    cd /usr/local/zend/apache2/htdocs
    open .

    Now you can create a shortcut on your sidebar for easy access.

    To access the ZEND Server Admin interface, navigate to the following URL in your browser:

    If you’re done with it, you can uninstall ZEND Server with the following command:

    sudo /usr/local/zend/bin/uninstall.sh

    (More …)





     
    • Yonni 10:28 am on February 26, 2014 Permalink | Reply

      Mysql access – you can deploy phpmyadmin from within the Zend Server UI’s Guide Page. After launching Zend Server, this is the first page that opens up and is the homepage for Zend Server’s UI.

      Right at the top, in Getting Started you have a scrolling gallery of applications, one of which is phpmyadmin.

      Deploy, configure, rejoice

      • Jay Versluis 9:17 am on February 27, 2014 Permalink | Reply

        Hi Yonni,

        Thank you so much for the tip – how could I have missed that 🙂 I hadn’t spotted there was a second page for applications!

        My first attempt to deploy phpMyAdmin manually didn’t work, but auto deploy via ZEND Server was indeed a breeze. Thanks for sharing!

  • Jay Versluis 6:35 pm on February 15, 2014 Permalink | Reply
    Tags: , ,   

    Categories: PHP   

    How to install ZEND Framework for use with MAMP 

    ZEND_logoIf you have MAMP installed and working on your Mac, it’s easy to get started with ZEND Framework development. I’ll show you how in this article.

    Download the framework from here:

    Choose the full version without ZEND Server (not necessary as we’re using MAMP). Unpack the download and put it somewhere safe. I’m adding mine to my Documents directory. I’ll also rename my folder to something like “ZendFramework” without the version number.

    To access it from anywhere on our machine we’ll create an alias named “zf”. zf is a shell script provided by the framework that we’ll need throughout our development journey with ZEND. Let’s to this in a Terminal session:

    alias zf="/Users/you/Documents/ZendFramework/bin/zf.sh'

    Replace the path with your own. Notice the call to /bin/zf.sh which is the “real” shell script. Our alias has just made this universal and accessible without having to mess with our shell path.

    Verify that it’s working with this:

    zf show version
    
    Zend Framework Version: 1.12.3

    Read the full article





     
    • nashivor 6:05 am on February 17, 2014 Permalink | Reply

      Installation Process of Zend Famework using Mamp define in this blog step by step..

  • Jay Versluis 5:54 pm on January 16, 2014 Permalink | Reply
    Tags:   

    Categories: PHP   

    How to send an email in PHP 

    Many complex things are extremely simple in PHP – sending mail is one of them. Here’s how:

    // components for our email
    $recepients = 'you@somewhere.com';
    $subject = 'Hello from PHP';
    $message = 'This is a test mail.';
    
    // let's send it 
    $success = mail($recepients, $subject, $message);
    if ($success) {
    	echo 'Mail added to outbox';
    } else {
    	echo 'That did not work so well';
    }
    

    The mail function will add the message to the out queue, so the test will not show if the message has actually been sent.

    To avoid really long single line emails (i.e. entire message on one line) we can use the wordwrap() function, causing an automatic wrap to the next line if more than 70 characters are in a single row:

    $message = wordwrap($message, 70, "\r\n"); 
    

    All tips courtesy of the PHP Manual Pages:





     
  • Jay Versluis 5:00 pm on January 16, 2014 Permalink | Reply  
    Categories: PHP   

    How to test if a Shell Command can be executed in PHP 

    Before we execute a shell command from PHP it’s a good idea to test if the server will respond to it. We can do this by making use of the empty() function.

    The following example consists of a helper function you can call before executing the command in question. Then we call it with the shell command we intend to use, before executing the command for real. We’re using ‘uname -a’ here as an example that will generate output and takes a parameter:

    // helper function
    function checkShellCommand($command) {
        $returnValue = shell_exec("$command");
    	if(empty($returnValue)) {
    		return false;
    	} else {
    		return true;
    	}
    }
    
    // test the shell command you'd like to use
    if (!checkShellCommand('uname -a')) {
        print 'This command cannot be executed.';
    } else {
        echo shell_exec('uname -a');
    }
    




     
    • Lionel Péramo 9:01 am on December 7, 2014 Permalink | Reply

      function checkShellCommand($command) { return !empty(shell_exec(“$command”)); }
      It’s shorter and …I wonder myself if it’s really needed to have a function for that.

  • Jay Versluis 4:15 pm on January 16, 2014 Permalink | Reply  
    Categories: PHP, Windows ( 22 )   

    How to test if your server is running Windows from PHP 

    If we’re executing shell commands via PHP we need to know if the server is running Windows or Linux. Thanks to a magic constant in PHP we can find out like this:

    echo PHP_OS;
    

    This will give us a single value like

    • Linux
    • Darwin
    • Windows
    • WINNT

    With that info at hand, we can write a function that delivers a boolean result (courtesy of the PHP manual):

    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        echo 'This server is running Windows!';
    } else {
        echo 'This server is NOT running Windows!';
    }
    

    This takes the output of PHP_OS and looks at the first three characters turned into upper case. If those are identical to WIN it’s Windows – and if not we assume it’s a Linux flavour.

    If you need a more detailed information about your environment consider using php_uname():

    echo php_uname();
    

    This will give you the above, plus server name, kernel version, release and local server time.





     
  • Jay Versluis 4:50 pm on November 15, 2013 Permalink | Reply  
    Categories: PHP   

    How to read the contents of a file into a string in PHP 

    file_get_contents() can help us here. It reads a file and stores it in a string. Can be used with local files, as well as online content:

    $myLocalFile = file_get_contents('myfile.html');
    $myOnlineFile = file_get_contents('http://wpguru.co.uk');
    
    echo myOnline File; // would display the actual website
    

    This is different from the file() function which reads the contents of a file into an array.





     
  • Jay Versluis 4:35 pm on November 15, 2013 Permalink | Reply
    Tags: str_replace   

    Categories: PHP   

    How to replace text inside a string in PHP 

    If we have a string and would like to replace a portion of it, we can use the str_replace() function in PHP. It works like this:

    str_replace (‘whatToReplace’, ‘theReplacement’, ‘originalText’);

    It’s easy to remember… but I always get confused when I look this up in the manual. Here’s an example:

    $originalText = "Now is the time when xxxx should be replaced.";
    $replacement = str_replace('xxxx', 'Something', $originalText);
    echo $replacement;
    

    This works well if there’s only one occurrence that can be replaced. If you had ‘xxxx’ twice in the original text, both xxxx’s would be replaced by Something:

    $originalText = "Now is the time when xxxx should be replaced with xxxx.";
    $replacement = str_replace('xxxx', 'Something', $originalText);
    echo $replacement;
    

    This function is cAsE SenSitiVe – you can also use str_ireplace() which will ignore case.

    You can also do it with Regular Expressions (shudders):





     
  • Jay Versluis 1:30 pm on November 15, 2013 Permalink | Reply
    Tags: date, timestamp   

    Categories: PHP   

    How to convert a timestamp into a readable date in PHP 

    A UNIX timestamp is something like a 10 digit (or less) integer number which represents the elapsed seconds since the 1st of January 1970 (also known as the Unix Epoch). It’s a very accurate representation of time, but not necessarily something us humans easily understand.

    A Unix Timestamp looks something like 1367805780.

    We can use PHP’s date() function to turn it into something more readable, such as 05/05/2013, or 5th of May, 2013 at 10:03pm. Here’s how:

    	$theTimestamp = 1367805780;
    	echo date('m/d/Y', $theTimestamp);
    
    	// result: 05/05/2013
    

    The first parameter tells date() how to format its output – and you can get extremely creative with it:

    	$theTimestamp = 1367805780;
    	echo date('l jS \of F Y h:i:sa', $theTimestamp);
    
    	// result: Sunday 5th of May 2013 10:03:00pm
    

    The slightly eerie looking combination of letters and numbers is made up of “real” printable characters (such as the “of” in “5th of May”) and special switches that represent each date component.

    For a full reference and plenty of examples have a look at the PHP Manual:





     
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