Best Kali Linux Compatible Wireless Adapters/Dongles 2017

On 12/10/2017 1 Comment so far

Here are the best kali linux compatible wireless adapters and usb dongles for 2017. Kali Linux is a Linux distribution mainly used for Penetration Testing, accessing N/W Security & Ethical Hacking. The process of choosing a wireless adapter or usb dongle to work with Kali Linux is not an easy task. It's just because the Operating system doesn't support all kinds of wifi adapters.

For example Pentesting requires a card to go into monitor mode and do packet injection which all cards can't do it. The Card's chipset and drivers is what determines if an adapter is compatible with kali or not.

Below I have listed out the most popular chipsets for Kali linux and Wireless adapters compatible with them. They work well for Penetration testing too.

Popular Kali Linux Compatible Chipsets:

  • Atheros AR9271
  • Ralink RT3070
  • Ralink RT3572

Best Kali Linux Compatible Wireless Adapters:

1. Alfa AWUS036NHA (Atheros AR9271 Chipset Compatible)

Check Price @ Amazon

Alfa-AWUS036NHA

Alfa AWUS036NHA is a best wifi adapter for pentesting. For penetration testing, Atheros AR9271 is a good chipset and you can go for Alfa AWUS036NHA card if you plan to run Kali as VM. Just get the job done without hassle.

  • Compatible with any 802.11b, 802.11g or 802.11n routers using 2.4Ghz band
  • Supports multiple input multiple output
  • High speed transfer TX data rate of up to 150 mbps
  • Includes 4" detachable antenna of 5 dbi which can be upgraded up to 9 dbi.
  • Works with 64/128-bit wep, wpa, wpa2, tkip, aes security protocols.
  • Supports Windows 2000, XP 32/64, vista 32/64 & Windows 7 Platform. So compatible with Kali Linux running as VM on these hosts.

Get It Now From Amazon »

2. TP-Link TL-WN722N (AR9271 Chipset Compatible)

Check Price @ Amazon

best wifi card for kali linux

Another great USB Wireless Adapter for cheapest price. TP-Link TL-WN722N uses AR9271 Chipset and has great range of up to 150Mbps. The card is easy to set up and works perfectly with Kali Linux.

  • Supports Wireless speed of up to 150Mbps
  • Works both on Infrastructure and Ad-Hoc Mode
  • Includes a detachable 4dbi omni directional antenna
  • Supports WPS & USB 2.0
  • Compatible with Windows XP, Windows Vista, Windows 7, 8, 8.1 platforms

Get It Now From Amazon »

3. Alfa AWUSO36NH (RT3070 Chipset Compatible)

Check Price @ Amazon

best alfa wifi adapter for kali

One of the best wireless dongle for pentesting. This 2 Watt 802.11n compatible Wi-fi dongle is quite powerful and supports Ralink RT3070 Chipset. It has very good range and perfect for packet monitoring.

  • Compatible with any 2.4GHz routers of 802.11n, 802.11b/g/n wireless standards
  • Includes removable 4" - 5 dBi antenna and can be be upgraded up to 9dBi
  • Supports 64/128-bit WEP, WPA, WPA2, TKIP, AES Protocols
  • Compatible with Windows 2000, XP 32/64, Vista 32/64, Windows 7, Linux (2.4.x/2.6.x),and Mac (10.4.x/10.5.x)

Get It Now From Amazon »

4. Alfa AWUS036NEH (RT3070 Chipset)

Check Price @ Amazon

Alfa-AWUS036NEH

This Wi-Fi Dongle is similar to Alfa AWUSO36NH in specs and covers long range. Alfa AWUS036NEH is exceptional for penetration testing and is good at packet injection and monitoring.

  • Works well with any 802.11b/g and 'N' routers
  • Includes removable 4" 5dBi antenna (upgradable up to 9dBi)
  • Supports packet injection & monitor mode
  • Protocols supported - 64/128-bit WEP, WPA, WPA2, TKIP, AES
  • Compatible with Windows 2000, 32/64 bit XP, Vista, Windows 7, Linux (2.4.x/2.6.x), Mac (10.4.x/10.5.x) Power PC& PC.

Get It Now From Amazon »

5. Panda PAU05 (RT3070 Chipset)

Check Price @ Amazon

Panda-PAU05

Panda 300mbps wireless n usb adapter is very reasonably priced and works with 802.11g/n standard and offers a data speed of up to 300 Mbps. It is exceptionally good considering the price but make sure to download and install the latest driver (alone) for Windows 7 and leave the rest of the setup to Windows itself.

  • Compatible with any 802.11g or 802.11n 2.4Ghz wireless routers
  • Wireless speed of up to 300Mbps
  • Works with both infrastructure and ad-hoc modes
  • Security protocol compliant: 64/128bit WEP, WPA, WPA2, 802.1x and 802.11i, Cisco CCS V1.0, 2.0 and 3.0
  • Supports 32/64-bit Windows 8/7/Vista, Mac OS 10.4/10.5/10.6/10.7/10.8/10.9 and latest version of 32/64-bit Mint, Ubuntu, Fedora, openSUSE, etc.

Get It Now From Amazon »

6. Alfa AWUS051NH (Ralink RT3572 Chipset)

Check Price @ Amazon

Alfa-AWUS051NH

Alfa AWUS051NH is little expensive but has amazing signal reception and works well on Kali Linux and in 5Ghz Monitor mode.

  • It is compatible with 802.11n draft 3.0, 802.11a/b/g wireless standards
  • Work with 2.4GHz and 5.8GHz band and MIMO (Multiple Input Multiple Output)
  • Supports wireless transfer RX data rate of up to to 300 Mbps
  • Allows wireless data encryption with 64/128-bit WEP, WPA, WPA2, TKIP, AES Protocols
  • Compatible with Windows 2000, 32/64 bit XP & Vista, Linux (2.4.x/2.6.x), Mac (10.4.x/10.5.x) Power PC& PC.

Get It Now From Amazon »

What Makes a Wireless Adapter Compatible with Kali?

Kali is a popular Linux Distro commonly used by security and penetrating testing professionals. Not all wireless adapters are made to work with Kali Linux. Only the drivers and chipsets decides if they are compatibile with the OS or not.

In addition, if you run it as a VM, the USB adapter must also be compatible with the host operating system.

Any of the above recommended devices will be good for pentesting, but you are called to decide which one is right for your configuration.

Long-range adapters with big dBi antenna are great for distance but not exactly compact. On the other hand smaller ones with built-in antenna are good for staying low profile.

Over To You:

So these are the best wireless adapters and usb dongles for kali linux. Though all these adapters works well with Kali, just make sure if it is the right one for your environment. For example if you wish to run Kali on Virtual box in Windows 7 host then make sure the card is compatible with Windows 7 OS. Also you must be cautious about the coverage range. Antenna with bigger dBi would be better for longer range. This helps you avoid future trouble. If you find this useful please share it with others to give them good suggestion.

Also Read:

10 Best Laptops for Writers & Writing 2017

On 12/10/2017 Be the first to comment!

Are you looking for the best laptop for writers? Then here's our review for Top 10 Best Laptops for Writers and Writing 2017. No matter if you are a professional writer, seasonal or a novice there's a laptop for everyone's budget here. The laptops we have recommended are for people who use them mainly for writing purpose and made sure they got spacious backlit keyboard, eye friendly display, no overheating issues and light weight but sturdy chassis.

top-10-laptops-for-writers-writing

Best Writers Laptop Configuration:

Are there any special laptops made for writing? Well! No. But a laptop specifically used for writing must have certain features that would make a writer's life easier. Here we go.

  • Keyboard: Backlit Keyboard (to write in low-light conditions) with spacious palm rest.
  • Storage: At least 128GB SSD (SSD is faster and produce less heat. A must for professional writers who writes all day long)
  • RAM: 6 to 8GB RAM
  • Processor: Good Quad core processor like Intel i3
  • Portable: Light-weight chassis recommended if writers travel a lot.

Top 10 Best Laptops for Writers & Writing 2017:

The Best Laptop for Writers in 2017

1. ASUS ZenBook UX303UA

Check Price @ Amazon

best-laptop-for-writing-ZenBook-UX303UA

ASUS ZenBook UX303UA is our top pick in Top 10 Laptops for Writers sporting the right combination of power, elegance & portability. Priced under $800, the ultrabook comes with high-end hardware's and boots and loads documents with lightning speed and suffers no heating problem.

The laptop comes preinstalled with Windows 10 and sports Intel i5 processor coupled with 8GB RAM, abundant 256GB SSD storage & wide spaced keypad. Plus the high definition 13.3 inch screen makes it highly portable. Given the fact it weighs just 3 pounds you can stash it in your backpack and take it on go.

Besides its 7 hours of battery backup is another huge plus. There is no overheating with zenbook as it uses SSD for storage which is relatively fast and prone to less heat. Overall it's a great investment for serious writers who write for living.

Get It Now From Amazon »

Best Affordable Laptop for Writers under $600

2. Acer Aspire E15

Check Price @ Amazon

best-laptop-for-writers-Aspire-E-15

Acer Aspire E15 is the best cheap laptop for writers in 2017 with wide 15.6 inch Full HD screen and full-sized keyboard along with comfortable palm rest. In fact it is one of the best laptop keyboard for writers. It includes abundant SSD storage of 256GB GB to store all your writings and features latest Intel Core i5 processor, 8GB RAM, great battery backup and of all windows 10 OS.

If you are a novoice or a seasonal writer then there's no point in spending $1000 for a laptop. A decent mid-range device will do. At the price tag of just $550, Acer Aspire E15 is the perfect laptop for writers on budget.

It sports a good NVIDIA GPU so you can use it for gaming if you don't feel like writing all day. Another good reason to go for this gem:)

Get It Now From Amazon »

Best Cheap Laptop for Writers 2017

3. HP 15-AY011NR

Check Price @ Amazon

cheapest-laptop-for-writers-HP-15-ay011nr

HP 15-AY011NR is another good writing laptop you can get for $450. Probably this is the most affordable laptop with good specs tailored for a writer's needs. For such a budget device HP 15-AY011NR includes great hardware like 8GB RAM, Core i5 Processor and surprisingly 1TB of hard disk space.

It offers 15.6 inch wide FHD display and spaciously arranged keyboard with large palm rest area and comes pre-installed with Windows 10 OS to let you start work immediately after purchase.

The laptop has excellent battery life of seven hours and suitable for outdoor writing. Highly recommended for beginners & seasonal writers.

Get It Now From Amazon »

Best Laptop for Professional Writers

4. MacBook Pro ME865LL/A

Check Price @ Amazon

best-laptop-for-professional-writers-macbook-pro

MacBook Pro with Retina Display is the Perfect Laptop for Professional Writers. Writers who are used to sit and write for hours starring at the laptop screen might suffer from eye irritation, red or puffy eyes. Having a laptop like MacBook with Retina display will keep away eye strain.

Plus the device is highly portable being very thin and light-weight and fits in your smallest backpack easily. It comes with high-end features like 8GB RAM, 128GB storage space, 13.3 inch screen with retina display and very long battery life. Plus the keypad has comfortable palm rest space and backlit keys to let you write in low-light conditions.

Overheating is never an issue with MacBook. A high-end product recommended for serious writers.

Get It Now From Amazon »

Best Dell Laptop for Writers

5. Dell Inspiron

Check Price @ Amazon

top-laptop-for-writers-dell-inspiron

Dell Inspiron is another great laptop for professional writers. Professional writers do need a sturdy laptop with wide-screen, full-sized backlit keyboard to write on low-light conditions, ample storage space and good hardware. Dell Inspiron meets up with all these challenges without trouble and would be a great buy under $1000.

Provided the specs are latest with Windows 10 OS, powerful Intel i7 processor along with 8GB RAM, Touch-enabled 15.6 inch FHD Screen, abundant 1TB storage and backlit full-sized keyboard with comfortable palm area. The laptop is worth every penny you spend and has an excellent battery life of more than seven hours. Overall Dell Inspiron would be very good companion in your writing career.

Get It Now From Amazon »

Best Laptop for Serious Writers

6. Microsoft Surface Book

Check Price @ Amazon

top-writers-laptop-for-professionals-Surface-Book

An expensive high-end laptop from Microsoft and extremely powerful with stunning 12 hours of battery backup, high definition display and comfortable backlit keyboard to write on dim light conditions. Writing is joy with Surface Book and if you are a professional writer who writes for living, this would be the best investment you make for your career.

The product comes in six different versions and for full-time writers we would recommend a hardware combination of Intel i5 processor, 8GB RAM, 256GB SSD Storage. Videos & games are highly enjoyable in Surface Book's high definition screen. So if you are fed up with writing all day you can treat yourself for some entertainment. Highly recommended for professional writers.

Get It Now From Amazon »

Best Chromebook for Writers 2017

7. HP Chrome 14

Check Price @ Amazon

best-affordable-laptop-for-journalist-HP-Chrome-14

At 3.4 lbs HP Chrome 14 is a great laptop for writers on go and journalists on budget. It costs you less than $300 and has remarkable battery backup of 8 hours in one go. Plus access to Google apps and the ability to connect with various Wi-Fi hot spots are other great additions helpful for people who work as team and share information with other members of the team.

Get It Now From Amazon »

8. Samsung Chromebook 2

Check Price @ Amazon

best-budget-laptop-for-writing-Chromebook-2

Slim and Light-weight this Chromebook from Samsung runs on Chrome operating system and comes with very useful software packs. The software's like AirDroid Premium, Little Bridge & Wunderlist Pro helps you to manage all your android devices on the web and let you synchronize & transfer files with others on your team. The ergonomic well-spaced keyboard allows you to type fast. Given the fact there is no hard-disk you have to rely on cloud storages.

Get It Now From Amazon »

Best 2 in 1 Laptop for Writers

9. HP Pavilion 13 2-in-1 Laptop

Check Price @ Amazon

best-portable-laptop-for-writers-HP-Pavilion-13

HP Pavilion 13 is a touch-enabled hybrid laptop that duals as a Laptop & Tablet and a perfect fit for Journalists and Writers. It is highly portable with 13.3 inch high definition touch screen yet has spaciously formed keypad with comfortable palm rest and would be a great choice for writing.

It comes with windows 10 OS and powered with Intel i3 processor coupled with 8 GB RAM, 126GB SSD disk and 7 hours of battery backup. It makes for a great companion on your travel and can be bought for under $600.

Get It Now From Amazon »

Best Writers Laptop with Backlit Keyboard

10. Lenovo Yoga 3 Pro

Check Price @ Amazon

light-weight-laptop-for-writers-yoga-3-pro

Yoga 3 pro is another good mid-range laptop for writers from Lenovo brand. The laptop runs on windows 10 operating system and comfortable for writing with well-spaced backlit keyboard and 13.3-inch QHD glossy multi-touch display.

It packs powerful Intel Core Processor, 8GB RAM, and huge 256GB SSD to store all your files. With 13.3 inch it's very portable and if you like to write on outdoors then it easily sustains for up to 9 hours without power. There is no doubt Yoga 3 Pro comes with all good features a writer needs in a laptop and would be another great choice for writing.

Get It Now From Amazon »

Related: Best Laptops for Programming & Coding 2017

Over To You:

That's makes our recommendations for top 10 best laptops for writers. If you are a novice or a seasonal writer there is no point investing $1000 in a laptop. Budget or mid-range laptops from the list will do. On the other hand professional writers need powerful machines to cope up with their work all day. For them a high-end laptop would be the wise choice. However all of the above recommended laptops are great for writing with well-spaced backlit keyboard, comfortable palm rest, high definition screen and optimal performance.

Top 10 Best Laptops for Programming & Coding (Developers Choice) 2017

On 12/10/2017 1 Comment so far

Are you a developer or a programming student and wondering which the best laptop for programming is? Well! Here we have compiled out the list of Top 10 Best Laptops for Programming and Coding 2017 after thorough research on the market. Of course budget is the main constraint while making purchases and we have kept that it mind while making out this best developer laptops list. Be a budding developer, experienced programmer making several thousands every month or a computer science student on tight budget, there is a laptop for everyone's budget here.

top 10 best laptops for programming coding game development

Best Programming Laptop Configuration:

There is no such thing like special laptops made for programming or coding. But before buying a laptop specifically for programming, game development or coding you must consider certain features so that the laptop meets your programming requirements.

So what should you look for in a laptop you buy ideally for programming/coding/game development?

  • Powerful Processor like Intel Core i5, i7 or AMD A10 (or higher)
  • Minimum RAM of 8GB
  • Enough storage space (500GB HDD or preferably 128GB SSD as they are faster than HDD)
  • 2GB Dedicated Graphics card at the min. (if you are into game development this one holds high priority)
  • Good battery backup

And this one is of minor importance. Developer laptop needs to have full-size keyboard - spaciously well-placed and illuminated keys. If you are prone to work for long hours or low-lightings then I can't insist more. And here AndroidCanvasHQ has some pretty good recommendations on laptops with number pad. A great boon for coding work.

Top 10 Best Laptops for Coding and Programming:

1. Dell Inspiron i7559-763blk Programming Laptop

Check Price @ Amazon

best programming laptop dell inspiron i7559

Dell Inspiron i7559-763blk tops our list of Top 10 Best Laptops for Programming and Coding. This one is the ideal choice for programmers & game developers with the right amount of power, execution, and performance. Dell i7559 is powered with 6th generation Intel Core i7 Processor clocked at 2.3GHz together with 8GB DDR3L RAM and 4GB 960M NVIDIA Graphics card making it a perfect fit for serious gaming too. It sports a wide 15.6 inch screen which is Full HD and Anti-Glare and comes with excellent 256GB SSD. If you are a Windows lover then rejoice, this powerful beast comes pre-installed with Windows 10 which seals the deal.

Get It Now at Amazon

2. HP Pavilion 13-s128nr: Affordable Programming Laptop with Touchscreen

Check Price @ Amazon

affordable programming laptops hp pavilion 13

HP Pavilion 13-s128nr is a very affordable touchscreen laptop that doubles as a tablet too. Being stylish and portable this 2-in-1 hybrid laptop is definitely a looker and packs superb configuration to meet all your programming needs. HP Pavilion 13-s128nr is made to run high-end coding softwares with ease and packs Intel Core i5 processor, 8GB RAM and a compatible 13.3-inch FHD screen under its hood. And the best thing is, it comes pre installed with Windows 10 OS and SSD storage of 128GB which is much faster than the traditional HDD disks. Priced under $700 this is a great choice for beginners and programming students.

Get It Now at Amazon

3. MacBook Pro 15.4 inch Laptop: Best Programming Laptop Ever

Check Price @ Amazon

best macbook for programmers

It's not news, wide number of Programmers & Developers prefers MAC OS X over Windows or Ubuntu and so many of them own both Windows Laptop and MacBook for coding. If you are a professional with high-budget then MacBook Pro is the laptop you have to go for. It comes with 2.5GHz Intel Core i7 Quad-core Processor with insane 16GB RAM for mind blowing performance and smoothness. And the best part is the awesome 15.4 inch retina display along with AMD Radeon R9 M370X, Intel Iris Pro graphics and 512GB PCIe-based flash storage.

Get It Now at Amazon

4. Acer Aspire E 15: Budget Laptop for Software Development

Check Price @ Amazon

cheap laptop for programmers aspire e15

Acer Aspire E 15 is the most affordable laptop on the market without compromising specs and performance and priced below 600 dollars. The laptop is suitable for both programming and gaming with 6th generation Intel Core i5 6200U Processor coupled with NVIDIA GeForce GTX940MX 2GB Graphic card. It offers 256GB SSD for storage and 8GB RAM for handling high-end softwares without struggle. Overall Aspire E15 is the best laptop for coding on budget. Highly recommended!

Get It Now at Amazon

5. Lenovo Y700: Good Laptop for Coders & Game Developers

Check Price @ Amazon

best lenovo laptop for coding lenovo y700

Lenovo Y700 is the solid 15.6 inch coding and gaming laptop with massive 16GB RAM teamed up with 6th gen. Intel Core i7 6700HQ Processor clocked at 2.6 GHz. And the best part of Lenovo Y700 is it's Graphics processor. Whether you are an occasional gamer or professional game developer, it's powerful NVIDIA GeForce 960M Graphics card render the graphics in high definition. Besides it has got 15.6 inch large display and 1TB of storage which is great.

Get It Now at Amazon

6. ASUS K501UW: Cheapest Laptop for Game Developers

Check Price @ Amazon

cheap laptop for game developers asus k501uw

ASUS K501UW is the most affordable gaming laptop from Asus. It packs so much power with 6th generation Intel Core i7 Processor with turbo-boost teamed up with 8GB RAM and can run any programming softwares with ease. ASUS K501UW is recommended for any programming but comes with some high-end features especially beneficial for Game developers which are rare to see on a laptop in this price range. It comes fitted with powerful NVIDIA GTX series 960M graphic card, backlit full size keyboard to work in low-light conditions and dual fan cooling system with IceCool technology to keep it from heating due to rendering high-graphics.

Get It Now at Amazon

7. Lenovo IdeaPad 510: Best Programming Laptop 2017

Check Price @ Amazon

best laptop for developers

Lenovo IdeaPad 510 is another good programming laptop in 2017 for beginners and programming students. The laptop is powered with Intel core i7 processor and a graphics processor of NVIDIA GTX 940Mx coupled with 12GB RAM which is excellent when it comes to performance. It offers 15.6 inch Full HD display and spacious full-sized keyboards to aid type coding for long-hours without fatigue. Overall Lenovo IdeaPad 510 includes all the right specs required for coding but doesn't burn a hole in your pocket.

Get It Now at Amazon

8. Acer Aspire E5-573G-56RG: Cheap Laptop for Programming Students

Check Price @ Amazon

acer aspire e5-573g laptop for programming

Priced under $600 Acer Aspire E5-573G-56RG is probably the cheapest programming laptop you can get in the market. No matter if you are a game developer or a coder, Aspire E5-573G is what you want. The laptop boasts the right combination of power and performance packing 8GB DDR3L SDRAM, Intel Core i5 5200U (turbo boost up to 2.7 GHz) with 3MB Cache along with Nvidia GeForce 940 GPU of 2GB Video Ram. It packs 1TB of Hard Disk space, 15.6" Full HD 1080p screen, 4-5 hours of decent battery backup and the best of all is the pre-installed Windows 10 OS. What's more to ask? Just the right laptop for tight budget.

Get It Now at Amazon

9. ASUS Zenbook UX303UB: Portable Programming Laptop with Touchscreen

Check Price @ Amazon

portable laptop for programming zenbook ux303ub

If you want a portable laptop to meet your programming requirements, then this little genie is all you want. It comes with sleek and shiny outlook with compact 13.3 inch QHD Touchscreen and weighs next to nothing and perfectly suitable for travel. The ultrabook delivers lightning speed with powerful Intel Core i7 processor together with 12GB RAM and 512GB SSD storage which is amazing for its size. Supported with NVIDIA GTX 940M Graphics Processor, performance is not something you have to bother.

Get It Now at Amazon

10. MSI GE72 Apache Pro-003: Gaming + Programming Laptop

Check Price @ Amazon

best msi gaming laptop msi ge72

MSI GE72 Apache Pro-003 is another great gaming laptop with sleek look and advanced hardware architecture. Powered with 6th generation Intel Core i7 6700HQ Processor and NVIDIA GeForce GTX960M 2GB Graphics along with 16GB RAM, the laptops performance is spectacular. Also the bigger 17.3 inch Full HD Matte Screen with True Color Technology brings out the gaming characters to life. If you are not budget constraint and want mind-blowing gaming experience go for MSI GE72 Apache Pro-003.

Get It Now at Amazon

Also Read: Top 10 Best Laptops for Writers 2017

Over To You:

That's makes for our list of top 10 best programming laptops 2017. I hope our Laptop reviews have provided you the best choices in the market and will help you pick the best laptop for coding. Being a web developer myself, I can once again assure you that the laptops we have recommended are more than capable of meeting all your programming requirements. If you are a game developer or an avid gamer then go for laptops with high graphics card (GPU) otherwise you can settle for any one of the mid-level laptops from the list.

Sort Files by Last Modified Date in PHP

On 12/10/2017 4 Comments so far

Hi, in this post we'll discuss about a method to sort files in a directory/folder by last modified date in php. Though php language comes with a rich set of sorting functions such as sort() rsort() ksort() etc., none of them will directly suits for this purpose. In order to sort files in a folder, we should first copy the filenames from the said directory to an array and then define our custom sorting function to sort those files by last modified date. PHP's usort() is such function which we can use to sort arrays by the way we define.

sort-files-by-last-modified-date-in-php

How to Sort Files by Last Modified Date in PHP

Let me show you by an example how to perform this file sorting. Say I want to sort all the 'JPEG' image files from a directory according to their recently modified date and time. Here's the php code to do it.

<?php
// get current directory path
$dirpath = getcwd();
// set file pattern
$dirpath .= "\*.jpg";
// copy filenames to array
$files = array();
$files = glob($dirpath);

// sort files by last modified date
usort($files, function($x, $y) {
    return filemtime($x) < filemtime($y);
});

foreach($files as $item){
    echo basename($item) . " => Last Modified On " . @date('F d, Y, H:i:s', filemtime($item)) . "<br/>";
}
?>

// produces output

// image001.jpg => Last Modified On November 04, 2015, 17:53:24
// image002.jpg => Last Modified On October 23, 2015, 21:03:26
// image003.jpg => Last Modified On October 09, 2015, 21:23:15
// image004.jpg => Last Modified On July 03, 2015, 14:49:07
// image005.jpg => Last Modified On July 02, 2015, 22:32:03
// image006.jpg => Last Modified On February 02, 2015, 15:35:34

The above php script sorts out '*.jpg' files from current working directory.

The method glob() will return an array of file names with full path matching the given pattern.

And filemtime() will get the last modified date and time of a file in unix timestamp.

The function usort() will sort the given array by value based upon the user defined comparison function. In this case the comparison is based upon the last-modified date.

To sort all the files in a folder, just use the file pattern like this,

$dirpath .= "\*.*";

If you want to sort the files from different folders then change the $dirpath variable accordingly.

Recommended Read:

And that was all about sorting files by last modified date in php.

How to Convert XML File to Array in PHP

On 12/10/2017 Be the first to comment!

Hi! In this post let us see How to Convert XML File/String to Array in PHP. Its reverse process of converting array to xml has been already discussed and you can find that tutorial here. It’s a known fact that XML is used to store and exchange information among web services and still some of them provide their API response in xml format. In such case you have to parse those xml files and extract data to process it. PHP provides a handy library called SIMPLEXML to handle xml data. Here I’ll show you how easy it is to use simplexml library to parse and covert the xml file to php array.

convert xml to associative array in php

Converting XML File to PHP Array

Converting xml data into array is simpler than you think and we are going to take advantage of simplexml lib and json functions to complete the task with minimal code. Just take this below xml file as an example for our purpose.

Data.xml

<?xml version="1.0" ?> 
- <root>
    - <item0>
          <id>XYZ100</id> 
        - <personal>
              <name>Ashton Cox</name> 
              <gender>Male</gender> 
              <age>32</age> 
            - <address>
                  <street>7 24th Street</street> 
                  <city>New York</city> 
                  <state>NY</state> 
                  <zipcode>10038</zipcode> 
              </address>
          </personal>
        - <profile>
              <position>Team Lead</position> 
              <department>Software</department> 
          </profile>
      </item0>
    - <item1>
          <id>XYZ121</id> 
        - <personal>
              <name>Rhona Davidson</name> 
              <gender>Female</gender> 
              <age>40</age> 
            - <address>
                  <street>S2 115th Street</street> 
                  <city>New York</city> 
                  <state>NY</state> 
                  <zipcode>10100</zipcode> 
              </address>
          </personal>
        - <profile>
              <position>Integration Specialist</position> 
              <department>Operations</department> 
          </profile>
      </item1>
  </root>

Here is the php script to convert the above xml file to associative array.

<?php
// function to convert xml to php array
function xml2Array($filename)
{
    $xml = simplexml_load_file($filename, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    return json_decode($json,TRUE);
}

// function callback
$arr = xml2Array("Data.xml");
print_r($arr);

// produces output:

// Array ( [item0] => Array ( [id] => XYZ100 [personal] => Array ( [name] => Ashton Cox [gender] => Male [age] => 32 [address] => Array ( [street] => 7 24th Street [city] => New York [state] => NY [zipcode] => 10038 ) ) [profile] => Array ( [position] => Team Lead [department] => Software ) ) [item1] => Array ( [id] => XYZ121 [personal] => Array ( [name] => Rhona Davidson [gender] => Female [age] => 40 [address] => Array ( [street] => S2 115th Street [city] => New York [state] => NY [zipcode] => 10100 ) ) [profile] => Array ( [position] => Integration Specialist [department] => Operations ) ) ) 
?>

We have written a php function xml2Array() that takes up the xml filename as argument and convert it into array.

The method simplexml_load_file($filename, "SimpleXMLElement", LIBXML_NOCDATA) converts the given XML file into a SimpleXMLElement object. Its second param SimpleXMLElement specifies the class name of the new object created. And the third param LIBXML_NOCDATA is a constant that tells to merge CDATA as text nodes. Learn more about the method here.

And the method json_encode($xmlstring) returns the JSON representation of the given object.

Finally json_decode($json, TRUE) decodes the given JSON string into an array or object. Providing the second param TRUE tells it to return an associative array.

Converting XML String to PHP Array

Alternatively if you have xml data as string and wish to convert to array, then you have to use this statement instead of loading from the file.

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);

This converts a well-formed xml string to a simplexmlelement object. You have to change only this line and the rest of the code remains the same.

Read Also:

Thus with the help of this php script you can easily convert xml file or string to an array.

How to Merge Two JSON Objects into One using jQuery

On 12/10/2017 Be the first to comment!

Hi, at times you may want to merge multiple json objects into a single entity when working with different APIs. Recently I also found myself in such situation and came across a very simple and effective solution with jQuery. In this tutorial, I'll show you how to merge two json objects into one using jQuery library. jQuery provides several utility functions and the extend() method is one among them. It merges two or more objects together into the first object (i.e., first parameter passed to the function).

merge two json objects in jquery

Merging Two JSON Objects using jQuery

In order to merge the json objects we have to use jQuery's extend() function which takes up multiple parameters. Here is the syntax for the method.

jQuery.extend([deep], target, object1 [, objectN])
  • Where 'deep' when set as TRUE, makes the merging process recursive (optional).
  • 'target' is the object which consists of the merged contents.
  • 'object1' is the first object to be merged.
  • 'objectN' is the additional objects to be merged.

Both 'deep' & 'target' parameters are optional and if the target object is not provided, then the subsequent object(s) contents will be merged and added to the first given object.

Here is the simple example of merging two json objects in jquery and displaying the result in a <div> block.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Merge Two JSON Objects in jQuery Example</title>
    <script src="js/jquery-1.10.2.js"></script>
</head>
<body>
    <div id="output"></div>
    <script>
    $(document).ready(function() {
        var obj1 = {"name": "Garrett Davidson", "gender": "male", "dob": "1990/04/20"};
        var obj2 = {"position": "System Administrator", "location": "New York"};

        $.extend(obj1, obj2);
        $('#output').text(JSON.stringify(obj1));
    });
    </script>
</body>
</html>

// produces output:

// obj1
// {"name":"Garrett Davidson","gender":"male","dob":"1990/04/20","position":"System Administrator","location":"New York"}

// obj2
// {"position": "System Administrator", "location": "New York"}

In the above script, we have two objects, 'obj1' and 'obj2' that contains personal and professional details of an employee.

$.extend(obj1, obj2); statement merges the contents of obj2 with obj1 as we haven't provided target object. In order to display the merged contents in a readable format, we have used JSON.stringify(obj1); statement to convert the object into json string.

Alternatively you can also preserve the original objects by passing an empty object as 'target' parameter like this,

<script>
$(document).ready(function() {
    var obj1 = {"name": "Garrett Davidson", "gender": "male", "dob": "1990/04/20"};
    var obj2 = {"position": "System Administrator", "location": "New York"};

    var obj = $.extend({}, obj1, obj2);
    $('#output').text(JSON.stringify(obj));
});
</script>

// produces output: 

// obj1
// {"name": "Garrett Davidson", "gender": "male", "dob": "1990/04/20"}

// obj2
// {"position": "System Administrator", "location": "New York"}

// obj
// {"name":"Garrett Davidson","gender":"male","dob":"1990/04/20","position":"System Administrator","location":"New York"}

If you want to just only verify if the object contents are properly merged, then you can log and check it in the browser console like this,

var obj = $.extend({}, obj1, obj2);
console.log(obj);

And that was all about merging two json objects into one using jquery.

Recommended Read: How to Read and Parse JSON String in jQuery

Don't Miss: Display JSON in HTML Table using jQuery DataTables Plug-in

Inline Editing using PHP MySQL and jQuery AJAX

On 12/08/2017 Be the first to comment!

Hi! Today we will see about ajax inline editing using php and mysql. Inline editing allows users to rapidly modify web page contents in place without the requirement of forms. Popular sites like Facebook, Twitter, etc. employ this technique so that users can change their profile information without having to navigate through separate forms. Using HTML5's 'contenteditable' on page elements will take care of inline editing. For example, you can convert a plain html table into an editable table by setting 'contenteditable = true'.

If you are new to inline editing, take a look at html5 editable table tutorial.

PHP MySQL Inline Editing using jQuery AJAX:

The 'contenteditable' attribute can be used on almost all html elements, but the data edited by user is only temporary. It will be lost when the page is refreshed. Therefore, you must use ajax to send the data back to the server and store it in database for future use.

Here, let's see a demo with editable html table listing records from mysql table. Each time the user makes some changes, the edited data will be sent to the server through an ajax call and will be updated in the database using php.

During editing, the table cell will change to red background and to green when completed.

We'll need the following files for our demo,

  1. Bootstrap.css - To design the user interface
  2. jQuery.js - To post data to server via ajax
  3. dbconnect.php - Takes care of database connection
  4. index.php - Main user interface that contains html table, css and javascript functions.
  5. savecustomer.php - PHP script to update database table.

STEP-1) Create Database

First we need a mysql database and table to use in our example. Run this below sql file on mysql. It will create a database, a table and add some sample records in it.

CREATE DATABASE `mysite`;
USE `mysite`;

CREATE TABLE IF NOT EXISTS `customers` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(60) NOT NULL,
  `location` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

INSERT INTO `customers` (`id`, `name`, `email`, `location`) VALUES
(1, 'Jim Connor', 'jimconnor@yahoo.com', 'Las Vegas'),
(2, 'Mark Higgins', 'mark.higgins21@yahoo.com', 'San Francisco'),
(3, 'Austin Joseph', 'austin.joseph.boston@gmail.com', 'Boston'),
(4, 'Sean Kennedy', 'seankennedy01@gmail.com', 'Seattle'),
(5, 'Rose Harris', 'roseharris@gmail.com', 'New York'),
(6, 'Lilly Whites', 'lillywhites@outlook.com', 'New York'),
(7, 'Jennifer Winters', 'jennie.winters001@gmail.com', 'Miami'),
(8, 'Michael Bruce', 'michaelbruce78@yahoo.com', 'Los Angeles'),
(9, 'John Alex', 'johnalex@example.com', 'Chicago'),
(10, 'Demi Milan', 'demimilan@gmail.com', 'Austin');

STEP-2) Open Database Connection

Next, we must establish the connection to database. The following script will open a php-mysql connection.

dbconnect.php

<?php
// connection settings
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'mysite';

//connect to mysql database
$con = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($con));
?>

STEP-3) Fetch Records from MySQL Table

Next fetch records from the mysql table we have created in step-1.

<?php
include_once 'dbconnect.php';

// fetch records
$sql = "select * from customers order by id";
$result = mysqli_query($con, $sql);
?>

STEP-4) Create HTML5 Editable Table

Then create an html5 table with inline editing enabled. And loop through the mysql resultset and display the records on the table one by one.

<div id="mytable">
    <h3 class="text-center bg-primary">AJAX Inline Editing HTML5 Table - Demo</h3>
    <table class="table table-bordered">
        <tr class="bg-primary">
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Location</th>
        </tr>
        <?php
        while($row = mysqli_fetch_array($result)) { ?>
        <tr>
            <td><?php echo $row['id']; ?></td>
            <td contenteditable="true" onfocus="changeBackground(this);" onblur="saveData(this, '<?php echo $row["id"]; ?>', 'name');"><?php echo $row['name']; ?></td>
            <td contenteditable="true" onfocus="changeBackground(this);" onblur="saveData(this, '<?php echo $row["id"]; ?>', 'email');"><?php echo $row['email']; ?></td>
            <td contenteditable="true" onfocus="changeBackground(this);" onblur="saveData(this, '<?php echo $row["id"]; ?>', 'location');"><?php echo $row['location']; ?></td>
        </tr>
        <?php } ?>
    </table>
</div>

In the above markup, we have added two event functions for each cell in the table. One is to change the background color on focus and the other is to submit edited cell data to the server on blur event.

STEP-5) Change Table Cell Background On Focus

Now it's time to add javascript functions. First let's create the changeBackground() method which will change the background color of the cell to red when it gets focus.

function changeBackground(obj) {
    $(obj).removeClass("bg-success");
    $(obj).addClass("bg-danger");
}

STEP-6) Make AJAX Call to Server

Next is the ajax function saveData(). This function will post the edited data, record id and column name to the server as a json string. Once the database update is complete, the background color of the <td> element will change to green.

function saveData(obj, id, column) {
    var customer = {
        id: id,
        column: column,
        value: obj.innerHTML
    }
    $.ajax({
        type: "POST",
        url: "savecustomer.php",
        data: customer,
        dataType: 'json',
        success: function(data){
            if (data) {
                $(obj).removeClass("bg-danger");
                $(obj).addClass("bg-success");
            }
        }
   });
}

Following is the complete script for the index.php file.

index.php

<?php
include_once 'dbconnect.php';
// fetch records
$sql = "select * from customers order by id";
$result = mysqli_query($con, $sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Inline Editing in PHP MySQL</title>
    <meta charset="utf-8"> 
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
    <style type="text/css">
    #mytable {
        margin: 0 auto;
        width: 60%;
    }
    </style>
</head>
<body>
<br/>
    <div id="mytable">
        <h3 class="text-center bg-primary">AJAX Inline Editing HTML5 Table - Demo</h3>
        <table class="table table-bordered">
            <tr class="bg-primary">
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Location</th>
            </tr>
            <?php
            while($row = mysqli_fetch_array($result)) { ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td contenteditable="true" onfocus="changeBackground(this);" onblur="saveData(this, '<?php echo $row["id"]; ?>', 'name');"><?php echo $row['name']; ?></td>
                <td contenteditable="true" onfocus="changeBackground(this);" onblur="saveData(this, '<?php echo $row["id"]; ?>', 'email');"><?php echo $row['email']; ?></td>
                <td contenteditable="true" onfocus="changeBackground(this);" onblur="saveData(this, '<?php echo $row["id"]; ?>', 'location');"><?php echo $row['location']; ?></td>
            </tr>
            <?php } ?>
        </table>
    </div>
    <script src="js/jquery-1.10.2.js"></script>
    <script type="text/javascript">
    function changeBackground(obj) {
        $(obj).removeClass("bg-success");
        $(obj).addClass("bg-danger");
    }

    function saveData(obj, id, column) {
        var customer = {
            id: id,
            column: column,
            value: obj.innerHTML
        }
        $.ajax({
            type: "POST",
            url: "savecustomer.php",
            data: customer,
            dataType: 'json',
            success: function(data){
                if (data) {
                    $(obj).removeClass("bg-danger");
                    $(obj).addClass("bg-success");
                }
            }
       });
    }
    </script>
</body>
</html>

STEP-7) Save Edited Data into MySQL Database

Finally, we need to store the data edited by the user on the database. Here is the php code to do it.

savecustomer.php

<?php
include_once "dbconnect.php";

$sql = "update customers set " . $_POST["column"] . "='" . $_POST["value"] . "' where id=" . $_POST["id"];
if (mysqli_query($con, $sql))
    echo "true";
else
    echo "false";
?>

Done! Now we have all the necessary files in place. Run index.php and you will see a nice table that lists the records from the database. Edit some table cells and the cell color will change to red during editing.

php mysql inline editing ajax

Once you finish editing, the table cell turns green as soon as it lost focus.

inline editing php mysql jquery ajax

Refresh the page and the data you have modified will remain there. It means that we have saved the edited data on the database successfully.

Read Also:

That explains about inline editing using php, mysql and ajax. Inline editing will enhance user experience and also save you from creating multiple web forms. You can apply the technique with any html element. I hope you like this tutorial. Please don't forget to share it on social media. Good day!!!

Contact Form

Name

Email *

Message *