Featured Post Today
print this page
Latest Post
Showing posts with label Download PHP Scripts. Show all posts
Showing posts with label Download PHP Scripts. 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

Date List Static Array with PHP Function Drop Down

Date List Static Array with PHP Function Drop Down :

Date list static array can help you to design contact form in offline mood. With this code, you can add dates in your form without using API system.

 <?php   
      $date = array(   
      '1'=>'1',  
      '2'=>'2',  
      '3'=>'3',  
      '4'=>'4',  
      '5'=>'5',  
      '6'=>'6',  
      '7'=>'7',  
      '8'=>'8',  
      '9'=>'9',  
      '10'=>'10',  
      '11'=>'11',  
      '12'=>'12',  
      '13'=>'13',  
      '14'=>'14',  
      '15'=>'15',  
      '16'=>'16',  
      '17'=>'17',  
      '18'=>'18',  
      '19'=>'19',  
      '20'=>'20',  
      '21'=>'21',  
      '22'=>'22',  
      '23'=>'23',  
      '24'=>'24',  
      '25'=>'25',  
      '26'=>'26',  
      '27'=>'27',  
      '28'=>'28',  
      '29'=>'29',  
      '30'=>'30',  
      '31'=>'31');   
 ?>   
  <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="dates"><b>date:</b></label></div>   
        <div><select name="date" id="dates">   
                 <?php   
         foreach($date as $dates => $datenow)   
         {   
          echo'<option value="'.$dates.'">'.$datenow.'</option>';   
         }   
        ?>   
            </select>   
              </div>   
         </form>   
    </div>   
    </body>   
  </html>   

0 comments

PHP | Login Form | User Will Redirect According To Category

mysql database user category

Login Form Code As Category System:

Sometime you have to redirect user according to his category / position to specific page. So, here this login form code can help you. It is simple code and localhost tested.

 <?php  
  //header('location: index.php');  
  //session_start();  
 function confirm_query($data)  
      {  
           if(!$data)  
                die("Query Failed: " . mysqli_connect_error());       
      }  
 $username = $_POST['username'];  
 $password = $_POST['password'];  
 $host = "localhost";  
 $dbuser = "root";  
 $dbpass = "";  
 $db = "estate";  
      $con = mysqli_connect($host, $dbuser); //Connection with server  
      confirm_query($con);  
      $connection = mysqli_select_db($con, $db); //Database is connected here  
      confirm_query($connection);  
 if(isset($_POST['submit']))  
 {  
      $query = "SELECT * FROM users where username = '{$username}' and password = '{$password}';";  
      $all_users = mysqli_query($con, $query);  
      if(!$all_users)  
           echo 'user pass query not working;' . mysqli_connect_error();  
      $user = mysqli_fetch_array($all_users);  
      if(mysqli_num_rows($all_users) != 0)  
      {  
           if($username == $user[username] AND $password == $user[password])  
           {  
                if($user[Category] == "Receptionist")  
                {  
                     $_SESSION['username'] = $username;  
                     header("location: receptionist.html");  
                     exit;  
                }  
                //Example Like uncomment and change.   
                //make sessions and add code start_session(); in all pages start.  
                /*elseif($user[Category] == "Receptionist")  
                {  
                     $_SESSION['username'] = $username;  
                     header("location: receptionist.html");  
                     exit;  
                }*/  
           }  
      }  
 }  
 else  
 {  
      header("location: login.html");  
      exit;  
 }  
 ?>  

2 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

What is my IP address PHP Function? Simple Script

IP address PHP Function
IP address PHP Function

Now you can easily find IP address of user. You just need to put this bellow function to your PHP script. This is cool script to find IP address of user. check it

 function getipaddress()  
      {  
           if (!empty($_SERVER['HTTP_CLIENT_IP'])) {  
             $ip = $_SERVER['HTTP_CLIENT_IP'];  
           } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
             $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
           } else {  
             $ip = $_SERVER['REMOTE_ADDR'];  
           }  
           return $ip;  
      }  
If you are not familiar with function, and want to learn that how to create function. Visit it.
If you are trying to find more simple code for IP Address.  Use this code in your page anywhere.

 <?php  
 $ip=$_SERVER['REMOTE_ADDR'];  
 echo "<b>IP Address = $ip</b>";  
 ?>   
It will make you easy to detect user Internet Protocol Address. And you can locate your IP address easily.
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

Online Database Creation PHP Code with SQL Contribution

Now you don't need to browse PHPMyAdmin for creating database user password by database wizard. You just need to upload this files on your server and create database automatically.

1st file is style sheet file. : stylesheet.css

 @charset "utf-8";  
 /* CSS Document for : http://www.QWC.Me */  
 #dbcreation{padding-left:30%; padding-right:30%; padding-top:10%; padding-bottom:20%;}  
 table{border-top-left-radius:25; border-top-right-radius:25;}  
 th{text-align:center; background-color:#999;}  
 table, th, td, tr, thead, tbody{padding: 10px;}  
 a{text-decoration:none;}  
 .error{color:red;}  
 #dbinstall{border:10; border-color:#999; border-top-left-radius:25; border-top-right-radius:25; border-bottom-left-radius:25; border-bottom-right-radius:25; padding-left:30%; padding-right:30%; padding-top:10%; padding-bottom:20%;}  
 #signupform{text-shadow:#999; padding-left:30%; padding-right:30%; padding-top:10%; padding-bottom:20%;}  

2nd file is Database Values Taken File : create_database.php

 <?php  
      session_start();  
 ?>  
 <!DOCTYPE html >  
 <html xmlns="http://www.w3.org/1999/xhtml" lang="us-en">  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
 <link rel="stylesheet" href="css/stylesheet.css" />  
 <title>Database Creation Process</title>  
 </head>  
 <body>  
   <div id="dbcreation">  
     <table align="center">  
          <thead>  
            <tr><th colspan="2" align="center">Enter Database Detail</th></tr>  
       </thead>  
       <tbody>  
         <form action="install.php" method="post">  
         <tr><td><label id="host">Host: </label></td><td><input type="text" name="host" placeholder="i.e. locahost" required="required" /></td></tr>  
         <tr><td><label id="dbname">Database Name: </label></td><td><input type="text" name="dbname" required="required" /></td>  
         <tr><td><label id="dbuname">User Name: </label></td><td><input type="text" name="dbuname" placeholder="i.e. root" required="required" /></td>  
         <tr><td><label id="dbpass">Password: </label></td><td><input type="text" name="dbpass" required="required" /></td>  
         <tr><td colspan="2" align="center"><input type="submit" name="submit" Value="Create" required="required" /></td></tr>  
         </form>  
       </tbody>  
     </table>  
   </div>   
 </body>  
 </html>  


3rd file is Database installation file : install.php

 <?php  
      session_start();  
 ?>  
 <!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=utf-8" />  
 <link rel="stylesheet" href="css/stylesheet.css" />  
 <title>Database Installation Process</title>  
 </head>  
 <body>  
 <div id="dbinstall">  
   <?php       
                //Get values from create_database.php files  
                if(isset($_POST['submit']))  
                {  
                     echo '<form method="post">  
                     <input type="hidden" name="host" value="'.$_POST['host'].'">  
                     <input type="hidden" name="dbname" value="'.$_POST['dbname'].'">  
                     <input type="hidden" name="dbuname" value="'.$_POST['dbuname'].'">  
                     <input type="hidden" name="dbpass" value="'.$_POST['dbpass'].'">  
                     <input type="submit" name="install" value="Install" align="center">  
                     </form><br/>';   
                     echo 'Welcome to installation process....<br/>  
                     Click install Button to install database.....<br />';  
                }                 
                //if user click on install button then install database on site  
                if(isset($_POST['install']))  
                {            
                     $dbhost = $_POST['host'];  
                     $dbname = $_POST['dbname'];  
                     $dbuname = $_POST['dbuname'];  
                     $dbpass = $_POST['dbpass'];  
                     //connect to mysql server for connecting server : need to give local host and user name  
                     $connect = mysqli_connect($dbhost, 'root');                 
                     //database creation.   
                     $db_create_query = "Create database " . $dbname;  
                     $database = mysqli_query($connect, $db_create_query);  
                     //database creation query error show  
                     if(!isset($database))  
                          {  
                               die("<div class=\"error\">Database creation query error : " . mysqli_connect_error() . "</div>");  
                          }  
                     //database users password query creation  
                     $dbuserpass = "create user " . $dbuname."@".$dbhost. " identified by '".$dbpass."'";  
                     $dbuserpass2 = mysqli_query($connect, $dbuserpass);  
                     //database users password query Error  
                     if(!isset($dbuserpass2))  
                          {  
                               die("<div class=\"error\">Database Username Password query error : " . mysqli_connect_error() . "</div>");  
                          }  
                     //give grant privileges to database user pass  
                     $previleges = "GRANT ALL PRIVILEGES ON $dbname. * TO '$dbuname'@'$dbpass' WITH GRANT OPTION";  
                     $previleges2 = mysqli_query($connect, $previleges);  
                     //check previleges error  
                     if(!isset($previleges2))  
                          {  
                               die("<div class=\"error\">Database Username Password query error : " . mysqli_connect_error() . "</div>");  
                          }                      
                     else  
                          {  
                               echo "Database has been created successfully<br />  
                                         Database Name :" . $dbname. "<br /> Database User Name : ".$dbuname."<br /> Database Password : ".$dbpass;  
                          }  
                }  
                session_destroy();  
      ?>  
 </div>  
 </body>  
 </html>  


I hope you will learn from it. copy code and check it

0 comments

Complete Self Controlled Form : Full Validations and Features with $_POST[] Method

According to new research, many hackers are working together to hack many sites. Now everyone is familiar with PHP, xHTML, CSS working and they can hack your form by
  • Save page as
  • Code checking
  • Firebug tool
  • Ctrl+U
So you need to make your contact form secure to safe your information..
I made this form to make your site more secure.
This form consists on some parts:
  1. Validate Function
  2. Values Validating
  3. Characters Limit Error Message
  4. Left Field Error Message
  5. Auto Selected fields after redirection
  6. CSS
  7. Form Fields
  8. Form Results
  9. Form Error Message
This form is divided into parts, anyone can easily understand it.
In this form : characters limit is
 'name' => 20, 'number' => 16, 'email' => 35,'subject' => 50, 'message' => 350, 'website' => 50

You can change it according to yourself.


  <?php  
           #######################################  
           #   Form Validation Function Start    #  
           #######################################  
      function form_validation($input)  
      {  
           $input = trim($input);  
           $input = htmlspecialchars($input);  
           $input = stripcslashes($input);  
           return $input;  
      }
   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;
   }
   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;
   }
   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;
   }
   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;
   }
   
           ######################################  
           #   Form Validation Function end     #  
           ######################################  
 /*--------------------------------------------------------------------------------*/  
           ####################################################
           #   Getting All Values and Validating them Start   #  
           ####################################################
                $error_msg = ""; //this variable for error massage  
    $departments = array(); //this array for saving department
                $name = $number = $email = $birth = $gender = $subject = $website = $select = $message = $color = ''; // we show all variables empty  
           ###############################################################  
           #   Submit Button Processing with secure validation Start     #  
           ###############################################################                      
                
    if(isset($_POST['submit']))  
                {  
                     $fields = array('name', 'number', 'email', 'birth', 'gender', 'departments', 'select', 'website', 'subject', 'message', 'color'); // all values field array  
      $errors = array(); //this array for saving errors 
                     foreach ($fields as $field) //this is for getting values  
                     {  
                          if(!isset($_POST[$field]) || $_POST[$field] == '' && $field != 'color') //if field value is empty or has nothing  
                          {  
                               array_push($errors, $field); //then selective field array value will be saved in error array.  
                          }  
                          else //if submit button has run, then it else will run  
                          {  
                               if($field != 'departments') //but if value is other than department field  
                               {  
                                    $$field = form_validation($_POST[$field]); //It will go through user define function and value will be made variables  
                               }  
                               elseif($field == 'departments') //but if value is about department then  
                               {  
                                    $departments = array(); //we define an array to save department values  
                                    $test_dept = $_POST[$field]; //we get department here  
                                    foreach($test_dept as $dept ) //we used departments parameter to save that on dept  
                                    {  
                                         array_push($departments, form_validation($dept)); //department will be fully validate and saved to department array  
                                    }  
                               }
                          }
        if($field == 'select' && $_POST[$field] == 'Navigation')
        {
         !array_push($errors, form_validation($field));
        }
                     } //this is foreach loop end  
                ##################################################  
                #   Getting All Values and Validating them end   #  
                ##################################################  
                ###########################################################################  
                # If No Error than Check characters Limit and show exceed Massage Start   #  
                ###########################################################################           
                          //As we have saved error values in errors array  
                     if(empty($errors) || !empty($errors))  
                     {  
                          //we define a assosiative array to define characters limit  
                          $fields = array('name' => 20, 'number' => 16, 'email' => 35,'subject' => 50, 'message' => 350, 'website' => 50);   
                          //For checking lenght we need to add a loop  
                          foreach($fields as $field => $length) //foreach loop is used for arrays : $field => $length we used for assosiative array  
                          ## in this $field => $length : $length variable as assigned to values  
                          {  
                               if (strlen($_POST[$field]) > $length)  
                               {  
                                    array_push($errors, $field . ' field characters limit has exceeded.'); //we shall use $field variable here,   
                                    # Because we are not using $fields, we are using $field as referance.   
                               }
          if($field == 'number' && !validate_number(($_POST[$field]))) //it is to validate number field.
          {
           array_push($errors, $field . " is not proper number."); //if there is an error in number field , error would be push on error array
          }
          if($field == 'name' && !validate_name(($_POST[$field]))) //it is to validate number field.
          {
           array_push($errors, $field . " is not proper name."); //if there is an error in number field , error would be push on error array
          }
          if($field == 'email' && !validate_email(($_POST[$field])) && !empty($_POST[$field])) //it is to validate number field.
          {
           array_push($errors, $field . " is not proper email."); //if there is an error in number field , error would be push on error array
          } 
          if($field == 'website' && !validate_web(($_POST[$field])) && !empty($_POST[$field])) //it is to validate number field.
          {
           array_push($errors, $field . " is not proper website link."); //if there is an error in number field , error would be push on error array
          } 
                          }  
                     } //it is if emtpy end  
                ########################################################################## 
                # If No Error than Check characters Limit and show exceed Massage End    #  
                ##########################################################################      
                ##################################################### 
                # If Error than then show the errors fields start   #  
                ##################################################### 
                     if(!empty($errors))  
                     {  
                          $error_msg = '<b>There are errors in following fields:</b> <br />';  
                          $error_msg .= implode('<br />', $errors);   
                     } //it is if not empty end  
                #########################################################  
                # If Error than then show the errors fields end         #  
                #########################################################  
                } //if isset POST['submit'] end  
           ###############################################################  
           #   Submit Button Processing with secure validation End       #  
           ###############################################################                      
 ?>  
 <!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" lang="us-en">  
 <head>  
 <title><?php $pagetitle="Self Controlled Form : Full Contact Form Feachers : Samee Ullah Feroz";
      define("blogname","www.QWC.me");
     echo $pagetitle ." : ". blogname; ?></title>
               <meta name="description" content="<?php echo $pagetitle ?> : Buy it." />
               <link rel="icon" type="image/ico" href="http://www.iconarchive.com/download/i50954/deleket/3d-cartoon-vol3/Web-Coding.ico" alt="Icon" />

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<style>
/*html
    {
        height:100%;
        width:100%;
        background:url(http://www.southsoft.co.za/images/mysql.jpg) center center no-repeat;
        background-position:center;
 You can also give local file path
    }*/
a:link 
    {
        color:#00F;
        text-decoration:none;
    }

body
    {
  color:#0000FF;
  font-family:"Courier New", Courier, monospace;
  /*background-image:url(http://www.getacho.com/download/phpcss/images/bg-color.png);
  background-repeat:repeat;
  background-attachment:fixed;*/
    }
    
 
#main
 {
  color: #0000FF;
  overflow: auto;
  padding: 10px;
  width: 100%;
 }
 
ul
 {
  
  list-style:square url("images/sqpurple.gif");
 }
#table_bg   
 {  
   border:0;  
   border-color:#000;   
      border-collapse:separate;  
   padding:3;
   padding-right:100px;
 }
.sidemsg  
 {  
      margin-top:60px;
   font-family:"Courier New", Courier, monospace;  
      font-size:16px;  
 }  

</style>               
 </head>  
 <body style="background-color:<?php echo $color?>; ">  
           <div id="main">
           <h1 align="center">Secure Self Controlled Contact Form.</h1> 
           <h2>Qualities</h2>
           <ul>
           <li>Secure from Hackers</li>
           <li>Fast Processing</li>
           <li>Single File Contact Form</li>
           <li>Show Error on characters limit exceeded</li>
           <li>Show Error on Wrong Name</li>
           <li>Show Error on Wrong Email</li>
           <li>Show Error on Wrong Website</li>
           <li>Show Error on Wrong number</li>
           <li>Numbers only digits not doubles</li>
           <li>Cannot select future date of birth</li>
           <li>Can select background custom color</li>
           <li>Can select required Department</li>
           <li>Can select required Agent</li>
           <li>HTML, Javascript etc. Don't work</li>
           <li>After getting errors, form will not reset</li>
           </ul>
           <blockquote>This form is coded to keep away your site from <b>Hackers</b>.</blockquote>
           <h2>Price</h2>
           <hp>You can purchase this form in 5$ just.</hp> 
           <b>Samee is Online On</b><br />
           <b>Company Site : </b><a href="http://www.getacho.com" target="_blank">Getacho Company</a><br />
           <b>Facebook : </b><a href="http://www.facebook.com/sameeullah.feroz" target="_blank">Samee Ullah Feroz</a><br />
           <b>Gtalk :</b> <a href="mailto:seo.getacho@gmail.com" target="_blank">SEO.Getacho</a><br />
           <b>Skype : </b><a href="skype:SEO.Getacho?call">SEO.Getacho</a><br />
           
           </div>
           <div id="table_bg">
               <table style="background-color:<?php echo $color?>; width: 100%;" align="center" >  
               <form action="self_controlled_form.php" method="post" >  
                    <tr><td><label for="name"><strong>Full Name:</strong></label></td>  
                    <td><input type="text" name="name" placeholder="Full Name" style="width:250px;" value="<?php echo $name;?>" /></td></tr>  
                    <tr><td><label for="number"><strong>Personal Number:</strong></label></td>  
                    <td><input type="text" name="number" placeholder="00923234223945" style="width:250px;" value="<?php echo $number;?>"/></td></tr>  
                    <tr><td><label for="email"><strong>Email:</strong></label></td>  
                    <td><input type="text" name="email" placeholder="i.e. mail@example.com" style="width:250px;" value="<?php echo $email;?>"/></td></tr> 
                    <tr><td><label for="website"><strong>Website:</strong></label></td>                   
                    <td><input type="text" name="website" placeholder="i.e. www.example.com" style="width:250px;" value="<?php echo $website;?>"/></td></tr                
                    ><tr><td><label for="gender"><strong>Your Gender:</strong></label></td>  
                    <td><input type="radio" name="gender" value="Male"   
                    <?php if($gender == 'Male' && !empty($gender))echo 'checked';?>/>Male  
                    <input type="radio" name="gender" value="Female"   
                    <?php if($gender == 'Female' && !empty($gender))echo 'checked';?>/>Female</td></tr>
                    <tr><td><label for="birth"><strong>Your DOB:</strong></label></td>                  
                    <td><input type="date" name="birth" value="<?php echo $birth;?>" max="<?php echo date();?>" min="1991-01-01" /></td></tr>  
                    <tr><td><label for="departments[]"><strong>Contact Departments:</strong></label></td>  
                    <td><input type="checkbox" name="departments[]" value="Marketing Department"   
                    <?php if(in_array('Marketing Department', $departments)&& !empty($departments))echo 'checked';?>/>Marketing Department <br /> 
                    <input type="checkbox" name="departments[]" value="Development Department"   
                    <?php if(in_array('Development Department',$departments)&& !empty($departments))echo 'checked';?>/>Development Department <br /> 
                   <input type="checkbox" name="departments[]" value="Finance Department"   
                    <?php if(in_array('Finance Department', $departments) && !empty($departments))echo 'checked';?>/>Finance Department </td></tr>  
             <tr><td><label for="select"><strong>Contact Agent:</strong></label></td>  
                    <td><select name="select">
                        <option value="Navigation">Navigation</option>
                           <option value="Online Agent" <?php if($select == 'Online Agent' && !empty($select))echo 'selected'; ?> >Online Agent</option>  
                           <option value="SEO, SMO Agent" <?php if($select == 'SEO, SMO Agent' && !empty($select))echo 'selected'; ?> >SEO, SMO Agent</option>  
                           <option value="SEM, SMM Agent" <?php if($select == 'SEM, SMM Agent' && !empty($select))echo 'selected'; ?> >SEM, SMM Agent</option>  
                           <option value="Development Agent" <?php if($select == 'Development Agent' && !empty($select))echo 'selected'; ?> >Development Agent</option>  
                           <option value="Consultancy Agent" <?php if($select == 'Consultancy Agent' && !empty($select))echo 'selected'; ?> >Consultancy Agent</option>  
                           <option value="HR Agent" <?php if($select == 'HR Agent' && !empty($select))echo 'selected'; ?> >HR Agent</option>  
                    </select></td></tr>  
                    <tr><td><label for="subject"><strong>Subject:</strong></label></td>  
                    <td><input type="text" name="subject" placeholder="Type Subject" style="width:250px;" value="<?php echo $subject;?>"/></td></tr>  
                    <tr><td valign="top" align="left"><label for="message"><strong>Your Message:</strong></label></td>  
                    <td><textarea cols="40" rows="10" name="message" placeholder="Write your message"><?php echo $message;?></textarea></td></td>  
                    <tr><td valign="top" align="right"><input type="submit" value="Send" name="submit" /></td>  
                    <td>Choose the color :<input type="color" name="color" value="<?php echo $color; ?>" />
                    <br />This Feature Works on Chrome.
                    <br />Developed by <a href="mailto:sam@qwc.me">Samee Ullah Feroz</a><br /> Powered by : <a href="http://www.qwc.me">QWC.Me</a></td></tr>  
               </form>  
               </table>
               </div>
             <div class="sidemsg" style="background-color:<?php echo $color?>; ">  
            <h2>Results Here</h2>
             <?php  
                   echo $name . "<br />";  
                   echo $number . "<br />";  
                   echo $email . "<br />";
       echo $website . "<br />";  
                   echo $gender . "<br />";
                   echo $birth . "<br />";  
                   if (!empty($departments))
                   {
                       echo implode("<br />", $departments) . "<br />";
                   }
                   echo $select . "<br />";  
                   echo $subject . "<br />";            
                   echo $message . "<br />";  
                   echo $error_msg . "<br />";
                   ?>  
             </div>
 </body>  
 </html>

Form is complete with full security and limitations.

Instructions : This code is in-complete if you need this form, contact Samee Ullah Feroz

Demo : 
Ask For Installation
Consultant: 
On Facebook
Gtalk : SEO.Getacho@gmail.com
Skype : SEO.Getacho


0 comments

Secure Form of $_GET[] Method : Form Validation Function

secure form

Now I am going to post a form with full security, Check this
I made this form to get full detail from client that how can we deal with him.
still this contact form is incomplete but I'll complete it in further post.
I made a stylesheet.css file
Here ; I made id for table to use it. As we know, id is used for unique element. 


 @charset "utf-8";  
 /* CSS Document */  
 #table_bg   
 {  
      border:5px;  
      border:solid;  
      background-color:#0F9;  
      border-collapse:separate;  
 }  



Now I made a contact.html file
This form output is same as given image in this post.
I used table to align form perfectly


 <!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>Contact Form</title>  
 <link rel="stylesheet" type="text/css" href="stylesheet.css" />  
 </head>  
      <body>  
           <table cellpadding="3" id="table_bg" align="center">  
           <form action="processing.php" method="get" >  
                <tr><td><label for="name"><strong>Full Name:</strong></label></td>  
                <td><input type="text" name="name" placeholder="Full Name" maxlength="20" style="width:250px;"/></td></tr>  
                <tr><td><label for="number"><strong>Personal Number:</strong></label></td>  
                <td><input type="text" name="number" placeholder="00923234223945" maxlength="16" style="width:250px;"/></td></tr>
                <tr><td><label for="email"><strong>Email:</strong></label></td>  
                <td><input type="text" name="email" placeholder="i.e. example@mail.com" style="width:250px;"/></td></tr>  
                <tr><td><label for="gender"><strong>Your Gender:</strong></label></td>  
                <td><input type="radio" name="gender" value="Male" />Male  
                <input type="radio" name="gender" value="Female"/ >Female</td></tr>  
                <tr><td><label for="department"><strong>Contact Department:</strong></label></td>  
                <td><input type="checkbox" name="department" value="Marketing_Department" />Marketing Department  
                <input type="checkbox" name="department" value="Development_Department" />Development Department</td></tr>  
       <tr><td><label for="select"><strong>Contact Person:</strong></label></td>  
                <td><select name="select" >  
       <option>Online Supporter</option>  
       <option>SEO, SMO Agent</option>  
       <option>SEM, SMM Agent</option>  
       <option>Development Agent</option>  
       <option>Consultancy Agent</option>  
       <option>HR Agent</option>  
       </select></td></tr>  
                <tr><td><label for="subject"><strong>Subject:</strong></label></td>  
                <td><input type="text" name="subject" placeholder="Type Subject" style="width:250px;"/></td></tr>  
                <tr><td valign="top" align="left"><label for="gender"><strong>Your Gender:</strong></label></td>  
                <td><textarea cols="50" rows="20" name="message" placeholder="Write your message"></textarea></td></td>  
                <tr><td>&nbsp;</td>  
                <td><input type="submit" value="Send" /> <input type="reset" value="Clear" /> </td></tr>  
           </form>  
           </table>  
      </body>  
 </html>  



Now I created a file processing.php
I needed to create this file for security. As we know, xHTML language runs on user side and PHP runs on Server side.
with $_GET[] Method, anyone can easily hack your code, that's why PHP is important to add creativity.
Features of Code:
  1. No value will be empty, User needs to enter all values
  2. If user will leave any value empty, form will redirect back to contact.html
  3. If user leaves spaces, form will trim them automatically
  4. HTML, Java code will not run in it.
  5. Back slash will not run in it
  6. User needs to write more than 25 characters in subject, more than 16 in message box, name maximum 20, number maximum 16



 <?php  
      require_once("form_validation.php");  
      #1st Form values should not be empty.   
      if (isset($_GET['name'] , $_GET['number'] , $_GET['email'], $_GET['gender'] , $_GET['department'], $_GET['select'], $_GET['subject'], $_GET['message'])  
      && $_GET['name']!="" && $_GET['number']!="" && $_GET['email']!="" && $_GET['subject']!="" && $_GET['message']!="")  
      {  
           if (strlen($_GET['name']) > 20 || strlen($_GET['number']) > 16 || strlen($_GET['email']) > 25 || strlen($_GET['subject']) < 25 || strlen($_GET['message']) < 160)  
                {  
                     header("Location: contact.html");  
                     exit;  
                }  
                $name = form_validation($_GET['name']);  
                $number = form_validation($_GET['number']);  
                $email = form_validation($_GET['email']);  
                $gender = $_GET['gender'];  
                $department = $_GET['department'];  
                $select = $_GET['select'];  
                $subject = form_validation($_GET['subject']);  
                $message = form_validation($_GET['message']);  
                echo "Name is : $name <br />  
                          Number is : $number <br />  
                               email is : $email <br />  
                                    Gender is : $gender <br />  
                                         Contact Department is : $department <br />  
                                              Subject is : $subject <br />  
                                                   Agent is : $select <br />  
                                                        Message is : $message <br />  
                ";  
           }  
           else  
           {  
                header("Location: contact.html");  
                exit;  
           }  
      ?>  

Now I created a function file with form_validation.php
In this function, it will use trim function to trim white spaces.
It will utilize HTML characters in whole form.
It will leave back slashes.


 <?php  
      function form_validation($input)  
      {  
           $input = trim($input);  
           $input = htmlspecialchars($input);  
           $input = stripcslashes($input);  
           return $input;  
      }  
 ?>  

Good Luck. Form is upgraded in further post.
5 comments

Download Input text bar Script And Try this code

Now you can download input text bar script and can use this code directly to any site easily. Try this code.
when you will give any value to input box, that value will be saved to an array and you can get array detail at header. and can get value from it.
use it.
here $inputs is variable of array.
Note : Download Input Text Bar code and  use it to your site directly.


 <?php  
   $inputs = array();  
   if (isset($_POST['submit'])) { //to check if the form was submitted  
     $value = isset($_POST['input0'])? $_POST['input0'] : null;  
     for($count = 1; $value != null; $count++){  
       array_push($inputs, $value);  
       $value = isset($_POST['input'.$count])? $_POST['input'.$count] : null;  
     }  
   }  
   var_dump($inputs);  
   // to access specific index  
   // to take more then 3 inputs just add one more input field in form  
   //echo $inputs[0];  
   /*  
    *  
    *  
    *code here  
    *  
    *  
    *  
    */  
 ?>  
 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
   <!-- to take multiple inputs copy the below line and change name="input" attribute -->  
   Enter input 1:&nbsp;<input type="text" name="input0" value="" /><br />  
   Enter input 2:&nbsp;<input type="text" name="input1" value="" /><br />  
   Enter input 3:&nbsp;<input type="text" name="input2" value="" /><br />  
   <input type="submit" name="submit" value="Submit" />  
 </form>  
0 comments
 
Copyright © 2011-2026. Samee Articles - All Rights Reserved
Proudly powered by Blogger