Session based flash messages

Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.

Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better.  And as usual, where there’s a will, and some code- there’s a way!

Before we get started, make sure that a session is started, otherwise a) no message will be displayed, and b) super fun headers already sent messages.

//Ensure that a session exists (just in case)
if( !session_id() )
{
    session_start();
}

//Actual function

/**
 * Function to create and display error and success messages
 * @access public
 * @param string session name
 * @param string message
 * @param string display class
 * @return string message
 */
function flash( $name = '', $message = '', $class = 'success fadeout-message' )
{
    //We can only do something if the name isn't empty
    if( !empty( $name ) )
    {
        //No message, create it
        if( !empty( $message ) && empty( $_SESSION[$name] ) )
        {
            if( !empty( $_SESSION[$name] ) )
            {
                unset( $_SESSION[$name] );
            }
            if( !empty( $_SESSION[$name.'_class'] ) )
            {
                unset( $_SESSION[$name.'_class'] );
            }

            $_SESSION[$name] = $message;
            $_SESSION[$name.'_class'] = $class;
        }
        //Message exists, display it
        elseif( !empty( $_SESSION[$name] ) && empty( $message ) )
        {
            $class = !empty( $_SESSION[$name.'_class'] ) ? $_SESSION[$name.'_class'] : 'success';
            echo '
.$class.'" id="msg-flash">'.$_SESSION[$name].'
'
; unset($_SESSION[$name]); unset($_SESSION[$name.'_class']); } } }
//Set the first flash message with default class
flash( 'example_message', 'This content will show up on example2.php' );

//Set the second flash with an error class
flash( 'example_class', 'This content will show up on example2.php with the error class', 'error' );
//Displaying the messages
<?php flash( 'example_message' ); ?>
<?php flash( 'example_class' ); ?>

You can download the source from here

From: http://www.phpdevtips.com/

Get Elapsed time(‘1 min ago’, ‘1 sec ago’, etc) from datetime

Many of the time we need to display the elapsed time from datetime field. This is mainly used in chatting system or in blog posting.

We can use the below function to get elapsed time:

     

function getTimeElapsedString($datetime, $full = false) {

$now = new DateTime(); // Current datetime $ago = new DateTime($datetime); $diff = $now->diff($ago); $diff->w = floor($diff->d / 7); $diff->d -= $diff->w * 7; $string = array( 'y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'min', 's' => 'sec', ); foreach ($string as $k => &$v) { if ($diff->$k) { $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); } else { unset($string[$k]); } } if (!$full) { $string = array_slice($string, 0, 1); }

return $string ? implode(', ', $string) . ' ago' : 'just now';

}

we can call above function as

$string = getTimeElapsedString(‘2016-01-27 16:00:14’);

echo $string; // it will print 2 hours ago

How to create wildcard subdomain in cPanel

Wildcard subdomains allow you to point all the subdomains ( existing and non-existing ) to a specific folder in your account. It means that if you enter any subdomain in your browser ( for example, test.domain.com – not existing, or blog.domain.com – existing), it will show the same content that you uploaded to the folder for the wildcard subdomain.

In order to create a wildcard subdomain, please, follow the next steps:

1) Log in your cPanel

2) Navigate to the menu ‘Subdomains’ under ‘Domains’ section

wildcard_subdomain_1

3) Create a subdomain‘*’ pointing it to the necessary folder ( you will need to specify the path in the field ‘Document Root’ ).

wildcard_subdomain_2

4) Go to the menu ‘Advanced DNS Zone Editor’

wildcard_subdomain_3

5) Make sure that there is an A record for *.yourdomain.com created and pointed to the server IP address ( it could coincide with the IP address of your main domain or ftp.yourdomain.com is pointed to).

wildcard_subdomain_4

6) Now you will need to wait until the propagation is over ( it should take N seconds, where N – is TTL for this A record; you can edit it manually and reduce the number to speed up the process ) and then the wildcard subdomain will work correctly.

Transfer files from one server to another server using PHP

 

server-to-server-php

Sometimes you need to move/migrate files to another server/hosting, and you/your client only have FTP access to the server. And to download these files and re-upload to another server can take a lot of time using FTP client such as Filezilla. FTP do not have zip – unzip functionality, so you need to upload it one by one. And server to server transfer is a lot faster than downloading and uploading the files.

You can use this simple PHP script to move files from one server to another server.

Note: It’s just a simple examples. you need to build your own auth/security method if needed.

1. Using PHP Copy to move files from server to server.

You can just create a php file in the destination server and load the file once in your browser. For example you add this code in http://destination-url/copy-files.php and in copy-files.php you add this php code:

  1. /**
  2.  * Transfer Files Server to Server using PHP Copy
  3.  * 
  4.  */
  5.  
  6. /* Source File URL */
  7. $remote_file_url = “http://origin-server-url/files.zip&#8221;;
  8.  
  9. /* New file name and path for this file */
  10. $local_file = ‘files.zip’;
  11.  
  12. /* Copy the file from source url to server */
  13. $copy = copy( $remote_file_url, $local_file );
  14.  
  15. /* Add notice for success/failure */
  16. if( !$copy ) {
  17.     echo “Doh! failed to copy $file…\n”;
  18. }
  19. else{
  20.     echo “WOOT! success to copy $file…\n”;
  21. }

2. Using PHP FTP to move files from server to server

Sometimes using PHP Copy didn’t work if the files is somehow protected by this method (hotlink protection maybe?). I did experience that if the source is from Hostgator it didn’t work.

But we can use another method. Using FTP (in PHP) to do the transfer using the code:

  1. /**
  2.  * Transfer (Import) Files Server to Server using PHP FTP
  3.  * 
  4.  */
  5.  
  6. /* Source File Name and Path */
  7. $remote_file = ‘files.zip’;
  8.  
  9. /* FTP Account */
  10. $ftp_host = ‘your-ftp-host.com’; /* host */
  11. $ftp_user_name = ‘ftp-username@your-ftp-host.com’; /* username */
  12. $ftp_user_pass = ‘ftppassword’; /* password */
  13.  
  14.  
  15. /* New file name and path for this file */
  16. $local_file = ‘files.zip’;
  17.  
  18. /* Connect using basic FTP */
  19. $connect_it = ftp_connect( $ftp_host );
  20.  
  21. /* Login to FTP */
  22. $login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
  23.  
  24. /* Download $remote_file and save to $local_file */
  25. if ( ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY ) ) {
  26.     echo “WOOT! Successfully written to $local_file\n”;
  27. }
  28. else {
  29.     echo “Doh! There was a problem\n”;
  30. }
  31.  
  32. /* Close the connection */
  33. ftp_close( $connect_it );

using FTP you have more flexibility, the code above is using ftp_get to import the files from source server to destination server. But we can also use ftp_put to export the files (send the files) from source server to destination, using this code:

  1. /**
  2.  * Transfer (Export) Files Server to Server using PHP FTP
  3.  * 
  4.  */
  5.  
  6. /* Remote File Name and Path */
  7. $remote_file = ‘files.zip’;
  8.  
  9. /* FTP Account (Remote Server) */
  10. $ftp_host = ‘your-ftp-host.com’; /* host */
  11. $ftp_user_name = ‘ftp-username@your-ftp-host.com’; /* username */
  12. $ftp_user_pass = ‘ftppassword’; /* password */
  13.  
  14.  
  15. /* File and path to send to remote FTP server */
  16. $local_file = ‘files.zip’;
  17.  
  18. /* Connect using basic FTP */
  19. $connect_it = ftp_connect( $ftp_host );
  20.  
  21. /* Login to FTP */
  22. $login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
  23.  
  24. /* Send $local_file to FTP */
  25. if ( ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
  26.     echo “WOOT! Successfully transfer $local_file\n”;
  27. }
  28. else {
  29.     echo “Doh! There was a problem\n”;
  30. }
  31.  
  32. /* Close the connection */
  33. ftp_close( $connect_it );

To make it easier to understand:

  • ftp_connect is to connect via FTP.
  • ftp_login is to login to FTP account after connection established.
  • ftp_close is to close the connection after transfer done (log out).
  • ftp_get is to import/download/pull file via FTP.
  • ftp_put is to export/send/push file via FTP.

After you import/export the file, always delete the PHP file you use to do this task to prevent other people using it.

ZIP and UNZIP Files using PHP

Of course to make the transfer easier we need to zip the files before moving, and unzip it after we move to destination.

ZIP Files using PHP

You can zip all files in the folder using this code:

  1. /**
  2.  * ZIP All content of current folder
  3.  * 
  4.  */
  5.  
  6. /* ZIP File name and path */
  7. $zip_file = ‘files.zip’;
  8.  
  9. /* Exclude Files */
  10. $exclude_files = array();
  11. $exclude_files[] = realpath( $zip_file );
  12. $exclude_files[] = realpath( ‘zip.php’ );
  13.  
  14. /* Path of current folder, need empty or null param for current folder */
  15. $root_path = realpath( );
  16.  
  17. /* Initialize archive object */
  18. $zip = new ZipArchive;
  19. $zip_open = $zip->open( $zip_file, ZipArchive::CREATE );
  20.  
  21. /* Create recursive files list */
  22. $files = new RecursiveIteratorIterator(
  23.     new RecursiveDirectoryIterator( $root_path ),
  24.     RecursiveIteratorIterator::LEAVES_ONLY
  25. );
  26.  
  27. /* For each files, get each path and add it in zip */
  28. if( !empty( $files ) ){
  29.  
  30.     foreach( $files as $name => $file ) {
  31.  
  32.         /* get path of the file */
  33.         $file_path = $file->getRealPath();
  34.  
  35.         /* only if it’s a file and not directory, and not excluded. */
  36.         if( !is_dir( $file_path ) && !in_array( $file_path, $exclude_files ) ){
  37.  
  38.             /* get relative path */
  39.             $file_relative_path = str_replace( $root_path, , $file_path );
  40.  
  41.             /* Add file to zip archive */
  42.             $zip_addfile = $zip->addFile( $file_path, $file_relative_path );
  43.         }
  44.     }
  45. }
  46.  
  47. /* Create ZIP after closing the object. */
  48. $zip_close = $zip->close();

UNZIP Files using PHP

You can unzip file to the same folder using this code:

  1. /**
  2.  * Unzip File in the same directory.
  3.  * @link http://stackoverflow.com/questions/8889025/unzip-a-file-with-php
  4.  */
  5. $file = ‘file.zip’;
  6.  
  7. $path = pathinfo( realpath( $file ), PATHINFO_DIRNAME );
  8.  
  9. $zip = new ZipArchive;
  10. $res = $zip->open($file);
  11. if ($res === TRUE) {
  12.     $zip->extractTo( $path );
  13.     $zip->close();
  14.     echo “WOOT! $file extracted to $path”;
  15. }
  16. else {
  17.     echo “Doh! I couldn’t open $file”;
  18. }

Other Alternative to ZIP / UNZIP File

Actually, if using cPanel you can easily create zip and unzip files using cPanel File Manager.

cpanel-zip-unzip-file-manager

I hope this tutorial is useful for you who need a simple way to transfer files from server to server.

Manually Restart Apache and MYSQL thru .bat file

bat-file-icon
Please save the below code as .bat file through notepad or any other editor.

@echo off
cls
:start
Echo.
Echo 1. Restart Apache
Echo 2. Restart MYSQL
Echo 3. Both
Echo 4. Exit
set /p choice=Please enter your choice:
rem if not '%choice%' == '' ser choice=%choice:~0;1%
if '%choice%' == '' Echo "%choice%" is not valid please try again
if '%choice%' == '1' goto apache
if '%choice%' == '2' goto mysql
if '%choice%' == '3' goto both
if '%choice%' == '4' goto exit
Echo.
goto start
:apache
Echo Apache
net stop Apache2.4 && net start Apache2.4
goto end
:mysql
Echo Mysql
net stop mysql && net start mysql
goto end
:both
Echo Both
net stop Apache2.4 && net start Apache2.4
net stop mysql && net start mysql
goto end
:exit
goto end
:end
pause
exit

Now just double click that .bat file and you can restart Apache/MYSQL or both.

NOTE: Please replace “Apache2.4” with your apache version.