Header-Ad

Linux & Web Development Geek - Tips & Tricks

PHP,Joomla,WordPress & Linux based server management, error resolutions and fixing problems.

Thursday, November 17, 2016

Linux: How to find - Size of a directory & Free disk space

2:37 PM


Linux Server Management Tips . (File & Directory)



Tip.1 - Finding the size of a directory

$ du
Typing the above at the prompt gives you a list of directories that exist in the current directory along with their sizes. The last line of the output gives you the total size of the current directory including its subdirectories. The size given includes the sizes of the files and the directories that exist in the current directory as well as all of its subdirectories. Note that by default the sizes given are in kilobytes. 

$ du /home/david
The above command would give you the directory size of the directory /home/david


$ du -h
This command gives you a better output than the default one. The option '-h' stands for human readable format. So the sizes of the files / directories are this time suffixed with a 'k' if its kilobytes and 'M' if its Megabytes and 'G' if its Gigabytes.

$ du -ah

This command would display in its output, not only the directories but also all the files that are present in the current directory. Note that 'du' always counts all files and directories while giving the final size in the last line. But the '-a' displaysthe filenames along with the directory names in the output. '-h' is once again human readable format.

$ du -c
This gives you a grand total as the last line of the output. So if your directory occupies 30MB the last 2 lines of the output would be

30M .
30M total

The first line would be the default last line of the 'du' output indicating the total size of the directory and another line displaying the same size, followed by the string 'total'. This is helpful in case you this command along with the grep command to only display the final total size of a directory as shown below.


$ du -ch | grep total
This would have only one line in its output that displays the total size of the current directory including all the subdirectories.

$ du -s
This displays a summary of the directory size. It is the simplest way to know the total size of the current directory.

$ du -S
This would display the size of the current directory excluding the size of the subdirectories that exist within that directory. So it basically shows you the total size of all the files that exist in the current directory.

$ du --exculde=mp3
The above command would display the size of the current directory along with all its subdirectories, but it would exclude all the files having the given pattern present in their filenames. Thus in the above case if there happens to be any mp3 files within the current directory or any of its subdirectories, their size would not be included while calculating the total directory size.

Tip 2.Finding the disk free space / disk usage

$ df
Typing the above, outputs a table consisting of 6 columns. All the columns are very easy to understand. Remember that the 'Size', 'Used' and 'Avail' columns use kilobytes as the unit. The 'Use%' column shows the usage as a percentage which is also very useful.


$ df -h
Displays the same output as the previous command but the '-h' indicates human readable format. Hence instead of kilobytes as the unit the output would have 'M' for Megabytes and 'G' for Gigabytes. 

Most of the users don't use the other parameters that can be passed to 'df'. So I shall not be discussing them.

I shall in turn show you an example that I use on my machine. I have actually stored this as a script named 'usage' since I use it often. 

Example :
I have my Linux installed on /dev/hda1 and I have mounted my Windows partitions as well (by default every time Linux boots). So 'df' by default shows me the disk usage of my Linux as well as Windows partitions. And I am only interested in the disk usage of the Linux partitions. This is what I use :

$ df -h | grep /dev/hda1 | cut -c 41-43

This command displays the following on my machine

45%

Basically this command makes 'df' display the disk usages of all the partitions and then extracts the lines with /dev/hda1 since I am only interested in that. Then it cuts the characters from the 41st to the 43rd column since they are the columns that display the usage in % , which is what I want.

Export & Import all mysql databases at one time.

2:33 PM


Most of the times you want to keep a backup of all of your MySQL databases. Suppose you have more than 100 MySQL databases & you want to export all of them at the same time and again import all of them into MySQL server at one time. How would you do that?

The answer ....


Go to the command line : 

How to export all mysql databases at once:

mysqldump -u root -p --all-databases > alldb.sql
Edit the root and enter the password for root to export all the databases to alldb.sql file, notice that this file will be generated at the same place where you are working in shell from.

How to Import all mysql databases at once:

mysql -u root -p < alldb.sql
Edit the user root if necessary and enter the password for root to import all the databases from alldb.sql file to mysql.


Good luck!!

Monday, November 14, 2016

Too many redirects occurred trying to open localhost - Joomla! [SOLVED]

5:18 PM

How to fix Too many redirects occurred Error in Joomla!



Too many redirects occurred trying to open http://mywebsite.com/Joomla_3/index.php " how do I fix this?


Fix:

You need to change the home menu item so it points to a published article. Assuming the home menu item is of type single article and is not pointing to a published article.
Issue with migrating? Include logs/joomla_update.php in your report!
Blank screen? Verify pagesource for HTML code (javascript error)
Installation failing on populating database? Install with set_time_limit(0)
Document your customizations!




PHP Send data to browser, but keep executing script in background

5:12 PM

How to echo or print PHP script while its still executing?


ob_flush writes the buffer. In other words, ob_flush tells PHP to give Apache (or nginx/lighttpd/whatever) the output and then for PHP to forget about it. Once Apache has the output, it does whatever it wants with it. (In other words, after ob_flush it's out of your control whether or not it gets immediately written to the browser).
So, short answer: There's no guaranteed way to do that.
Just a guess, you're likely looking for AJAX. Whenever people are trying to manipulate when page content loads as you're doing, AJAX is almost always the correct path.
If you want to continue a task in the background, you can use ignore_user_abort,  however, that is often not the optimal approach. You essentially lose control over that thread, and in my opinion, a web server thread is not where heavy processing belongs.
I would try to extract it out of the web facing stuff. This could mean a cron entry or just spawning a background process from inside of PHP (a process that though started from inside of script execution will not die with the script, and the script will not wait for it to finish before dying).
If you do go that route, it will mean that you can even make some kind of status system if necessary. Then you could monitor the execution and give the user periodic updates on the progress. (Technically you could make a status system with a ignore_user_abort-ed script too, but it doesn't seem as clean to me.)

I have done this in the past and this is how I solved it:
ob_start();

/*
 * Generate your output here
 */ 

// Ignore connection-closing by the client/user
ignore_user_abort(true);

// Set your timelimit to a length long enough for your script to run, 
// but not so long it will bog down your server in case multiple versions run 
// or this script get's in an endless loop.
if ( 
     !ini_get('safe_mode') 
     && strpos(ini_get('disable_functions'), 'set_time_limit') === FALSE 
){
    set_time_limit(60);
}

// Get your output and send it to the client
$content = ob_get_contents();         // Get the content of the output buffer
ob_end_clean();                      // Close current output buffer
$len = strlen($content);             // Get the length
header('Connection: close');         // Tell the client to close connection
header("Content-Length: $len");     // Close connection after $len characters
echo $content;                       // Output content
flush();                             // Force php-output-cache to flush to browser.
                                     // See caveats below.

// Optional: kill all other output buffering
while (ob_get_level() > 0) {
    ob_end_clean();
}

Understanding font file types for HTML/CSS

11:18 AM

Understanding Font File Types

The original snippet at the top of my previous post references a lot of files with strange extensions. Let's go over each one and get a better understanding of what they mean.

WOFF / WOFF2

Stands for: Web Open Font Format.
Created for use on the web, and developed by Mozilla in conjunction with other organizations, WOFF fonts often load faster than other formats because they use a compressed version of the structure used by OpenType (OTF) and TrueType (TTF) fonts. This format can also include metadata and license info within the font file. This format seems to be the winner and where all browsers are headed.
WOFF2 is the next generation of WOFF and boasts better compression than the original.

SVG / SVGZ

Stands for: Scalable Vector Graphics (Font)
SVG is a vector re-creation of the font, which makes it much lighter in file size, and also makes it ideal for mobile use. This format is the only one allowed by version 4.1 and below of Safari for iOS. SVG fonts are not currently supported by Firefox, IE or IE Mobile. Firefox has postponed implementation indefinitely to focus on WOFF.
SVGZ is the zipped version of SVG.

EOT

Stands for: Embedded Open Type.
This format was created by Microsoft (the original innovators of @font-face) and is a proprietary file standard supported only by IE. In fact, it’s the only format that IE8 and below will recognize when using @font-face.

OTF / TTF

Stands for: OpenType Font and TrueType Font.
The WOFF format was initially created as a reaction to OTF and TTF, in part, because these formats could easily (and illegally) be copied, However, OpenType has capabilities that many designers might be interested in (ligatures and such).

A Note on Performance

Web fonts are great for design but it's important to also understand their impact on web performance. Custom fonts often cause sites to take a performance hit because the font must be downloaded before it's displayed.
A common symptom used to be a brief moment where fonts first load as the fallback, then blink to the downloaded font. Paul Irish has an older post on this (dubbed "FOUT": Flash Of Unstyled Text).
These days, browsers are generally hiding the text before the custom font loads by default. Better or worse? You decide. You can exert some control over this through various techniques. A little out-of-scope for this article, but here's a trifecta of articles by Zach Leatherman to get you started down the rabbit hole:
Here are some more considerations when implementing custom fonts:

Watch the file size

Fonts can be surprisingly heavy, so lean towards options that offer lighter versions. For example, favor a font set that is 50KB versus one that weighs 400KB.

Limit the character set, if possible

Do you really need the bold and black weights for one font? Limiting your font sets to load only what is used is a good idea and there are some good tips on that here.

Consider system fonts for small screens

Many devices are stuck on crappy connections. One trick might be to target larger screens when loading the custom font using @media.
In this example, screens smaller than 1000px will be served a system font instead and screens that wide and above will be served the custom font.
@media (min-width: 1000px) { 
  body {
    font-family: 'FontName', Fallback, sans-serif; 
  }
}

Font Services

There are a number of services that will host fonts and provide access to commercially-licensed fonts as well. The benefits of using a service often boil down to having a large selection of legal fonts delivered efficiently (e.g. serving them on a speedy CDN).
Here are a few hosted font services:

What About Icon Fonts?

It's true, @font-face can load a font file full of icons that can be used for an icon system. However, I think you're far better off using SVG as an icon system. 

How to use External fonts in CSS? @font-face,.WOFF,.TTF. [Solved]

11:17 AM
This is the method with the deepest support possible right now. The @font-facerule should be added to the stylesheet before any styles.
@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); 
  src: url('webfont.eot?#iefix') format('embedded-opentype'), 
       url('webfont.woff2') format('woff2'), 
       url('webfont.woff') format('woff'), 
       url('webfont.ttf')  format('truetype'), 
       url('webfont.svg#svgFontName') format('svg'); 
}
Then use it to style elements like this:
body {
  font-family: 'MyWebFont', Fallback, sans-serif;
}

The WOFF Support: 

Things are shifting heavily toward WOFF and WOFF 2, so we can probably get away with:
@font-face {
  font-family: 'MyWebFont';
  src:  url('myfont.woff2') format('woff2'),
        url('myfont.woff') format('woff');
}
Chrome Safari Firefox Opera IE Android iOS 5+ 5.1+ 3.6+ 11.50+ 9+ 4.4+ 5.1+

If you need a sort of a happy medium between full support and practical support, this will cover a few more bases:
@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff2') format('woff2'),
       url('myfont.woff') format('woff'),
       url('myfont.ttf') format('truetype');
}
Chrome Safari Firefox Opera IE Android iOS 3.5+ 3+ 3.5+ 10.1+ 9+ 2.2+ 4.3+


If we're staking the farm on WOFF, then we can expect things to shift toward WOFF2 at some point in time. That means we can live on the bleeding edge with:
@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff2') format('woff2');
}
Chrome Safari Firefox Opera IE Android iOS 36+ No 35+ with flag 23+ No 37


Other Useful Techniques

@import

While @font-face is excellent for fonts that are hosted on our own servers, there may be situations where a hosted font solution is better. Google Fonts offers this as a way to use their fonts. The following is an example of using @import to load the Open Sans font from Google Fonts:
@import url(//fonts.googleapis.com/css?family=Open+Sans);
Then we can use it to style elements:
body {
  font-family: 'Open Sans', sans-serif;
}

<link>ing a stylesheet

Similarly, you could link to the same asset as you would any other CSS filter, in the <head> of the HTML document rather than in the CSS. Using the same example from Google Fonts, this is what we would use:
<link href='//fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
Then, we can style our elements like the other methods:
body {
  font-family: 'Open Sans', sans-serif;
}
Again, this is importing the @font-face rules but, instead of injecting them to our stylesheet, they are added to our HTML <head> instead.
It's about the same thing... both techniques download the assets needed.

Good Luck!

How to use iPad Specific CSS?

11:14 AM


How to use iPad-specific CSS?



Many people have been lately asking me to post things about iPad specific CSS. So here we go :

@media only screen and (device-width: 768px) { /* For general iPad layouts */ } @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) { /* For portrait layouts only */ } @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) { /* For landscape layouts only */ }



CSS Cross-browser min-width & max-width - Explained!

11:12 AM
Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.
For example:
@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}
Versus
@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}
I've found the best method is to write your default CSS for the older browsers, as older browsers including i.e. 5.5, 6, 7 and 8. Can't read @media. When I use @media I use it like this:
<style type="text/css">
    /* default styles here for older browsers. 
       I tend to go for a 600px - 960px width max but using percentages
    */
    @media only screen and (min-width:960px){
        /* styles for browsers larger than 960px; */
    }
    @media only screen and (min-width:1440px){
        /* styles for browsers larger than 1440px; */
    }
    @media only screen and (min-width:2000px){
        /* for sumo sized (mac) screens */
    }
    @media only screen and (max-device-width:480px){
       /* styles for mobile browsers smaller than 480px; (iPhone) */
    }
    @media only screen and (device-width:768px){
       /* default iPad screens */
    }
    /* different techniques for iPad screening */
    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
      /* For portrait layouts only */
    }

    @media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
      /* For landscape layouts only */
    }
</style>
But you can do whatever you like with your @media, This is just an example of what I've found best for me when building styles for all browsers.


Good Luck!

Sunday, November 13, 2016

How to get absolute path of Current script in PHP? [Quick & Easy]

5:28 PM

How to get absolute path of Current script in PHP?


This is the most easiest and quicker approach to this very novice matter...

Go ahead and try :

echo realpath(dirname(__FILE__));
If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__ with $_SERVER['PHP_SELF']. But be aware that PHP_SELF is a security risk!
example for URL:http://example.com/folder1/folder2/yourfile.php?var=blabla#12345

typical PHP codes:

$_SERVER["DOCUMENT_ROOT"] === /home/user/public_html
$_SERVER["SERVER_ADDR"]   === 143.34.112.23
$_SERVER['HTTP_HOST']     === example.com (or with WWW)
$_SERVER["REQUEST_URI"]   === /folder1/folder2/yourfile.php?var=blabla
__FILE__                  === /home/user/public_html/folder1/folder2/yourfile.php
basename(__FILE__)        === yourfile.php
__DIR__                   === /home/user/public_html/folder1/folder2 [same: dirname(__FILE__)]
$_SERVER["QUERY_STRING"]  === var=blabla

$_SERVER["REQUEST_URI"]   === /folder1/folder2/yourfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)  === /folder1/folder2/yourfile.php 
$_SERVER["PHP_SELF"]      === /folder1/folder2/yourfile.php

//if "YOURFILE.php" is included in "PARENTFILE.php" , and "PARENTFILE.PHP?abc"   is opened:
$_SERVER["PHP_SELF"]       === /parentfile.php
$_SERVER["REQUEST_URI"]    === /parentfile.php?abc
$_SERVER["SCRIPT_FILENAME"]=== /home/user/public_html/parentfile.php
str_replace($_SERVER["DOCUMENT_ROOT"],'', str_replace('\\','/',__FILE__ ) )  === /folder1/folder2/yourfile.php
Notice:
  • hastag (#...) url parts cant be detected from PHP (server-side). For that, use Javascript.
  • DIRECTORY_SEPARATOR returns \ for Windows-type hostings, instead of /*

For WordPress

home_url()                      //>     http://example.com
get_stylesheet_directory_uri()  //>     http://example.com/wp-content/themes/THEME_NAME  [same: get_bloginfo('template_url') ]
get_stylesheet_directory()      //>     /home/user/public_html/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__)        //>     http://example.com/wp-content/plugins/MY-PLUGIN/  [while used inside plugin.. same as:  plugins_url('',__FILE__) ]
plugin_dir_path(__FILE__)       //>     /home/user/public_html/wp-content/plugins/MY-PLUGIN/   [while used inside plugin]    



//===============MY EXAMPLES - USAGE============//
(i.e. wordpress is installed in subdirectory:  http://example.com/wpdir/)

define('domainURL',                 (((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' ).$_SERVER['HTTP_HOST']);
    // ----->  http://example.com
define('homeURL',                   home_url());
    // ----->  http://example.com/wpdir/
define('homeFOLD',                  str_replace(domainURL,'',   homeURL));
    // ----->                    /wpdir/
define('requestURI',                $_SERVER["REQUEST_URI"]);
    // ----->                    /wpdir/any-page?with=parameters
define('requestURIfromHome',        str_replace(homeFOLD, '',requestURI) );
    // ----->                          /any-page?with=parameters
define('requestURIWithoutParametr',parse_url(requestURIfromHome, PHP_URL_PATH));
    // ----->                    /wpdir/any-page
define('currentURL',                domainURL.requestURI);
    // -----> http://example.com/wpdir/any-page?with=parameters
define('THEME_URL',                 str_replace(domainURL, '', get_template_directory_uri()) );plugin_dir_url(__FILE__)) ); 
    // -----> http://example.com/wpdir/wp-content/themes/THE-THEME-NAME/
define('PLUGIN_URL',                str_replace(domainURL, '', plugin_dir_url(__FILE__)) ); 
    // -----> http://example.com/wpdir/wp-content/plugins/THE-PLUGIN-NAME/