programming

PHP – Email Injection protection

PHP – Email Injection protection

A malicious spammer could use Email Injection to send large numbers of messages anonymously.

When a form is added to a Web page that submits data to a Web application, a malicious user may exploit the MIME format to append additional information to the message being sent, such as a new list of recipients or a completely different message body.

Because the MIME format uses a carriage return to delimit the information in a message, and only the raw message determines its eventual destination, adding carriage returns to submitted form data can allow a simple guestbook to be used to send thousands of messages at once.

The best way to stop e-mail injections is to validate the input.

HTML form:


<html>
<body>
<?php
function spamcheck($field)
  {
  // Sanitize e-mail address
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  // Validate e-mail address
  if(filter_var($field, FILTER_VALIDATE_EMAIL))
    {
    return TRUE;
    }
  else
    {
    return FALSE;
    }
  }
?>

<h2>Feedback Form</h2>
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
  {
  ?>
  <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Submit Feedback">
  </form>
  <?php 
  }
else
  // the user has submitted the form
  {
  // Check if the "from" input field is filled out
  if (isset($_POST["from"]))
    {
    // Check if "from" email address is valid
    $mailcheck = spamcheck($_POST["from"]);
    if ($mailcheck==FALSE)
      {
      echo "Invalid input";
      }
    else
      {
      $from = $_POST["from"]; // sender
      $subject = $_POST["subject"];
      $message = $_POST["message"];
      // message lines should not exceed 70 characters (PHP rule), so wrap it
      $message = wordwrap($message, 70);
      // send mail
      mail("webmaster@example.com",$subject,$message,"From: $from\n");
      echo "Thank you for sending us feedback";
      }
    }
  }
?>
</body>
</html>

How does it work?

1. Get the input data from the HTML form:

 <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  From: <input type="text" name="from"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea rows="10" cols="40" name="message"></textarea><br>
  <input type="submit" name="submit" value="Submit Feedback">
 </form>

2. The php script send form data to itself:

<?php echo $_SERVER["PHP_SELF"];?>

3. Check if the “from” input field is filled out

if (isset($_POST["from"]))

4.Send the “from” value to the function spamcheck()

$mailcheck = spamcheck($_POST["from"]);

5. spamcheck() function:
a. The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters from a string
b. The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address
c. It wll return TRUE if it is all ok!

function spamcheck($field)
  {
  // Sanitize e-mail address
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  // Validate e-mail address
  if(filter_var($field, FILTER_VALIDATE_EMAIL))
    {
    return TRUE;
    }
  else
    {
    return FALSE;
    }
  }

6. If it is FALSE It will print the message “Invalid input”

$mailcheck = spamcheck($_POST["from"]);
    if ($mailcheck==FALSE)
      {
      echo "Invalid input";
      }

7. If it is TRUE It will send the message and will print “Thank you for sending us feedback”

else
      {
      $from = $_POST["from"]; // sender
      $subject = $_POST["subject"];
      $message = $_POST["message"];
      // message lines should not exceed 70 characters (PHP rule), so wrap it
      $message = wordwrap($message, 70);
      // send mail
      mail("myemail@lucedigitale.com",$subject,$message,"From: $from\n");
      echo "Email sent successfully";
      }
By |Web Design, WordPress|Commenti disabilitati su PHP – Email Injection protection

Disabling WordPress Automatic Updates

Disabling WordPress Automatic Updates

Wordpress 3.7 or over has an automatic updates function.

There are users who run WordPress for clients and have their own ways to update WordPress when a new version is available. Lastly, there are users who just want to do their updates manually and have more control over it.

Open wp-config.php file and add:

define( 'WP_AUTO_UPDATE_CORE', false );

This will disable the WordPress automatic updater, and you will still get notified when there is a new version available, so you can update at your own convenience.

By |Web Design, WordPress|Commenti disabilitati su Disabling WordPress Automatic Updates

PHP – MySQL – Simple Calendar

PHP – MySQL – Simple Calendar

DOWNLOAD

 

We want a calendar like this:

—–

Title of the event

Start date – End date

Content bla bla bla … Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.

Link>

—–

Create database

Entriamo in phpMyAdmin

In alto posizioniamoci su localhost> mydatabase

Usando phpMyAdmin creiamo:

Colonna di sinistra> ‘Crea tabella’> MyISAM

Nome tabella: calendar’

Struttura> aggiungere i campi

Campo: id
Tipo: INT
Lunghezza: 20
Predefinito: Nessuno
Null: deselezionato
Indice: PRIMARY
AUTO_INCREMENT: selezionato

Campo: title
Tipo: VARCHAR
Lunghezza: 255
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: link
Tipo: VARCHAR
Lunghezza: 255
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: content
Tipo: LONGTEXT -> it must contain max 4,294,967,295 characters
Lunghezza: -> non specifichiamo nulla
Predefinito: Nessuno
Null: deselezionato
Indice: nessuno
AUTO_INCREMENT: deselezionato

Campo: startDate
Tipo: DATETIME -> Format: YYYY-MM-DD HH:MM:SS Example: 2014-12-31 23:59:59

Campo: endDate
Tipo: DATETIME -> Format: YYYY-MM-DD HH:MM:SS Example: 2014-12-31 23:59:59

PhpMyAdmin
php-mysql-008

calendar_input_form.php

The input form

<!-- CONNESSIONE DB START -->
<?php
// Create DATABASE connection - START
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");
// Check connection
if (mysqli_connect_errno())
  {
  echo "<br> Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!<br><br>";
  }
  // Create DATABASE connection - END
  ?>
<!-- CONNESSIONE DB END -->

<html>
<body>
 
<!-- FORM INSERT START -->
<!-- Send data to calendar_insert_engine.php -->
<form action="calendar_insert_engine.php?action=addEvent" method="post">
    Title: <input type="text" name="title"><br/>
    Link: <input type="text" name="link"><br/>
    Start date (YYYY-MM-DD HH:MM): <input type="text" name="startDate"><br/>
    End date (YYYY-MM-DD HH:MM): <input type="text" name="endDate"><br/>
    Content: <br/>
    <textarea rows="15" cols="30" name="content"></textarea><br/>
    <input type="submit" value="Insert Event">
</form>
<!-- FORM INSERT END -->
 
</body>
</html>

<!-- QUERY DB START -->
<?php
// SELECT asterisco (tutti i dati) dalla tabella START
// inserisco i dati nella variabile $result
// ordinati in base a startDate in ordine decrescente
$result = mysqli_query($con,"SELECT * FROM calendar ORDER BY startDate DESC");
 
echo "<strong>Calendar - Event List: (Order by startDate DESC)</strong>";
echo "<br><br>ID - Title - Link - Start date - End date - Content<br>";
// Restituisce il set di record come un array
// ad ogni chiamata viene restituita la riga successiva
while($row = mysqli_fetch_array($result))
  {
  // Visualizza a video i dati
  echo $row['id'] . " - " .$row['title'] . " - " . $row['link'] . " - " . $row['startDate'] . " - " . $row['endDate'] . " - " . $row['content'];
  echo "<br>";
  }
// SELECT asterisco (tutti i dati) dalla tabella END
 
mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
?>
<!-- QUERY DB END -->

calendar_insert_engine.php

The PHP engine to store data

<?php
 
$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="calendar"; //Indicate la tabella presente nel database a cui si deve collegare 
 
// Connetti al server e seleziona il database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("DB non connesso");
 
// Ottengo i dati dal form HTML
// Se dal form arriva - action=addEvent - esegui il seguente
if($_GET['action'] == 'addEvent'){
    $title = mysql_real_escape_string($_POST['title']);
    $link = mysql_real_escape_string($_POST['link']);
    $content = mysql_real_escape_string($_POST['content']);
    $startDate = date('Y-m-d H:i:s', strtotime($_POST['startDate'] . ":00"));
    $endDate = date('Y-m-d H:i:s', strtotime($_POST['endDate'] . ":00"));

    // Invio una query per inserire i dati
    mysql_query("INSERT INTO calendar VALUES (null, '$title', '$link', '$content', '$startDate', '$endDate');");
	echo "Great! New Record Inserted!";
}

?>

IMPROVE INPUT FORM WITH date tag

<!-- CONNESSIONE DB START -->
<?php
// Create DATABASE connection - START
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");
// Check connection
if (mysqli_connect_errno())
  {
  echo "<br> Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!<br><br>";
  }
  // Create DATABASE connection - END
  ?>
<!-- CONNESSIONE DB END -->

<html>
<body>
 
<!-- FORM INSERT START -->
<!-- Send data to calendar_insert_engine.php -->
<form action="calendar_insert_engine.php?action=addEvent" method="post">
    Title: <input type="text" name="title"><br/>
    Link: <input type="text" name="link"><br/>
    Start date (this send -> 2018-02-05): <input type="date" name="startDate"><br/>
    End date (this send -> 2018-02-05): <input type="date" name="endDate"><br/>
    Content: <br/>
    <textarea rows="15" cols="30" name="content"></textarea><br/>
    <input type="submit" value="Insert Event">
</form>
<!-- FORM INSERT END -->
 
</body>
</html>

<!-- QUERY DB START -->
<?php
// SELECT asterisco (tutti i dati) dalla tabella START
// inserisco i dati nella variabile $result
// ordinati in base a startDate in ordine decrescente
$result = mysqli_query($con,"SELECT * FROM calendar ORDER BY startDate DESC");
 
echo "<strong>Calendar - Event List: (Order by startDate DESC)</strong>";
echo "<br><br>ID - Title - Link - Start date - End date - Content<br>";
// Restituisce il set di record come un array
// ad ogni chiamata viene restituita la riga successiva
while($row = mysqli_fetch_array($result))
  {
  // Visualizza a video i dati
  echo $row['id'] . " - " .$row['title'] . " - " . $row['link'] . " - " . $row['startDate'] . " - " . $row['endDate'] . " - " . $row['content'];
  echo "<br>";
  }
// SELECT asterisco (tutti i dati) dalla tabella END
 
mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
?>
<!-- QUERY DB END -->
<?php
 
$host="localhost"; //lasciare com'è se utilizzate bluehost
$username="lucedigi_user"; 
$password="mypassword"; 
$db_name="lucedigi_testphp"; // database name
$tbl_name="calendar"; //Indicate la tabella presente nel database a cui si deve collegare 
 
// Connetti al server e seleziona il database
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("DB non connesso");
 
// Ottengo i dati dal form HTML
// Se dal form arriva - action=addEvent - esegui il seguente
if($_GET['action'] == 'addEvent'){
    $title = mysql_real_escape_string($_POST['title']);
    $link = mysql_real_escape_string($_POST['link']);
    $content = mysql_real_escape_string($_POST['content']);
    $startDate = date('Y-m-d H:i:s', strtotime($_POST['startDate'] . " 00:00:00"));
    $endDate = date('Y-m-d H:i:s', strtotime($_POST['endDate'] . " 00:00:00"));

    // Invio una query per inserire i dati
    mysql_query("INSERT INTO calendar VALUES (null, '$title', '$link', '$content', '$startDate', '$endDate');");
	echo "Great! New Record Inserted!";
}

?>

Notice:
the HTML form send data as 2018-02-05
the PHP script add ” 00:00:00″ -> strtotime($_POST[‘startDate’] . ” 00:00:00″
because MySQL DATETIME needs the format: YYYY-MM-DD HH:MM:SS Example: 2014-12-31 23:59:59

By |PHP, Web Design|Commenti disabilitati su PHP – MySQL – Simple Calendar

PHP – MySQL – Simple Data Management Skeleton

PHP – MySQL – Simple Data Management Skeleton

DOWNLOAD

 

insert-form.php

<?php
// Create DATABASE connection - START
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");
// Check connection
if (mysqli_connect_errno())
  {
  echo "<br> Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
  // Create DATABASE connection - END
  ?>
  
<html>
<body>

<!-- FORM INSERT START -->
<!-- Send data to insert-engine.php -->
<br><br><strong>Insert New Data:</strong>
<form action="insert-engine.php" method="post">
<br>First name: <input type="text" name="firstname">
<br>Last name: <input type="text" name="lastname">
<br>Age: <input type="text" name="age">
<br><input type="submit">
</form>
<!-- FORM INSERT END -->

<!-- FORM DELETE START -->
<!-- Send data to delete-engine.php -->
<br><strong>Delete Data:</strong>
<form action="delete-engine.php" method="post">
<br>PID: <input type="text" name="deletepid">
<br><input type="submit">
</form>
<!-- FORM DELETE END -->

<!-- FORM UPDATE START -->
<!-- Send data to update-engine.php -->
<br><strong>Update Data:</strong>
<form action="update-engine.php" method="post">
<br>PID: <input type="text" name="updatepid">
<br>First name: <input type="text" name="upfirstname">
<br>Last name: <input type="text" name="uplastname">
<br>Age: <input type="text" name="upage">
<br><input type="submit">
</form>
<!-- FORM UPDATE END -->

</body>
</html>

<?php
// SELECT asterisco (tutti i dati) dalla tabella Persons - START
// inserisco i dati nella variabile $result
$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<strong>Data Inside Database:</strong>";
echo "<br><br>PID - First name - Last name - Age<br>";
// Restituisce il set di record come un array
// ad ogni chiamata viene restituita la riga successiva
while($row = mysqli_fetch_array($result))
  {
  // Visualizza a video i dati
  echo $row['PID'] . " - " .$row['FirstName'] . " - " . $row['LastName'] . " - " . $row['Age'];
  echo "<br>";
  }
// SELECT asterisco (tutti i dati) dalla tabella Persons - END

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
?>

update-engine.php

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
  
// Update records START
// SET column1=value, column2=value2,...
mysqli_query($con,"UPDATE Persons SET Age='$_POST[upage]', FirstName='$_POST[upfirstname]', LastName='$_POST[uplastname]' WHERE PID='$_POST[updatepid]'");

// Update records END
echo "<br>1 record updated";

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
echo "<br><a href='insert-form.php'>Torna alla pagina precedente</a>";
?>

insert-engine.php

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
 
// ###################################################### 
// Aggiungere nuovi record alle colonne con POST - START
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
// Aggiungere nuovi record alle colonne con POST - END
// ###################################################### 

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "<br>1 record added";

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
echo "<br><a href='insert-form.php'>Torna alla pagina precedente</a>";
?>

delete-engine.php

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
else
  {
  echo "Great! Connect to MySQL!";
  }
  
// Delete records START
mysqli_query($con,"DELETE FROM Persons WHERE PID='$_POST[deletepid]'");
// Delete records END
echo "<br>1 record deleted";

mysqli_close($con); 
echo "<br>Great! Connection Closed!"; 
echo "<br><a href='insert-form.php'>Torna alla pagina precedente</a>";
?>
By |MySQL, PHP|Commenti disabilitati su PHP – MySQL – Simple Data Management Skeleton

PHP – MySQL – Order By Keyword

PHP – MySQL – Order By Keyword

Statement:

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

<?php
// Create connection
// Statement: mysqli_connect(host,username,password,dbname)
// NOTICE: se lo script è installato nello stesso server del Data Base, host->localhost
$con=mysqli_connect("localhost","lucedigi_user","mypassword","lucedigi_testphp");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

// Order records START
$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
  {
  echo $row['FirstName'];
  echo " " . $row['LastName'];
  echo " " . $row['Age'];
  echo "<br>";
  }
// Order records END

mysqli_close($con); 
echo "Great! Connection Closed!"; 
?>

phpMyAdmin:

mysql-0004

The result:

Glenn Quagmire 33
Peter Griffin 35
Andrea Tonin 39

By |MySQL, PHP|Commenti disabilitati su PHP – MySQL – Order By Keyword