Featured Post Today
print this page
Latest Post
Showing posts with label PHP Learning. Show all posts
Showing posts with label PHP Learning. Show all posts

PHP Error Handling and Debugging: A Practical Guide for Beginners

 

PHP Error Handling and Debugging

Every PHP developer eventually hits the same wall: a blank white screen, a cryptic warning, or a fatal error that gives almost no clue about what actually went wrong. Learning to read, handle, and prevent these errors is one of the fastest ways to level up as a PHP developer. This guide walks through the error types you'll encounter, how to handle them properly, and the tools that make debugging far less painful.

Understanding the Different Types of PHP Errors

PHP doesn't have just one kind of error — it has several, and knowing the difference helps you react correctly.

Notices are the mildest. They tell you something might be wrong, like using an undefined variable, but the script keeps running.

Warnings are more serious. Something failed, like including a file that doesn't exist, but PHP still tries to continue execution.

Fatal Errors stop the script completely. Calling a function that doesn't exist, or a class that hasn't been defined, will halt everything.

Parse Errors happen before your code even runs. A missing semicolon or an unclosed bracket triggers this, and PHP refuses to execute the file at all.

Understanding which category you're dealing with tells you how urgently it needs fixing and whether your application can keep functioning around it.

Turning On Error Reporting the Right Way

A huge number of "mystery bugs" are actually errors that were happening silently the whole time. On a development environment, always make sure error reporting is fully visible:

error_reporting(E_ALL);
ini_set('display_errors', 1);

This forces PHP to show every notice, warning, and error directly on the page, which is invaluable while building or debugging locally.

On a production site, you should do the opposite — never display raw errors to visitors, since they can leak file paths, database structure, or other sensitive details. Instead, log errors quietly to a file:

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');

This way, you still capture everything for debugging later, without exposing internals to the public.

Using Try/Catch for Controlled Error Handling

Modern PHP encourages handling foreseeable failures with exceptions rather than letting the script die. Wrap risky code — database queries, file operations, API calls — in a try/catch block:

try {
    $result = riskyDatabaseOperation();
} catch (Exception $e) {
    error_log('Database operation failed: ' . $e->getMessage());
    echo 'Something went wrong. Please try again later.';
}

This pattern does two important things: it prevents a single failure from crashing the whole application, and it gives you a clean place to log what happened for later debugging, while showing the user a friendly message instead of a stack trace.

For more precise handling, you can catch specific exception types:

try {
    $pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    die('Unable to connect to the database.');
}

Custom Error Handlers

If you want full control over how errors are processed across your entire application, PHP lets you register a custom error handler:

function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $message = "Error [$errno]: $errstr in $errfile on line $errline";
    error_log($message);
 
    if ($errno == E_USER_ERROR) {
        echo 'A critical error occurred. Our team has been notified.';
        exit(1);
    }
}
 
set_error_handler('customErrorHandler');

This is especially useful if you want consistent logging formats, or if you want to send critical errors to a monitoring service instead of just a text file.

Debugging Tools That Actually Save Time

var_dump() and print_r() are the simplest tools for inspecting variables. var_dump() shows the data type alongside the value, which is often the missing clue when a comparison isn't behaving as expected.

var_dump($userInput); // shows type + value
print_r($arrayData);  // more readable for arrays

Xdebug is the most powerful step up from manual dumping. Once installed, it gives you breakpoints, step-through debugging, and detailed stack traces directly in your code editor (VS Code and PHPStorm both support it well). If you're debugging anything beyond a simple script, Xdebug will save hours compared to scattering var_dump() calls everywhere.

Logging strategically is often more useful than either. Instead of dumping variables to the screen, log key checkpoints to a file so you can trace exactly where execution diverged from what you expected:

error_log('User ID at checkout: ' . $userId);

Common Mistakes That Cause Silent Failures

A few issues come up again and again for PHP developers, especially beginners:

  • Comparing values with == instead of === — PHP's loose comparison can produce surprising results ("0" == false is true), so use strict comparison when the type matters.
  • Forgetting to check if a database query actually succeeded before using its result.
  • Suppressing errors with the @ symbol — this hides the error entirely instead of handling it, making debugging much harder later.
  • Not validating user input before using it in file paths, database queries, or included files.

Final Thoughts

Good error handling isn't just about preventing crashes — it's about making problems visible to you (through logs) while staying invisible to your users (through clean fallback messages). Start with proper error reporting during development, wrap risky operations in try/catch, log meaningfully, and reach for Xdebug once var_dump() stops being enough. These habits alone will cut your debugging time dramatically as your PHP projects grow.

0 comments

PHP Brief Definition

PHP definition

PHP Brief Definition

PHP is a widely-used open-source scripting language designed for web development and can also be embedded in HTML.

Key Points:

  • Meaning: PHP originally stood for "Personal Home Page," but now it is a recursive acronym for "PHP: Hypertext Preprocessor."
  • Purpose: It is primarily used to build dynamic and interactive websites.
  • Platform: Most commonly used on Linux web servers but is also compatible with various platforms like Windows and macOS.
  • Features:
    • Server-side execution.
    • Integration with databases like MySQL, PostgreSQL, and others.
    • Free and open-source with extensive community support.
  • Use Cases: Content Management Systems (like WordPress), e-commerce websites, APIs, and more.

In essence, PHP is a powerful tool for developers to create dynamic, database-driven websites efficiently.

0 comments

Increase Max Execution Time With .htaccess file

Max Execution Time
How to Increase Max Execution Time Using .htaccess

If you’ve been struggling with increasing the max execution time for your website, you’re not alone. Many users encounter this issue, especially when using cPanel, which doesn’t allow direct modifications to php.ini. However, if you’re using the Apache system with PHP, there’s a simple workaround using the .htaccess file.

This guide provides a shortcut to solve the issue without requiring access to WHM, WHMCS, root privileges, or a VPS/dedicated server.


Requirements

  1. Updated PHP Version: Ensure your PHP version is at least 5.x or higher.
  2. Verify PHP Version:
    • Create a file named info.php.
    • Add the following code to the file:
      php

      <?php phpinfo(); ?>
    • Upload this file to your server (e.g., yourdomain.com/info.php).
    • Open the file in your browser and search for PHP Version.
  3. Check Current Max Execution Time:
    • On the same page, search for max_execution_time to view the current limit.

Steps to Increase Max Execution Time

  1. Open your website’s .htaccess file.
    • This file is located in your website’s root directory.
  2. Add the following code to the .htaccess file:
    apache

    <IfModule mod_php5.c> php_value max_execution_time 900 </IfModule>
    • Explanation:
      • 900 seconds equals 15 minutes.
      • You can adjust this value based on your requirements.
  3. Save the file and test your changes.

Important Notes

  • This method works only if your server uses the Apache module and PHP is configured accordingly.
  • For PHP 7.x or later, you may need to replace 
mod_php5.c 
with 
mod_php7.c.
  • Always back up your .htaccess file before making changes.

By following this simple guide, you can increase your website’s max execution time without relying on root access or advanced hosting features. If you encounter issues, consult your hosting provider for further assistance.

0 comments

How to add custom PHP Page or PHP Code in Wordpress?

PHP Code in Wordpress

How to Add PHP Code in WordPress Posts and Pages (Without Plugins)

By default, WordPress does not allow PHP code execution inside posts or pages for security reasons. However, if you need to add custom PHP functions without relying on plugins, follow this simple method to integrate PHP into your WordPress content.


Method: Using a Custom Template File

Step 1: Duplicate an Existing Template File

  • Navigate to your WordPress theme folder:
    wp-content/themes/your-theme/
  • Copy and duplicate page.php or single.php
  • Rename the duplicate file (e.g., custom-template.php)

Step 2: Modify the File Header

Open the newly created custom-template.php file and add the following lines at the top:


 <?php  
 ///////////////////////////////////////
 // File Name: FusionMarketPro.Online //
 ///////////////////////////////////////
 ?>  

4) This will allow WordPress to recognize it as a custom template.

Step 3: Add Your PHP Code

Inside custom-template.php, you can now insert your PHP functions anywhere within the content structure:

 <?php  
    echo "Hello, this is a custom PHP function in WordPress!";
?>

Step 4: Assign the Custom Template to a Page

  1. Create a new page or post in WordPress.
  2. In the Page Attributes section (right sidebar), select "Custom PHP Template" from the Template dropdown.
  3. Publish or update the page.

Benefits of This Method

✅ No need for additional plugins
✅ Direct control over PHP functions
✅ Customizable for advanced functionality

This approach is ideal for developers who want greater flexibility while maintaining WordPress security best practices.

0 comments

PHP | Detect User Browser Language

How to detect user browser language and how to use it in URL.
If you add this script above your file code.
Then url will be :
  • www.domain.com/index.php?lang=en
  • www.domain.com/index.php?lang=ar
  • www.domain.com/index.php?lang=es
  • www.domain.com/index.php?lang=fr
  • www.domain.com/index.php?lang=hu
  • www.domain.com/index.php?lang=ra
 Region wise. and you can use this to multilingual website.

 <?php  
 //Redirect by language  
 $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  
 if(!isset($_GET['lang']))  
 {  
      //Retrieve location, set time  
      if(!isset($lang))  
      {  
           header("location: ".$_SERVER['PHP_SELF']);  
           exit;  
      }  
      else  
      {  
           header("location: ".$_SERVER['PHP_SELF']."?lang=".$lang);  
           exit;  
      }  
 }  
 ?>  

0 comments

Convert XML to PHP Array | Multilingual + Country wise SEO URL Solution

Multilingual + Country wise SEO URL Solution:

Example
https://www.samijeweller.com.com/index.php?loc=pk&lang=en
Here I did deep research that how can I use PHP for Multilingual websites?
But we need to keep in mind some topics like
  1. User IP Address Function
  2. User Language Function
  3. IP to XML
  4. XML to PHP Array Conversion
  5. URL Concept
  6. Language And Area codes concept
If you know these things then, you can use this function easily.

 <?php  
 //Redirect by language  
 $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);  
 $context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));  
 //redirect by IP  
 $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];  
 $ip = $_SESSION['ip'];  
 $data = file_get_contents("http://api.hostip.info/get_html.php?ip=".$ip."&position=true");  
 $arrayofdata = explode("\n", $data);  
 $country = explode(":", $arrayofdata[0]);  
 $count = explode(" ", $country[1]);  
 if(!isset($_GET['lang']) AND !isset($_GET['loc']))  
 {  
      //Retrieve location, set time  
      if(empty($count))  
      {  
           header("location: index.php?loc=us-en&lang=".$lang);  
           exit;  
      }  
      else  
      {  
           header("location: index.php?loc=".strtolower(trim($count[2],"()"))."&lang=".$lang);  
           exit;  
      }  
 }  
 ?>  

0 comments

PHP | Website Validation Function


php validation function

PHP | Website Validation Function

Could you clarify what type of website validation function you need in PHP? Are you looking for:

URL validation (checking if a URL is valid)
Domain validation (checking if a domain exists)
Form input validation (ensuring users enter a valid website in a form)
Server-side HTTP status check (checking if a website is online or returning a specific response)

Let me know your specific requirement, and I'll provide you with a proper PHP validation function!

function validate_web($input_web)
   {  
   $input_web = preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $input_web);
   $input_web = trim($input_web);  
            $input_web = htmlspecialchars($input_web);  
            $input_web = stripcslashes($input_web);
   return $input_web;
   }

0 comments

PHP | Email Validation Function

PHP Email Validation Function
function validate_email($input_email)
   {  
   $input_email = preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $input_email);
   $input_email = trim($input_email);  
            $input_email = htmlspecialchars($input_email);  
            $input_email = stripcslashes($input_email);
   return $input_email;
   }
0 comments

PHP | Name Validation Function

PHP Name Validation Function
function validate_name($input_name)
   {  
   $input_name = preg_match("/^[a-zA-Z ]*$/", $input_name);
   $input_name = trim($input_name);  
            $input_name = htmlspecialchars($input_name);  
            $input_name = stripcslashes($input_name);
   return $input_name;
   }
0 comments

PHP | Number Validation Function

PHP number validation function
function validate_number($input_number)
   {  
   $input_number = preg_match ("/^[0-9]*$/", $input_number);
   $input_number = trim($input_number);  
            $input_number = htmlspecialchars($input_number);  
            $input_number = stripcslashes($input_number);
   return $input_number;
   }
0 comments

PHP | Form Validation Function

PHP Form Validation Function for your site.
function validate_email($input_email)
   {  
   $input_email = preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $input_email);
   $input_email = trim($input_email);  
            $input_email = htmlspecialchars($input_email);  
            $input_email = stripcslashes($input_email);
   return $input_email;
   }
0 comments

PHP | How to destroy session?

PHP Session
On +Wizpert, Someone asked me that how to destroy session?
Session is used for specific purpose. like
  • Login user
  • Review creation
  • Forms Creation
  • Check Out system
  • And more
In this code you will learn, How to destroy session on logout click?


 <?php  
 $_SESSION = array(); // Oh Sorry here you need to null all sessions  
 setcookie(session_name(), '', time()-60); // here you will set cookies time back to age. like time()-60 mean . 1 minute before now.  
 session_destroy(); // here you will delete session  
 header("Location: login.php"); // here you will be reallocated to login.php page.  
 exit; // page code will be exit.  
 ?>  

I hope this can help you.
0 comments

PHP | Compare Arrays (Indexed Arrays, Associative Arrays, Multidimensional arrays)

PHP | Compare Arrays


 In Arrays lecture, I described about types of Array.
Types of Array in PHP

  1. Indexed arrays - Arrays with numeric index
  2. Associative arrays - Arrays with named keys
  3. Multidimensional arrays - Arrays containing one or more arrays
Here you will come to know that how to compare PHP arrays and how to fetch same value. Sometimes you have to get user detail and compare their attributes. 
Just like
  1. Reviews
  2. Top Contributors 
  3. Levels
  4. Addresses
  5. Cast
  6. Religion
  7. Country
  8. and more
And this question makes you confuse that how to compare and how to fetch same values with simple PHP functions.
The most important thing you need to understand
array_intersect
Concept. Array_Intersect is used to fetch same values between two arrays.
Here you will come to know, How to check arrays values for duplication?

Compare Arrays Code:

(Indexed Arrays, Associative Arrays, Multidimensional arrays)


 <?php  
      $array1 = array('Samee', 'Ullah', 'Feroz');  
      $array2 = array('SEO', 'SMO', 'PPC', 'Samee');  
      $campare = array_intersect($array1, $array2);  
      print_r($campare);  
      echo "<br />";  
      // => Output would be <=  
      // Array ( [0] => Samee )   
      $array1 = array('author' => 'Samee', 'Ullah', 'Feroz');  
      $array2 = array('SEO', 'SMO', 'PPC', 'worker' => 'Samee');  
      $campare = array_intersect($array1, $array2);  
      print_r($campare);  
      echo "<br />";  
      // => Output would be <=  
      // Array ( [author] => Samee )  
      $array1 = array('Samee', 'Ullah', array('Mohammad', 'Feroz', 'Din'));  
      $values = array_values($array1);  
      $array2 = array('SEO', 'SMO', 'PPC', 'Samee', 'Feroz');  
      foreach($values as $array)  
      {  
           $multiarray = array_intersect($array, $array2);  
      }  
      print_r($multiarray);  
      // => Output would be <=  
      // Array ( [1] => Feroz )  
 ?>  


Most Wanted Terms:
  1. php compare arrays
  2. php array compare
  3. php compare array
  4. php compare two arrays
  5. compare arrays php
  6. php compare array values
  7. php compare 2 arrays
  8. compare two arrays php
  9. array compare php
  10. php array of arrays
0 comments

How to use class="Active" in navigation, If you are using static pages?

navigation with URL
My Local Project for Getacho Company
I am working on my own company project. I am using Pixelogic static theme. I created different files for different website parts. like
  1. Menu.php
  2. Header.php
  3. Footer.php
Like it. But here I was facing a problem in class="active" Code. It was like

 <nav class="navigation">  
   <ul class="sf-menu" style="float:left;">  
     <li class="active"><a href="index.php">Home</a>  
     </li>  
     <li><a href="about.php">About</a></li>  
     <li><a href="portfolio.php">Portfolio</a>  
     <li><a href="forums/">Forums</a>  
     </li>  
     <li><a href="blog/">Blog</a>  
     </li>  
     <li><a href="contact.php">Contact</a>  
       <ul class="sub-menu main-ul">  
       <li><a href="support/">Support</a></li>  
       <li><a href="support/">Live Chat</a></li>  
       </ul>  
     </li>  
     <li><a href="user/">User Panel</a>  
       <ul class="sub-menu main-ul">  
       <li><a href="user/seo/">SEO Panel</a></li>  
       </ul>  
     </li>  
   </ul>  
 </nav>  

But here I was getting some problem that how to move class="active" according to static current page.
Then I consulted with my friends and someone suggested me a code. now it is working.

Code was :

 <?php  
      $url = $_SERVER['REQUEST_URI'];  
      if (strpos($url,'about.php') !== false)  
           echo 'class="active"';  
 ?>  

Here you need to understand STRPOS function.
I used same code in my navigation. Now navigation is working good. Now navigation code is

 <div id="menu" class="clearfix">  
   <nav class="navigation">  
     <ul class="sf-menu" style="float:left;">  
       <li   
       <?php   
       $url = $_SERVER['REQUEST_URI'];  
       if (strpos($url,'index.php') !== false)  
       {  
       echo 'class="active"';  
       }  
       ?>  
       ><a href="index.php">Home</a>  
       </li>  
       <li   
       <?php   
       $url = $_SERVER['REQUEST_URI'];  
       if (strpos($url,'about.php') !== false)  
       {  
       echo 'class="active"';  
       }  
       ?>  
       ><a href="about.php">About</a></li>  
       <li   
       <?php   
       $url = $_SERVER['REQUEST_URI'];  
       if (strpos($url,'portfolio.php') !== false)  
       {  
       echo 'class="active"';  
       }  
       ?>  
       ><a href="portfolio.php">Portfolio</a>  
       <li><a href="forums/">Forums</a>  
       </li>  
       <li><a href="blog/">Blog</a>  
       </li>  
       <li   
       <?php   
       $url = $_SERVER['REQUEST_URI'];  
       if (strpos($url,'contact.php') !== false)  
       {  
       echo 'class="active"';  
       }  
       ?>  
       ><a href="contact.php">Contact</a>  
         <ul class="sub-menu main-ul">  
         <li><a href="support/">Support</a></li>  
         <li><a href="support/">Live Chat</a></li>  
         </ul>  
       </li>  
       <li><a href="user/">User Panel</a>  
         <ul class="sub-menu main-ul">  
         <li><a href="user/seo/">SEO Panel</a></li>  
         </ul>  
       </li>  
     </ul>  
   </nav>  
 </div>  

Guidance by :  Nahyan Shiwani
4 comments

All Country List Static Array in PHP With Drop Down Option

All Countries List
County List
There are about 242 counties in this world. May be I also don't know all names. But as developer, we may need to add country list in registration form. You can get complete country list as static array from QWC. You just need to copy code and paste to your site. If you are beginner then you need to learn about ForEach Loop to understand this code.
Complete Country List Code is available below.
 <?php  
 $countrylist = array(  
      'AD' => 'Andorra',  
      'AE' => 'United Arab Emirates',  
      'AF' => 'Afghanistan',  
      'AG' => 'Antigua and Barbuda',  
      'AI' => 'Anguilla',  
      'AL' => 'Albania',  
      'AM' => 'Armenia',  
      'AN' => 'Netherlands Antilles',  
      'AO' => 'Angola',  
      'AQ' => 'Antarctica',  
      'AR' => 'Argentina',  
      'AS' => 'American Samoa',  
      'AT' => 'Austria',  
      'AU' => 'Australia',  
      'AW' => 'Aruba',  
      'AZ' => 'Azerbaijan',  
      'BA' => 'Bosnia and Herzegovina',  
      'BB' => 'Barbados',  
      'BD' => 'Bangladesh',  
      'BE' => 'Belgium',  
      'BF' => 'Burkina Faso',  
      'BG' => 'Bulgaria',  
      'BH' => 'Bahrain',  
      'BI' => 'Burundi',  
      'BJ' => 'Benin',  
      'BM' => 'Bermuda',  
      'BN' => 'Brunei Darrussalam',  
      'BO' => 'Bolivia',  
      'BR' => 'Brazil',  
      'BS' => 'Bahamas',  
      'BT' => 'Bhutan',  
      'BV' => 'Bouvet Island',  
      'BW' => 'Botswana',  
      'BY' => 'Belarus',  
      'BZ' => 'Belize',  
      'CA' => 'Canada',  
      'CC' => 'Cocos (keeling) Islands',  
      'CD' => "Congo, Democratic People's Republic",  
      'CF' => 'Central African Republic',  
      'CG' => 'Congo, Republic of',  
      'CH' => 'Switzerland',  
      'CI' => 'Cote D Ivoire',  
      'CK' => 'Cook Islands',  
      'CL' => 'Chile',  
      'CM' => 'Cameroon',  
      'CN' => 'China',  
      'CO' => 'Colombia',  
      'CR' => 'Costa Rica',  
      'CS' => 'Serbia and Montenegro',  
      'CU' => 'Cuba',  
      'CV' => 'Cap Verde',  
      'CS' => 'Christmas Island',  
      'CY' => 'Cyprus Island',  
      'CZ' => 'Czech Republic',  
      'DE' => 'Germany',  
      'DJ' => 'Djibouti',  
      'DK' => 'Denmark',  
      'DM' => 'Dominica',  
      'DO' => 'Dominican Republic',  
      'DZ' => 'Algeria',  
      'EC' => 'Ecuador',  
      'EE' => 'Estonia',  
      'EG' => 'Egypt',  
      'EH' => 'Western Sahara',  
      'ER' => 'Eritrea',  
      'ES' => 'Spain',  
      'ET' => 'Ethiopia',  
      'FI' => 'Finland',  
      'FJ' => 'Fiji',  
      'FK' => 'Falkland Islands (Malvina)',  
      'FM' => 'Micronesia, Federal State of',  
      'FO' => 'Faroe Islands',  
      'FR' => 'France',  
      'GA' => 'Gabon',  
      'GB' => 'United Kingdom (GB)',  
      'GD' => 'Grenada',  
      'GE' => 'Georgia',  
      'GF' => 'French Guiana',  
      'GG' => 'Guernsey',  
      'GH' => 'Ghana',  
      'GI' => 'Gibraltar',  
      'GL' => 'Greenland',  
      'GM' => 'Gambia',  
      'GN' => 'Guinea',  
      'GP' => 'Guadeloupe',  
      'GQ' => 'Equatorial Guinea',  
      'GR' => 'Greece',  
      'GS' => 'South Georgia',  
      'GT' => 'Guatemala',  
      'GU' => 'Guam',  
      'GW' => 'Guinea-Bissau',  
      'GY' => 'Guyana',  
      'HK' => 'Hong Kong',  
      'HM' => 'Heard and McDonald Islands',  
      'HN' => 'Honduras',  
      'HR' => 'Croatia/Hrvatska',  
      'HT' => 'Haiti',  
      'HU' => 'Hungary',  
      'ID' => 'Indonesia',  
      'IE' => 'Ireland',  
      'IL' => 'Israel',  
      'IM' => 'Isle of Man',  
      'IN' => 'India',  
      'IO' => 'British Indian Ocean Territory',  
      'IQ' => 'Iraq',  
      'IR' => 'Iran (Islamic Republic of)',  
      'IS' => 'Iceland',  
      'IT' => 'Italy',  
      'JE' => 'Jersey',  
      'JM' => 'Jamaica',  
      'JO' => 'Jordan',  
      'JP' => 'Japan',  
      'KE' => 'Kenya',  
      'KG' => 'Kyrgyzstan',  
      'KH' => 'Cambodia',  
      'KI' => 'Kiribati',  
      'KM' => 'Comoros',  
      'KN' => 'Saint Kitts and Nevis',  
      'KP' => "Korea, Democratic People's Republic",  
      'KR' => 'Korea, Republic of',  
      'KW' => 'Kuwait',  
      'KY' => 'Cayman Islands',  
      'KZ' => 'Kazakhstan',  
      'LA' => "Lao People's Democratic Republic",  
      'LB' => 'Lebanon',  
      'LC' => 'Saint Lucia',  
      'LI' => 'Liechtenstein',  
      'LK' => 'Sri Lanka',  
      'LR' => 'Liberia',  
      'LS' => 'Lesotho',  
      'LT' => 'Lithuania',  
      'LU' => 'Luxembourgh',  
      'LV' => 'Latvia',  
      'LY' => 'Libyan Arab Jamahiriya',  
      'MA' => 'Morocco',  
      'MC' => 'Monaco',  
      'MD' => 'Moldova, Republic of',  
      'MG' => 'Madagascar',  
      'MH' => 'Marshall Islands',  
      'MK' => 'Macedonia',  
      'ML' => 'Mali',  
      'MM' => 'Myanmar',  
      'MN' => 'Mongolia',  
      'MO' => 'Macau',  
      'MP' => 'Northern Mariana Islands',  
      'MQ' => 'Martinique',  
      'MR' => 'Mauritania',  
      'MS' => 'Montserrat',  
      'MT' => 'Malta',  
      'MU' => 'Mauritius',  
      'Mv' => 'Maldives',  
      'MW' => 'malawi',  
      'MX' => 'Mexico',  
      'MY' => 'Malaysia',  
      'MZ' => 'Mozambique',  
      'NA' => 'Namibia',  
      'NC' => 'New Caledonia',  
      'NE' => 'Niger',  
      'NF' => 'Norfolk Island',  
      'NG' => 'Nigeria',  
      'NI' => 'Nicaragua',  
      'NL' => 'Netherlands',  
      'NO' => 'Norway',  
      'NP' => 'Nepal',  
      'NR' => 'Nauru',  
      'NU' => 'Niue',  
      'NZ' => 'New Zealand',  
      'OM' => 'Oman',  
      'PA' => 'Panama',  
      'PE' => 'Peru',  
      'PF' => 'French Polynesia',  
      'PG' => 'papua New Guinea',  
      'PH' => 'Phillipines',  
      'PK' => 'Pakistan',  
      'PL' => 'Poland',  
      'PM' => 'St. Pierre and Miquelon',  
      'PN' => 'Pitcairn Island',  
      'PR' => 'Puerto Rico',  
      'PS' => 'Palestinian Territories',  
      'PT' => 'Portugal',  
      'PW' => 'Palau',  
      'PY' => 'Paraguay',  
      'QA' => 'Qatar',  
      'RE' => 'Reunion Island',  
      'RO' => 'Romania',  
      'RU' => 'Russian Federation',  
      'RW' => 'Rwanda',  
      'SA' => 'Saudi Arabia',  
      'SB' => 'Solomon Islands',  
      'SC' => 'Seychelles',  
      'SD' => 'Sudan',  
      'SE' => 'Sweden',  
      'SG' => 'Singapore',  
      'SH' => 'St. Helena',  
      'SI' => 'Slovenia',  
      'SJ' => 'Svalbard and Jan Mayen Islands',  
      'SK' => 'Slovak Republic',  
      'SL' => 'Sierra Leone',  
      'SM' => 'San Marino',  
      'SN' => 'Senegal',  
      'SO' => 'Somalia',  
      'SR' => 'Suriname',  
      'ST' => 'Sao Tome and Principe',  
      'SV' => 'El Salvador',  
      'SY' => 'Syrian Arab Republic',  
      'SZ' => 'Swaziland',  
      'TC' => 'Turks and Caicos Islands',  
      'TD' => 'Chad',  
      'TF' => 'French Southern Territories',  
      'TG' => 'Togo',  
      'TH' => 'Thailand',  
      'TJ' => 'Tajikistan',  
      'TK' => 'Tokelau',  
      'TM' => 'Turkmenistan',  
      'TN' => 'Tunisia',  
      'TO' => 'Tonga',  
      'TP' => 'East Timor',  
      'TR' => 'Turkey',  
      'TT' => 'Trinidad and Tobago',  
      'TV' => 'Tuvalu',  
      'TW' => 'Taiwan',  
      'TZ' => 'Tanzania',  
      'UA' => 'Ukraine',  
      'UG' => 'Uganda',  
      'UM' => 'US Minor Outlying Islands',  
      'US' => 'United States',  
      'UY' => 'Uruguay',  
      'UZ' => 'Uzbekistan',  
      'VA' => 'Holy See (City Vatican State)',  
      'VC' => 'Saint Vincent and the Grenadines',  
      'VE' => 'Venezuela',  
      'VG' => 'Virgin Islands (British)',  
      'VI' => 'Virgin Islands (USA)',  
      'VN' => 'Vietnam',  
      'VU' => 'Vanuatu',  
      'WF' => 'Wallis and Futuna Islands',  
      'WS' => 'Western Samoa',  
      'YE' => 'Yemen',  
      'YT' => 'Mayotte',  
      'YU' => 'Yugoslavia',  
      'ZA' => 'South Africa',  
      'ZM' => 'Zambia',  
      'ZW' => 'Zimbabwe'  
 ); ?>  
 <html lang="us-en" xml:lang="us-en">  
   <head>  
           <style>  
                .form{  
                     margin:10px auto;  
                }  
                .form label, select{  
                     display:inline-block;  
                     float:left;  
                }  
                .form label{  
                     width:100px;  
                }  
                .body{  
                     width:400px;  
                     height:50px;  
                     background-color:#C33;  
                     padding:20 20 20 20;  
                     margin:300px auto;  
                }  
     </style>  
   </head>  
   <body>  
        <div class="body">  
       <form class="form">  
            <div><label for="usstates"><b>Countries:</b></label></div>  
              <div><select name="states" id="usstates">  
                     <option>Select Country</option>  
                               <?php  
               foreach($countrylist as $countrycode => $countryname)  
               {  
                 echo'<option value="'.$countrycode.'">'.$countryname.'</option>';  
               }  
             ?>  
                      </select>  
                          </div>  
                </form>  
     </div>  
      </body>  
 </html>  

If you are from USA also get US States List code.
4 comments

US States List Static PHP Array with Drop Down Option

US States List in PHP
PHP States List Code Result

US States List with Static Array in PHP with Drop Down Option. You just need to copy it and add to your site. For this code, you just need to learn ForEach Loop in PHP.

US States Array List In PHP


 <?php  
 $usstates = array(  
   'AK' => 'Alaska',  
   'AZ' => 'Arizona',  
   'AR' => 'Arkansas',  
   'CA' => 'California',  
   'CO' => 'Colorado',  
   'CT' => 'Connecticut',  
   'DE' => 'Delaware',  
   'DC' => 'District of Columbia',  
   'FL' => 'Florida',  
   'GA' => 'Georgia',  
   'HI' => 'Hawaii',  
   'ID' => 'Idaho',  
   'IL' => 'Illinois',  
   'IN' => 'Indiana',  
   'IA' => 'Iowa',  
   'KS' => 'Kansas',  
   'KY' => 'Kentucky',  
   'LA' => 'Louisiana',  
   'ME' => 'Maine',  
   'MD' => 'Maryland',  
   'MA' => 'Massachusetts',  
   'MI' => 'Michigan',  
   'MN' => 'Minnesota',  
   'MS' => 'Mississippi',  
   'MO' => 'Missouri',  
   'MT' => 'Montana',  
   'NE' => 'Nebraska',  
   'NV' => 'Nevada',  
   'NH' => 'New Hampshire',  
   'NJ' => 'New Jersey',  
   'NM' => 'New Mexico',  
   'NY' => 'New York',  
   'NC' => 'North Carolina',  
   'ND' => 'North Dakota',  
   'OH' => 'Ohio',  
   'OK' => 'Oklahoma',  
   'OR' => 'Oregon',  
   'PA' => 'Pennsylvania',  
   'RI' => 'Rhode Island',  
   'SC' => 'South Carolina',  
   'SD' => 'South Dakota',  
   'TN' => 'Tennessee',  
   'TX' => 'Texas',  
   'UT' => 'Utah',  
   'VT' => 'Vermont',  
   'VA' => 'Virginia',  
   'WA' => 'Washington',  
   'WV' => 'West Virginia',  
   'WI' => 'Wisconsin',  
   'WY' => 'Wyoming');  
 ?>  
 <html lang="us-en" xml:lang="us-en">  
   <head>  
           <style>  
                .form{  
                     margin:10px auto;  
                }  
                .form label, select{  
                     display:inline-block;  
                     float:left;  
                }  
                .form label{  
                     width:75px;  
                }  
                .body{  
                     width:250px;  
                     height:50px;  
                     background-color:#C33;  
                     padding:20 20 20 20;  
                     margin:300px auto;  
                }  
     </style>  
   </head>  
   <body>  
        <div class="body">  
       <form class="form">  
            <div><label for="usstates"><b>States:</b></label></div>  
              <div><select name="states" id="usstates">  
                               <?php  
               foreach($usstates as $statcode => $statname)  
               {  
                 echo'<option value="'.$statcode.'">'.$statname.'</option>';  
               }  
             ?>  
                      </select>  
                          </div>  
                </form>  
     </div>  
      </body>  
 </html>  
0 comments

Simple Login Page And Its Code For Creating Sassion


Here you can create user sassion and detect Login Errors by this form. Easy and simple code for newbies.
 <?php session_start(); ?>  
 <?php require_once("includes/connection.php"); ?>  
 <?php  
      if(!isset($_SESSION['username']))  
      {  
           $error= array();  
           if(isset($_POST['submit']))  
           {  
                //Get values from form  
                $username = $_POST['username'];  
                $password = $_POST['password'];  
                $query = "select * from users where username = '" . mysql_real_escape_string($username) . "'";  
                $query_run = mysqli_query($connection, $query);  
                if(!$query_run)  
                     echo 'username, password query is not working well. <br />' . mysqli_connect_error();  
                if(mysqli_num_rows($query_run) != 0 )  
                {  
                     $user = mysqli_fetch_array($query_run);  
                     if($username == $user['username'])  
                     {                      
                          if($password == $user['password'])  
                          {  
                               $_SESSION['username'] = $username;  //User session is created here
                               header("Location: index.php");  
                               exit;  
                          }  
                          else  
                          {  
                               array_push($error, 'password Wrong');  
                          }  
                     }  
                     else  
                     {  
                          array_push($error, 'Username Wrong');  
                     }  
                }  
                else  
                {  
                     array_push($error, 'Login Error');  
                }  
           }  
      }  
      else  
      {  
           header('Location: signup.php');  
           exit;  
      }  
 ?>  
 <div align="left" style="float:right">  
 <h2 align="center">Login Panel for Developer</h2>  
 <form method="post" action="login.php">  
      <label for="username">Username: </label><input name="username" type="text" id="username" /><br />  
   <label for="password">Password: </label><input type="password" name="password" id="password" /><br />  
   <input type="submit" name="submit" value="Login" />  
 </form>  
 <?php  
      if(isset($_POST['submit']))  
                {  
                     echo $error[0];  
                }  
           ?>  
 </div>  

0 comments

Slug Create Function in PHP. URL Rewriting According to SEO Rules

SEO friendly Slug is very important in Search Engine Optimization. It is used to rewrite your URL as your title.
as if you write title: "My Name Is Sami" And if it is a page. Then
Its URL will be :
www.QWC.me/?page=1 [1 Is Page ID]

If you use title in URL it can be like it
www.QWC.me/?page=my20%name20%is20%sami

But if you use slug function: URL will be SEO friendly like

www.QWC.me/?page=my-name-is-sami

There are many function: I am going to add 2 good functions for it. there is no any personal PHP built in function.

1:
 function slug($str, $replace=array(), $delimiter='-')  
      {  
           if( !empty($replace) )  
      {  
           $str = str_replace((array)$replace, ' ', $str);  
      }  
           $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);  
           $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);  
           $clean = strtolower(trim($clean, '-'));  
           $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);  
           $clean = form_validation($clean);  
           return $clean;  
 }  


2:
 function slug2($string){  
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);  
   return $slug;  
 }  
0 comments

Get Row Data in Tables from MySQL

This small code is used by Pakistan Floor Mills. Here you can easily understand that how to show rows data from your database to your table in front end.
Use it and learn from it.

insert data form
This code will tell you how to get data from array and how to show in fields.
Setup a database connection with following code.
 -- phpMyAdmin SQL Dump  
 -- version 4.0.4  
 -- http://www.phpmyadmin.net  
 --  
 -- Host: localhost  
 -- Generation Time: Nov 12, 2013 at 06:49 PM  
 -- Server version: 5.6.12-log  
 -- PHP Version: 5.4.16  
 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";  
 SET time_zone = "+00:00";  
 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;  
 /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;  
 /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;  
 /*!40101 SET NAMES utf8 */;  
 --  
 -- Database: `asia`  
 --  
 -- --------------------------------------------------------  
 --  
 -- Table structure for table `test`  
 --  
 CREATE TABLE IF NOT EXISTS `test` (  
  `sno` int(4) NOT NULL,  
  `packing` varchar(20) NOT NULL,  
  `weight` int(4) NOT NULL  
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1;  
 --  
 -- Dumping data for table `test`  
 --  
 INSERT INTO `test` (`sno`, `packing`, `weight`) VALUES  
 (1, 'Ghee 16 kgs', 16),  
 (2, 'Ghee 10 kgs', 10),  
 (3, 'Ghee 5 kgs', 5);  
 /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;  
 /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;  
 /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;  

phpmysql
See this SQL file Image
Get Row Data in Tables from MySQL
Now when you press this button results should be here. like that
code is here check it.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>BROWSE DATA </title>

 <style type="text/css">
 
 html {
 overflow:auto;
 }
 
 body {
 background-color:#FFFFFF;
 margin:0 auto;
 }
 
  
 #mypopup2
 {
 float: left;
 width: 250px; height: 350px;
 background: #90bade; 
 border: 1px solid #069;
 text-align:center;
 padding:2px;
 margin-top:150px;
 margin-left:50px;
 overflow:auto;
 }
 
 
 #header
 {
 background-color:#3399FF;
 background-position:left center;
 line-height:25px;
 font-size:22px;
 color:#FFFF33;
 font-weight:600;
 border-bottom:1px solid #6699CC;
 padding:10px;
 }
 
 .design12 {
 background-image:url(Images/disk.png);
 background-position:left center;
 background-repeat:no-repeat;
 background-color:#FF9;
 border:1px solid #88de85;
 -webkit-border-radius:7px;
 -moz-border-radius:7px;
 font-size:15px;
 font-weight:700;
 font-family:verdana;
 color:#0d5f83;
 width:100px;
 cursor:hand;
 padding:9px;
 }
 
 .design13 {
 background-image:url(Images/reload_16.png);
 background-position:left center;
 background-repeat:no-repeat;
 background-color:#CF9;
 border:1px solid #88de85;
 -webkit-border-radius:7px;
 -moz-border-radius:7px;
 font-size:15px;
 font-family:verdana;
 font-weight:700;
 color:#0d5f83;
 width:100px;
 cursor:hand;
 padding:9px;
 }
 
 
 .txt
 {
 width:150px;
 font-family:Arial, Helvetica, sans-serif;
 font-size:14px;
 font-weight:300;
 }
 
 td
 {color:#6600CC;}
 
 </style>
    
    <!-- PHP Code START -->

<?php 

 if(isset($_POST['submit']))
 {
  // Connection variables 
  $host="localhost"; 
  $username="root"; 
  $password=""; 
  $db_name="asia";  
  
  // Connect to database 
  $con = mysqli_connect($host, $username, $password); 
  
  // Connect result 
  if(!$con)
  { 
   die('Error Connecting to Database: ' . mysqli_connect_error()); 
  } 
  
  // Database Selection 
  $sel = mysqli_select_db($con, $db_name); 
  
  // Database Selection result 
  if(!$sel)
  { 
   echo ('Error selecting Database: ' . mysqli_connect_error()); 
  } 

    $query  = 'select * from test';
      $result = mysqli_query($con, $query);
    $count = mysqli_num_rows($result);
    $row = mysqli_fetch_array($result);  
    
   if(!$result)
    echo 'select query error or data not found'; 

   }  
   else
   {
 $i = '';
 $count = '';
  $row = array('sno' => '', 'packing' => '', 'weight' => '');
   }
   ?>
 <!-- PHP Code END -->

 </head>
 
 <body>

 <div id="mypopup2" >
 <div id="header"><img src="Images/book_open.png" align="left">Browse Data</div>
 <div style="margin-top:10px;">

 <form name="form1" method="POST" action="#">
 
 <table border="1" cellpadding="1" cellspacing="1" bgcolor="silver" align="center" width="95%" >
    
 
 <th width="20%">Code</th>
 <th width="50%">Product</th>
 <th width="20%">Weight</th>
    <?php 
  if(isset($_POST['submit']))
  {
   $i = 1;
   while($i <= $count)
    {
       echo"<tr>";
     echo "<td>" . $row['sno'] . "</td>";
     echo "<td>" . $row['packing'] . "</td>";
     echo "<td>" . $row['weight'] . "</td>";
     echo "</tr>";
     $row = mysqli_fetch_array($result); 
     $i++;
    } 
  }


   echo "</table><br>";

 ?>
 </table>
 

 <div style="margin-top:125px;text-align:center;margin-top:100px;">
    <input type="submit" name="submit" value="Brow" class="design12">
 <input type="submit" name="button2" value="Clear" class="design13">
    </div>
 </form>
 </div>
 </div>
</body>
</html>

Result Output is :
Get Row Data in Tables from MySQL

Now it is your turn read this code, understand it and align it yourself by using great CSS skills.
0 comments

Echo Rules / Problems in PHP Language

Echo is used to show output results in PHP. But sometimes you get confuse for solving simple problems. like

How to add Conditional Statement within echo statement?
 It is wrong to use if conditional statement within echo statement. You should use ternary operator within echo statement. like
 echo '<li' . ($sel_subject == $subject['id']) ? 'class="selected"' : '' . '>';  

Can we use echo statement within echo statement?
No we can not use echo statement within echo statement. It is bad logic. 

Can we use echo with double or single quotes?
Yes; you can use  echo with double and single quotes like

 echo 'This is Quality Written Codes Blog';  
Output is : This is Quality Written Codes Blog

 echo "This is Quality Written Codes Blog";  
Output is : This is Quality Written Codes Blog

What is concatenation in echo statement? 
Concatenation is sued to connect two quotes blocks. like 

 echo "My Blog Name is " . "Quality Written Codes";  

" . " dot is used to add concatenation.

How to use backslash within echo?
There are two ways to use backslash within echo tag.

You can use single quote if you want to use backslash; like it

 echo 'This is Quality Written Codes Blog And My Name is \ Samee Ullah Feroz \';  
Its output is
This is Quality Written Codes Blog and My Name is \ Samee Ullah Feroz \

If you use double quotes for echo statement. then you need to remember this solutions.
  1. \/ => /
  2. \" => "
  3. \/\/ => //
 echo "This is \"Quality Written Codes\" Blog and my name is \\ Samee Ullah Feroz \\";  
Its output is 
This is Quality Written Codes Blog and My Name is \ Samee Ullah Feroz \

How to use Variables within and with echo?
You can use different methods for it. like 

 $blog = "Quality Written Codes";  
 echo "$blog";  
 echo '{$blog}'  
 echo $blog;  

Read More about it in our previous post : Display of Variables
0 comments
 
Copyright © 2011-2026. Samee Articles - All Rights Reserved
Proudly powered by Blogger