Showing posts with label PHP HTML. Show all posts
Showing posts with label PHP HTML. Show all posts

Monday, 5 August 2019

Handling HTML forms with PHP

Today in this post, I would talk about Handling HTML forms with PHP.  A simple example would be registration form. Lets create a html form with php


<html>
<form action=”register.php” method=”post”>
<table border=0>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Username:*</b></br>
<i>It must be 3 or more characters in length <br> and may
only contain letters and number</i></td>
<td><input name=”userid” type=”text” id=”userid” maxlength=”30″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Password:*</b><br>
<i>It must be 6 or more characters in length <br> and may
only contain letters and number</i></td>
<td><input name=”password” type=”password” id=”password” maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Re-type Password:*</b></td>
<td><input name=”password2″ type=”password” id=”password2″ maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Firstname:*</b></td>
<td><input name=”firstname” type=”text” id=”firstname” maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Lastname:*</b></td>
<td><input name=”lastname” type=”text” id=”lastname” maxlength=”15″>
</td>
</tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Your Email Atdress:*</b><br>
<i>A confirmation email will be sent to you <br>
at this address</i>
</td>
<td><input name=”email” type=”text” id=”email” maxlength=”255″>
</td>
</tr>
<tr>
<tr>
<td><font face=”Arial, Helvetica, sans-serif” color=black size=-1>
<b>Your Mobile No:*</b><br>
</td>
<td><input name=”mob” type=”text” id=”mob” maxlength=”10″>
</td>
</tr>
<tr>
<td><input name=”reset” type=”reset” value=”Reset”></td>
<td><input name=”register” type=”submit” value=”register”> </td>
</tr>
</table>
</form>
</html>

We can save this file as myregistration.html and When you will open it you will get below html form.
myregister
When you fill the data and click the submit button, the all the submitted data is sent to register.php through HTML Post method
All variables passed to the current script via the HTTP POST method are stored in associative array $_POST. So you can access data from each field using $_POST[‘NAME’], where NAME is the actual field name. If you submit the form above you would have access to a number of $_POST array values inside the register.php file. The vvariables
$_POST[‘userid’]
$_POST[‘password’]
$_POST[‘password2’]
$_POST[‘firstname’]
$_POST[‘lastname’]
$_POST[’email’]
$_POST[‘mob’]
Now it is the job of register.php to process these variable according to the need and return the information back to user
Let’s for example, we choose register.php like
<?php
echo ‘<html>’;
$userid=$_POST[‘userid’];
$password=$_POST[‘password’];
$password2=$_POST[‘password2’];
$firstname=$_POST[‘firstname’];
$lastname=$_POST[‘lastname’];
$email=$_POST[’email’];
$mob=$_POST[‘mob’];
/* some mysql stuff */
echo ‘You name is $userid’;
echo ‘<br>’;
echo ‘You Firstname is $firstname’;
echo ‘<br>’;
echo ‘You lastname is $lastname’;
echo ‘<br>’;
echo ‘Your registration is completed’;
echo ‘</html>’;
?>


But here we are missing very important piece of information i.e validation. Users may put bad piece and totally corrupt the things. so it is always good to validate the information
There are many ways to perform the validation and it depends on the need,I would tell here some of the basics one
htmlspecialchars()This function convert the html special character in the input to html version. So attacker cannot inject html or java code in the field
stripslashes() : It removes the backflashed in the data
trim()This function returns a string with whitespace stripped from the beginning and end of string
preg_matchThis function matches the string with the strings. This is good function to validate the character in the field
preg_match(“/[^a-zA-Z]/”,$userid) : It check for if $userid is made of letters a-z and A-Z only (no spaces, digits or any other characters)

Keeping all these validation in mind, we can write the register.php as
<?php
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function validate_email($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”,$data))
{
die(“E-mail address not valid”);
}
return $data;
}
echo ‘<html>’;
$userid=validate_input($_POST[‘userid’]);
$password=validate_input($_POST[‘password’]);
$password2=validate_input($_POST[‘password2’]);
$firstname=validate_input($_POST[‘firstname’]);
$lastname=validate_input($_POST[‘lastname’]);
$email=validate_email($_POST[’email’]);
$mob=$_POST[‘mob’];
/* some mysql stuff */
echo ‘You name is $userid’;
echo ‘<br>’;
echo ‘You Firstname is $firstname’;
echo ‘<br>’;
echo ‘You lastname is $lastname’;
echo ‘<br>’;
echo ‘Your registration is completed’;
echo ‘</html>’;
?>


Monday, 8 July 2019

Save HTML Form Data in a (.txt) Text File in PHP

Hello Programmers, in this post I gonna show you a very essential task that can be easily done with Core PHP and HTML form.
Sometimes it happens that we need to store some data in local storage file rather than making it complex using the database. Yes, it’s a fact that in many cases we don’t want to store our text data in database always.
Here I am giving you an example, suppose you have an HTML form and you want to store the data submitted by the user in a text file so that you can easily access it later from that file without opening your database.

PHP Program to store HTML Form data in a .txt File

Below I have provided the PHP code to store the form data in a text file. Just took a glance at this code.
For easy understanding after the code, I have provided the explanation and how to use this code step by step.
  1. <?php
  2. if(isset($_POST['textdata']))
  3. {
  4. $data=$_POST['textdata'];
  5. $fp = fopen('data.txt', 'a');
  6. fwrite($fp, $data);
  7. fclose($fp);
  8. }
  9. ?>
Here ‘textdata’ is the name of our HTML form field that is provided below.
data.txt is a file that we have to create for storing our form submission data in it.


$data is a PHP variable to store the form field data entered by the user.
Now the HTML part`
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Store form data in .txt file</title>
  5. </head>
  6. <body>
  7. <form method="post">
  8. Enter Your Text Here:<br>
  9. <input type="text" name="textdata"><br>
  10. <input type="submit" name="submit">
  11. </form>
  12. </body>
  13. </html>
Now I think you have understood the thing.

remember to add method in your form. <form method=”post”>

Step by step guide on How to put the HTML form field data in a text file or dot txt file in PHP

  1. Create a PHP file and put the below code and save it.
    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <title>Store form data in .txt file</title>
    5. </head>
    6. <body>
    7. <form method="post">
    8. Enter Your Text Here:<br>
    9. <input type="text" name="textdata"><br>
    10. <input type="submit" name="submit">
    11. </form>
    12. </body>
    13. </html>
    14. <?php
    15. if(isset($_POST['textdata']))
    16. {
    17. $data=$_POST['textdata'];
    18. $fp = fopen('data.txt', 'a');
    19. fwrite($fp, $data);
    20. fclose($fp);
    21. }
    22. ?>

  2. create a new file in the same directory or folder & name it data.txt and save it.
  3. Now run the PHP file.
    enter any text and hit on submit button and check your data.txt file. Your text entered in the form is saved in your text file.

look at the below code. It will also work fine
<?php
             
$data = $_POST['textdata'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
this will work fine. But in some servers it might show an error like this
“Undefined index: ”
in order to prevent the error warning we use isset()
so it’s safe to use this before $_POST[‘value’];
something like this one
if(isset($_POST['value'])) { 

       //////your code

 }

Thursday, 20 September 2018

Allowed memory size exhausted with the PHP Simple HTML DOM Parser

The Simple HTML DOM Parser is a useful tool for extracting content from web pages using jQuery like syntax. If multiple pages are loaded into the parser the available memory will eventually be exhausted and a fatal error will occur.

Some example code

The example code below has an already defined array $urls which contains a list of URLs to download content and parse.
require_once('/path/to/simple_html_dom.php');
foreach($urls as $url) {
    $dom = file_get_html($url);
    // do some stuff here
}
Depending on the number of pages downloaded, their size and size of the associated DOM, and how much memory is available to PHP, the available memory may be exhausted and result in a fatal error, halting your script at that point.

The error message 

The error message when memory is exhausted will be similar to this:
PHP Fatal error: Allowed memory size of XYZ bytes exhausted (tried to allocate XYZ bytes) in [path]/simple_html_dom.php on line XYZ

The solution

The Simple HTML DOM Parser does not clean up memory in the DOM each time file_get_html or str_get_html is called so it needs to be done explicity each time you have finished with the current DOM. This is as simple as adding ->clear() at the end of a loop or when you've finished using it.
The revised example with clear() is as follows:
require_once('/path/to/simple_html_dom.php');
foreach($urls as $url) {
    $dom = file_get_html($url);
    // do some stuff here
    $dom->clear();
}
Assuming there is enough memory available to PHP to handle each individual page and associated DOM, the process will now no longer suffer from memory exhaustion.

Download PHP Simple HTML DOM Parser / Examples

The PHP Simple HTML DOM Parser can be downloaded from SourceForge where there are also several examples of extracting content from pages.

Related posts:

Get meta tags from an HTML file with PHP

While researching some functions for a PHP article I'm writing I came across the get_meta_tags() function and decided to write a quick post about it.

get_meta_tags() function

The way this function works is to take the filename passed as the first parameter (which can be a URL if allow_url_fopen is on in the PHP confuguration) and then find all the <meta> tags until the closing </head> tag. Any that are in the following form will be returned in an array:
<meta name="KEY" content="VALUE">
The meta name (KEY in the above example) will be the array's key and the content (VALUE in the above example) will be the value.
So if the start of the HTML at http://www.example.com/ contained the following:
<html>
<head>
<title>Welcome to example.com</title>
<meta name="keywords" content="the keywords meta tag is redundant but people still include it">
<meta name="description" content="here's the meta description for my fictional example.com homepage">
</head>
Then doing this:
$tags = get_meta_tags('http://www.healthy.co.nz/');
print_r($tags);
will output this:
Array
(
    [keywords] => the keywords meta tag is redundant but people still include it
    [description] => here's the meta description for my fictional example.com homepage
)
As far as I can tell from testing this myself, any meta tag in the form <meta name="KEY" content="VALUE"> will be included in the array returned.

Related posts: