Monday, 14 August 2017

Upload file using PHP

Upload file using PHP

Upload file using PHP


This is a simple tutorial to learn how to upload file using PHP with the help of HTML form. PHP makes it very easy, which is required in most of websites.
Upload file by user can be harmful to your website, because hackers can effect the data always upload file with some security and precautions like file size, file type, etc.

Steps to upload file using PHP

First we need a HTML form to upload file.
  1. <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" enctype="multipart/form-data">
  2. <p><input type="file" name="myfile"></p>
  3. <p><input type="submit" name="submit" value="Upload files"></p>
  4. </form>

Important

We must have a attribute enctype = “multiplat/form-data” in form tag. This attribute mention how data should be encoded before uploading to the server.
type =”file” will create an array by using PHP Global function $_FILE[] from which is going to upload and all information in separate elements like file name, file size, temporary location.

PHP Script

When user click submit button to upload file then php script comes in action.
  1. if(isset($_POST["submit"])){
  2. }
Getting file name
  1. $file_name = $_FILES['myfile']['name'];
Getting temporary location of file from file array. Wen user upload files php hold the file in temporary location on server during the upload process.
  1. $file_tmp = $_FILES['myfile']['tmp_name'];
Now we will get the file size from file array. It will help in providing restriction  file size.
  1. $file_size = $_FILES['myfile']['size'];
Getting file extension from the file using explode function. This function convert the  string to array with specified separator.
  1. $get_extension = explode('.',$file_name);
Now get proper extension of file using end function and also convert the extension in lower.
  1. $get_extension = strtolower(end($get_extension));
here I am using uniqid() function to prevent the upload file with same name.
  1. $new_file = uniqid().'.'.$get_extension;
Set the location where you want to upload the file. Here I am using uploads directory to upload file.
  1. $file_store = "uploads/".$new_file;
Now make the required validation before upload file on destination folder, like file size, file type with if condition
Here I am allowing only jpg, png and gif image with less than or equal to 200kb.
  1. if ($get_extension=='jpg' || $get_extension=='png' || $get_extension=='gif') {
  2. if($file_size>=200000){
  3. echo "<script>alert('Max. file size should be 200 KB.')</script>";
  4. }
  5. else{
  6. if(move_uploaded_file($file_tmp, $file_store)){
  7. echo "<script>alert('$file_name is uploaded successfully with uniq ID')</script>";
  8. };
  9. }
  10. }
  11. else{
  12. echo "<script>alert('Please select only jpg, png or gif image only.')</script>";
  13. }
  14. }
Finally  as if no errors occurred the move_upload function will upload file to destination folder from temporary location with unique name.

Complete Code for Upload file using PHP

  1. <?php
  2. if(isset($_POST["submit"])){
  3. $file_name = $_FILES['myfile']['name'];
  4. $file_tmp = $_FILES['myfile']['tmp_name'];
  5. $file_size = $_FILES['myfile']['size'];
  6. $get_extension = explode('.',$file_name);
  7. $get_extension = strtolower(end($get_extension));
  8. $new_file = uniqid().'.'.$get_extension;
  9. $file_store = "uploads/".$new_file;
  10. //move_upload_file() function is use to store the file to destination folder from the temperary folder. It have two parameter 1. for temperary file 2. destination folder.
  11. if ($get_extension=='jpg' || $get_extension=='png' || $get_extension=='gif') {
  12. if($file_size>=200000){
  13. echo "<script>alert('Max. file size should be 200 KB.')</script>";
  14. }
  15. else{
  16. if(move_uploaded_file($file_tmp, $file_store)){
  17. echo "<script>alert('$file_name is uploaded successfully with uniq ID')</script>";
  18. }
  19. }
  20. }
  21. else{
  22. echo "<script>alert('Please select only jpg, png or gif image only.')</script>";
  23. }
  24. }
  25. ?>

Sunday, 13 August 2017

HTML Form validation using PHP

HTML Form validation using PHP

HTML Form validation using PHP

In this tutorial we will make form validation using PHP. We will check and validate to most common element of a HTML form.

See Demo 

Why we need to validation?

HTML form is used to collecting information from user for further communicate or recognizing as well as providing the necessary information to the particular user.

Form Validation Process

Form validation using PHP applies useful security and approach to user for filling the relevant information as per required.

The Process

First we need HTML form with submit button and some input field to collecting data like text, email, text area, radio buttons, checkbox.
For tutorial point of view I am using all most of the form field to make better understand of validation process in PHP.

HTML Form

  1. <form id="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST">

  2. </form>
Here Im using Id selector for targeting css for the this particular form and its elements and two form attributes :
1. action and 2. method.
The action : $_SERVER[‘PHP_SELF’] perform the validation on current page, for security I will wrap this request into php inbuilt function htmlspecialchars(). htmlspecialchars() function convert the special character like (“”, <>) into HTML entities as &quot;, &gt;, &lt. So hackers can not insert any script or query in our HTML form.
The method : Here I am using post method to sending data to server. The post method is more secure than get method. In get method the request add to the url which is visible to everyone and request remains in browser history which can be cached. This can be harmful for our data.

HTML Structure

  1. <html>
  2. <head>
  3. <title>HTML form validation using PHP</title>

  4. </head>
  5. <body>
  6. <div class="container">

  7. <form id="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST">
  8. <h3>Form Validation</h3>
  9. <h4>Complete form validation using PHP</h4>
  10. <fieldset>
  11. <input placeholder="Your name" type="text" tabindex="1" name="name">
  12. <span><?php echo $nameErr ;?></span>
  13. </fieldset>
  14. <fieldset>
  15. <input placeholder="Your Email Address" type="email" name="email">
  16. <span><?php echo $emailErr ;?></span>
  17. </fieldset>
  18. <fieldset>
  19. <input placeholder="Your Phone Number" type="text" name="phone">
  20. <span><?php echo $phoneErr ;?></span>
  21. </fieldset>
  22. <fieldset>
  23. <input placeholder="Your Pin Code" type="text" name="pin">
  24. <span><?php echo $pinErr ;?></span>
  25. </fieldset>
  26. <fieldset>
  27. <input placeholder="Your Url" type="text" name="url">
  28. <span><?php echo $urlErr ;?></span>
  29. </fieldset>
  30. <fieldset>
  31. Gender
  32. <input type="radio" name="gender[]" value="Male">Male
  33. <input type="radio" name="gender[]" value="Female">Female
  34. <br><span><?php echo $genderErr ;?></span>
  35. </fieldset>

  36. <fieldset>
  37. Hobbies
  38. <input type="checkbox" name="vehicle[]" value="Bike">I have a bike
  39. <input type="checkbox" name="vehicle[]" value="Car">I have a car
  40. <input type="checkbox" name="vehicle[]" value="Cycle">I have a Bycycle
  41. <br><span><?php echo $vehicleErr ;?></span>
  42. </fieldset>
  43. <fieldset>
  44. <textarea placeholder="Type your Message Here...." name="text"></textarea>
  45. <br><span><?php echo $textErr ;?></span>
  46. </fieldset>
  47. <fieldset>
  48. <button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
  49. </fieldset>
  50. <div style="text-align: center;">
  51. <?php
  52. $date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
  53. echo '&copy;'.' Copyright - '. $date->format('d-m-Y');
  54. ?>
  55. </div>
  56. </form>
  57. </div>
  58. </body>
  59. </html>

Styling with CSS

  1. <style>
  2. @import url(https://fonts.googleapis.com/css?family=Open+Sans:400italic,400,300,600);

  3. * {
  4. margin:0;
  5. padding:0;
  6. box-sizing:border-box;
  7. -webkit-box-sizing:border-box;
  8. -moz-box-sizing:border-box;
  9. -webkit-font-smoothing:antialiased;
  10. -moz-font-smoothing:antialiased;
  11. -o-font-smoothing:antialiased;
  12. font-smoothing:antialiased;
  13. text-rendering:optimizeLegibility;
  14. }

  15. body {
  16. font-family:"Open Sans", Helvetica, Arial, sans-serif;
  17. font-weight:300;
  18. font-size: 12px;
  19. line-height:30px;
  20. color:#777;
  21. background:#0CF;
  22. }

  23. .container {
  24. max-width:400px;
  25. width:100%;
  26. margin:0 auto;
  27. position:relative;

  28. }

  29. #contact input[type="text"], #contact input[type="email"], #contact input[type="url"], #contact textarea, #contact button[type="submit"] { font:400 12px/16px "Open Sans", Helvetica, Arial, sans-serif; }

  30. input[type="checkbox"]{
  31. display:inline-block;
  32. margin-right:2px;
  33. }
  34. #contact {
  35. background:#F9F9F9;
  36. padding:25px;
  37. margin:20px 0;
  38. border-radius: 0 30px 0 30px;
  39. }


  40. #contact h3 {
  41. color: #F96;
  42. font-size: 40px;
  43. font-weight: 300;
  44. }

  45. #contact h4 {
  46. margin:5px 0 15px;
  47. font-size:13px;
  48. }

  49. fieldset {
  50. border: medium none !important;
  51. margin: 0 0 10px;
  52. min-width: 100%;
  53. padding: 0;
  54. width: 100%;
  55. }

  56. #contact input:not([type="radio"]), textarea {
  57. width:100%;
  58. border:1px solid #CCC;
  59. background:#FFF;
  60. margin:0 0 5px;
  61. padding:10px;
  62. }
  63. #contact input[type="checkbox"], input[type="radio"]{
  64. width:auto;
  65. border:1px solid #CCC;
  66. background:#FFF;
  67. margin:0 0 5px;
  68. padding:10px;
  69. }

  70. #contact input:hover, #contact input[type="email"]:hover, #contact input[type="url"]:hover, #contact textarea:hover {
  71. -webkit-transition:border-color 0.3s ease-in-out;
  72. -moz-transition:border-color 0.3s ease-in-out;
  73. transition:border-color 0.3s ease-in-out;
  74. border:1px solid #AAA;
  75. }

  76. #contact textarea {
  77. height:100px;
  78. max-width:100%;
  79. resize:none;
  80. }

  81. #contact button[type="submit"] {
  82. cursor:pointer;
  83. width:100%;
  84. border:none;
  85. background:#0CF;
  86. color:#FFF;
  87. margin:0 0 5px;
  88. padding:10px;
  89. font-size:15px;
  90. }

  91. #contact button[type="submit"]:hover {
  92. background:#09C;
  93. -webkit-transition:background 0.3s ease-in-out;
  94. -moz-transition:background 0.3s ease-in-out;
  95. transition:background-color 0.3s ease-in-out;
  96. }

  97. #contact button[type="submit"]:active { box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); }

  98. #contact input:focus, #contact textarea:focus {
  99. outline:0;
  100. border:1px solid #999;
  101. }
  102. ::-webkit-input-placeholder {
  103. color:#888;
  104. }
  105. :-moz-placeholder {
  106. color:#888;
  107. }
  108. ::-moz-placeholder {
  109. color:#888;
  110. }
  111. :-ms-input-placeholder {
  112. color:#888;
  113. }
  114. span{
  115. color:#f00;
  116. }
  117. </style>

Form Validation using PHP

Setting up variable for collecting fields value.
  1. // setting up variables for inputs;
  2. $name = $email = $phone = $pin = $url = $gender = $vehicle = $text = "";
Setting up variable for collecting if any errors in particular field.
  1. // setting up variables for showing erros
  2. $nameErr = $emailErr = $phoneErr = $pinErr = $urlErr = $genderErr = $vehicleErr = $textErr = "";
Now we create a function to check input fields.
  1. function test($data)
  2. {
  3. $data = trim($data); // removes the extra spaces, tabs and lines from the input field
  4. $data = stripslashes($data); // removes the backslaces (\) from the input field
  5. $data = htmlspecialchars($data); // converts the special characters into HTML entities
  6. return $data;
  7. }
Now we can perform our verification on submitting the submit button.
  1. // submit button
  2. if(isset($_POST['submit']))
  3. {
  4. // validation for name field
  5. if(empty($_POST['name']))
  6. {
  7. $nameErr = "Name is Required";
  8. // $errors ++;
  9. }else
  10. {
  11. $name = test($_POST['name']);
  12. //check if name only contains letters and whitespace
  13. if(!preg_match("/^[a-z A-Z ]*$/", $name))
  14. {
  15. $nameErr = "Only letters allowed with White Space in between";
  16. }
  17. }
  18. // validation for email field
  19. if(empty($_POST['email']))
  20. {
  21. $emailErr = "Email is Required";
  22. // $errors ++;
  23. }else
  24. {
  25. $email = test($_POST["email"]);
  26. // check if e-mail address is well-formed
  27. if (!filter_var($email, FILTER_VALIDATE_EMAIL))
  28. {
  29. $emailErr = "Invalid email format";
  30. }
  31. }
  32. // validation for phone field
  33. if(empty($_POST['phone']))
  34. {
  35. $phoneErr = "Phone is Required";
  36. // $errors ++;
  37. }else
  38. {
  39. $phone = test($_POST['phone']);
  40. //check if phone only contains numbers
  41. if(!preg_match("/^[0-9]*$/", $phone))
  42. {
  43. $phoneErr = "Only numbers allowed";
  44. }
  45. else
  46. {
  47. if(strlen($phone)<10)
  48. {
  49. $phoneErr = "Invalid Phone";
  50. }
  51. }
  52. }
  53. // validation for pin field
  54. if(empty($_POST['pin']))
  55. {
  56. $pinErr = "Pin is Required";
  57. // $errors ++;
  58. }else
  59. {
  60. $pin = test($_POST['pin']);
  61. //check if phone only contains numbers
  62. if(!preg_match("/^[0-9]*$/", $pin))
  63. {
  64. $pinErr = "Only numbers allowed";
  65. }
  66. else
  67. {
  68. if(strlen($pin)!==6)
  69. {
  70. $pinErr = "Invalid Pin";
  71. }
  72. }
  73. }
  74. // url verification
  75. if (empty($_POST["url"]))
  76. {
  77. $urlErr = "URL is Required";
  78. // $errors ++;
  79. }
  80. else
  81. {
  82. $url = test($_POST["url"]);
  83. // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
  84. if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$url))
  85. {
  86. $urlErr = "Invalid URL";
  87. }
  88. }
  89. // radio button verification
  90. if (isset($_POST['gender']))
  91. {
  92. if (!empty($_POST['gender']))
  93. {
  94. foreach ($_POST['gender'] as $selectedGender)
  95. {
  96. $gender = $selectedGender;
  97. }
  98. }
  99. }
  100. else
  101. {
  102. $genderErr = "please select Gender";
  103. // $errors ++;
  104. }
  105. // select button verification
  106. if (isset($_POST['vehicle']))
  107. {
  108. if (!empty($_POST['vehicle']))
  109. {
  110. foreach ($_POST['vehicle'] as $selectedVehicle)
  111. {
  112. $vehicle = $selectedVehicle;
  113. }
  114. }
  115. }
  116. else
  117. {
  118. $vehicleErr = "please select Vehicle";
  119. // $errors ++;
  120. }
  121. // validation for text Area
  122. if(empty($_POST['text']))
  123. {
  124. $textErr = "Please submit your comments";
  125. // $errors ++;
  126. }else
  127. {
  128. $text = test($_POST['text']);
  129. }
  130. } // end of submit button
If do not any  errors by submitting form then we can mail or insert data in our database.
I hope it will help you in your projects form validation.

Upload file using PHP

Upload file using PHP This is a simple tutorial to learn how to upload file using PHP with the help of HTML form. PHP makes it very...