Web Development

From Sinfronteras
Revision as of 21:28, 14 February 2020 by Adelo Vieira (talk | contribs) (Installing PHP)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Path de los códigos:

Variable definida con:
{{#vardefine:codespath|http://localhost/webdevelopment/}}

Para usar la variable:
{{#var:codespath}}



Contents

Web Applications

A Web Applicaton is an application running on the Internet. Ex: Google, Facebook, Amazon, etc.

A WebApp is typically a 3-tier (or multi-tier) client-server database application run over the Internet .

Using simple HTML and CSS we can create static client Web Sites. Sin embargo, para crear páginas más avanzadas (WebApp) necesitamos otras tecnologías.

A WebApp generally comprises five components:

  1. Web Server (HTTP Server):
    • Apache HTTP Server (Compatible con PHP)
    • Apache Tomcat Server (Compatible con JSP (JavaServer Pages))
    • Microsoft Internet Information Server (IIS) (Compatible con ASP.Net)
    • Nginx
    • Google Web Server (GWS)
  2. HTTP Client (or Web Browser):
    • Internet Explorer (MSIE), FireFox, Chrome, Safari.
  3. Database (Un serveur de base de données):
    • MySQL (mysql-server):
    • Open source, free
    • OS: Windows, Mac OS, Linux OS
    • Web Server: Apache Http, IIS amongst others
    • Oracle:
    • Commercial Licence required
    • OS: Windows, Mac OS, Linux OS
    • Web Server: Apache Http, IIS amongst others
    • MSSQL (Microsoft SQL Server):
    • Commercial Licence required
    • OS: windows, (recently linux version)
    • Web server: IIS
    • Other open-sources: Apache Derby, mSQL, SQLite, PostgreSQL, OpenOffice's Base.
    • Other Commercials: IBM DB2, SAP SyBase, MS Access.
  4. Client-Side Programs:
    • HTML
    • CSS
    • JavaScript, VBScript, Flash.
  5. Server-Side Programs:
    • PHP: Platform independent (Windows, Linux, Mac OS)
    • Java Servlet/JSP: Platform independent (Windows, Linux, Mac OS)
    • ASP.NET (Windows only (as IIS proprietary to windows))
    • Othre thecnologies: Perl, Python, CGI.



Wireframe

Algunas aplicaciones para hacer wireframes y otros tipos de gráficos/charts:

  • https://www.lucidchart.com: Esta me pareció excelente. La versión gratis no está mal. Permite realizar muchos tipos de gráficos.
  • https://www.draw.io/: Esta es la que he usado para relizar diagramas en Bases de datos. Permite relizar muchos tipo de gráficos.
  • https://wireframe.cc: Esta es sólo para wireframes. No tiene muchas funciones.



Some fundamental concepts


URLs

URL stands for Uniform Resource Locator. It is generally the address we use to locate files/resources on the web.

An example of a URL is: http://www.example.com/directory-name/file.php

  • http - this is the protocol we are using
  • www.example.com - This is the domain addresss (port 80 assumed) (we could also enter www.example.com:80)
  • directory-name - Path to file (or resource)
  • index.php this is the file we are requesting



Document Object Model (DOM)

The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.

When a web page is shown in the browser, each of the different elements e.g. Input Field, Text Field, Radio Buttons etc are all considered "Elements". Each of these different elements are added to a Tree type structure called the Document Object Model (DOM).

Think about the web page being the root of the tree and each of the elements added to the tree are different branches coming off the tree. Each of the elements has different attributes such as the name, id, value.

Considere el siguiente código html:

<html>
     <head>
          <title>My Title</title>
     </head>
     <body>
          <h1>My Header</h1>
          <a href='www.google.com'>my link</a>
          <div>
               <p>this is a paragraph</p>
          </div>
     </body>
</html>

The DOM defines a structure like this:

DOM structure

There is a parent/child relationship between elements:

  • <h1> is said to be a child of the <body> element
  • <body> is a parent of the <h1> element

HTML

HyperText Markup Language (HTML) is the standard markup language for creating web pages and web applications. With Cascading Style Sheets (CSS), and JavaScript, it forms a triad of cornerstone technologies for the World Wide Web. Web browsers receive HTML documents from a webserver or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document. https://en.wikipedia.org/wiki/HTML

HTML can embed programs written in a scripting language such as JavaScript which affect the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), maintainer of both the HTML and the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997. https://en.wikipedia.org/wiki/HTML

Validations

  • We want to get the right data, in the right format — our applications won't work properly if our user's data is stored in any old format they like, or if they don't enter the correct information in the correct places, or omit it altogether.
  • We want to protect our users — if they entered really easy passwords, or no password at all, then malicious users could easily get into their accounts and steal their data.
  • We want to protect ourselves — there are many ways that malicious users can misuse unprotected forms to damage the application they are part of

Validation comes in three forms:

  • HTML5 - put directly in the form - client side
  • JavaScript - This is done on the - client side
  • PHP - This validation is done on the server side

Client-side validation occurs in the browser, before the data has been submitted to the server. Client Side Validation is more user-friendly and efficient than server-side validation(validation performed by PHP on the client site) as it gives an instant response (it can enhance the user experience by informing the user as to formatting errors and what is expected).

However, client site validation is very easy to hack, as it resides on the client side. People can easily manipulate the JavaScript. Why? Because code can be copied and changed. For example, remove all javascript validation but keeping the form. Then inputting malicious data to the form.

Client side validation is more about creating a better user experience by informing the user as to errors and how to correct them before moving to the server for processing.

Server-side validation is validation that occurs on the server, after the data has been submitted e.g. by a form 'post'. Server-side code is used to validate the data before it is put into the database.

Server-side validation is not as user-friendly as client-side validation, as it requires a round trip to the server, but it is essential — it is your application's last line of defense against bad (meaning incorrect, or even malicious) data.

In other words if we’ve set up our web server security properly it’s difficult for anyone to Get At the php code and manipulate the server side validation.

HTML5 Form validations

Built in form validation is done with HTML5 form validation features. This way of validations has better performance that JavaScript validations, but it is not as customizable. JavaScript is completely customizable.

/var/www/html/webdevelopment/lecture9-CSValidation/CSValidationForm.php
<!DOCTYPE>
<html>
<head>
</head>
<body>
      <form action='cvform.php' method='post'>
                      <!-- The «required» attribute essentially checks if the field is not blank -->
                      <!-- We can add minlength/maxlength attributes (min/max number of characters) to a «text» input field -->
            Username  <input type='text'   name='username' required  minlength='3'  maxlength='40'/><br>
                      <!-- We can add min/max attributes (minimum/maximum value) to a «number» input field -->
            Age       <input type='number' name='age'      required  min='18'  max='35'/><br>
            Telephone <input type='text'   name='tel'      required/><br>
                      <!-- We can add an input types such as «email» -->
            Email     <input type='email'  name='email'    required><br>
            Date      <input type='date'   name='date'     required><br>
                      <input type='submit'/>
      </form>
</body>
</html>

Why is client side validation only not sufficient?

Let's look at our web page and do a view source. Para ver el código fuente de una página web basta con solocar la orden view-source: antes de la dirección de la página:

view-source:http://localhost/webdevelopment/lecture9-CSValidation/cvform.php

view-source:https://www.facebook.com/

Remember what we are seeing in our browser is the 'executed' code from our php file. In our case when we request the php file from the web server we are seeing a combination of the:

  • html text, and
  • text output from the 'executed' php code.

This is why we don't see any php code when we do a view-source in the browser.

But we can see the HTML and JavaScript code. So, we can take a copy of this web page and remove all the validation and then submit the original web page form without any validation:

Breaking client side validation

CSS

Colores

Meilleurs Générateurs de Palette de Couleur:

http://htmlcolorcodes.com/fr/ressources/meilleurs-generateurs-de-palette-de-couleur/

https://color.adobe.com/create/color-wheel/?base=2&rule=Analogous&selected=0&name=My%20Color%20Theme&mode=rgb&rgbvalues=0.8483762931332555,1,0.3951068113728652,0.87,0.5611135766500768,0.04350000000000004,1,0,0,0.338027436008127,0.04550000000000004,0.91,0.6646886641632195,0.9457528844018331,1&swatchOrder=0,1,2,3,4


PHP

  • It's a server side programming language.
  • It's an interpretative language rather than a compiled language.
  • It's typeless: No requiere una estricta definición del tipo de variable.
    • In computer programming, programming languages are often colloquially classified as strongly typed or weakly typed (loosely typed). These terms do not have a precise definition, but in general, a strongly typed language is more likely to generate an error or refuse to compile if the argument passed to a function does not closely match the expected type.
  • PHP can perform complicated tasks such as form processing, database access and update before returning content to the web page.

We need server side technologies as there are tasks that purely client side technologies cannot perform:

  • e.g. accessing databases , accessing services from external applications (APIs - Application Programming Interface)
  • For security reasons client side technologies cannot perform certain tasks



Installing PHP

https://en.wikipedia.org/wiki/PHP

https://websiteforstudents.com/php-php-fpm-7-2-9-releaed-heres-how-to-install-upgrade-on-ubuntu-16-04-18-04/

To use PHP with Apache2 HTTP server, you should first install Apache2.


Para instalar la última versión disponible por defecto en los repositorio de Ubuntu

sudo apt install php


Para instalar la última versión: https://websiteforstudents.com/php-php-fpm-7-2-9-releaed-heres-how-to-install-upgrade-on-ubuntu-16-04-18-04/


No me queda claro si se instalan de php instala también automáticamente las librerías Apache support, and MySQL support. Para estar seguro podemos instalarlas por separado. There are also many PHP modules that perform different function. However, these are some popular ones that may be needed when developing PHP based websites:

sudo apt-get install libapache2-mod-php7.2 
sudo apt-get install php7.2-mysql 
sudo apt-get install php7.2-cli
sudo apt-get install php7.2-gd
sudo apt-get install php7.2-imagick
sudo apt-get install php7.2-recode
sudo apt-get install php7.2-tidy
sudo apt-get install php7.2-xml       # This one is required for Mediawiki. See Help_MediaWiki#Actualización
sudo apt-get install php7.2-xmlrpc    # This one is required for Mediawiki. See Help_MediaWiki#Actualización
sudo apt-get install php7.2-mbstring  # This one is required for Mediawiki. See Help_MediaWiki#Actualización
sudo apt-get install php7.2-curl      # This one is required for Mediawiki

No me queda claro si el 7.2 se tiene que colocar. He intentado realizar las instalaciones sin usar el 7.2 pues «sudo apt-get install php-cli», por ejemplo, debería instalar versión actualizada que sería la 7.2 en este caso. Sin embargo creo que he tenido la necesidad de instalar la librería usado la versi (7.2). En la instalación de MediaWiki creo que en alcunos caso me vi oblidado a colocar el 7.2.



Info PHP

La información de la versión de PHP instalada se puede desplegar ejecutando el archivo:

/var/www/html/info.php
php /var/www/html/info.php

Otra forma es:

php -i

También podemos abrirlo en el navegador web: http://localhost/info.php

Ejecutar un código php desde la línea de comandos

https://www.tecmint.com/run-php-codes-from-linux-commandline/

php script.php


También se puede ejecutar como cualquier script ejecutable (con un simple «./») si el código se coloca dentro de:

Por ejemplo, si creamos phpscript.php:

#!/usr/bin/php

<?php

   // C'odigo php...
 
?>

Podemos (luego de darle la permisología correcta) ejecutar:

./phpscript.php

Activar el modo interactivo desde la línea de comandos

php -a

// or

php -a -c /etc/php/7.0/cli/php.ini

Wherever we want php codes to run into a html doc, we have to surround the php code with:

<?php
   // PHP code ...
?>

The Web Server requires these tags as it indicates to the web server that what is contained within these tags is PHP code which the server needs to process (or parse).

Online PHP tutorials

Estos links fueron colocados por el Prof. en Moodle:

https://www.w3schools.com/php/default.asp

https://www.tutorialspoint.com/php_online_training/index.asp

https://www.codecademy.com/en/tracks/php

http://www.cctmoodle.com/mod/url/view.php?id=27108 (Comes with certification. Other tutorials available for $10)

https://www.ibm.com/developerworks/opensource/tutorials/os-phptut1/os-phptut1.html?ca=drs-

Online PHP editor (for practicing PHP code) N.B. don't include tags: https://repl.it/languages/php

PHP Variables

PHP supports the following data types:

  • String.
  • Integer.
  • Float (floating point numbers - also called double)
  • Boolean.
  • Array.
  • Object.
  • NULL

To determine type of a variable use

gettype($var_name);

Testing type

isset()                 // Esta función se usa para saber si una variable ha sido definida.
is_null()               // Finds whether a variable is NULL
is_bool()               // Finds out whether a variable is a boolean
is_int()                // Find whether the type of a variable is integer
is_float()              // Finds whether the type of a variable is float
is_numeric()            // Finds whether a variable is a number or a numeric string
is_string()             // Find whether the type of a variable is string
is_array()              // Finds whether a variable is an array
is_object()             // Finds whether a variable is an object
is_scalar()             // Finds whether a variable is a scalar

is_callable()           // Verify that the contents of a variable can be called as a function
is_resource()           // Finds whether a variable is a resource
function_exists()       // Return TRUE if the given function has been defined

Strings

To include special characters in a string we use a backslash:

$str = "This is an example \"of a quote\" in a string";

Some comaprison Operators

$a  ==   $b    //  [Equal]           TRUE if $a is equal to $b after type juggling.
$a  ===  $b    //  [Identical]       TRUE if $a is equal to $b and they are of the same type.
$a  !=   $b    //  [Not equal]       TRUE if $a is not iqual to $b after type juggling.
$a  <>   $b    //  [Not equal]       Same as !=
$a  !==  $b    //  [Not identical]   TRUE if $a is not equal to $b, or they are not of the same type.

Logical Operators

!$a             //  [Not]  TRUE if $a is not TRUE.
$a  and  $b     //  [And] 
$a  &&   $b     //  [And]
$a  or   $b     //  [Or]
$a  ||   $b     //  [Or]
$a  xor  $b     //  [Xor]  TRUE if either $a or $b is TRUE, but not both.

Loops

For loop

for (expr1; expr2; expr3)
    statement

While loop

while (condition true)
    Statement

do - while loop

do {
    statements
} while (condition true)

Data Structures

Numeric Arrays

$fruit = array("orange","apple","plum","pear");

echo $fruit[0];  // “orange”
echo $fruit[1];  // “apple”
.
.

// New Element:
$fruit[4] = "grape";

Associative Array

// Numeric Array:
$employee[0] = "sean"

// Associative Arrays:
$employee["firstName"] = "sean"
// First method to create associate array:
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

// Second method to create array:
$salaries["mohammad"] = "high";   // We call "high" the «value» and "mohammad" the «key»
$salaries["qadir"] = "medium";
$salaries["zara"] = "low";

Creación de arreglos numéricos dentro de un arreglo asociativo:

$groceries = array(
                   "fruit"    =>  array("apple",  "orange",  "pear",     "plum"),
                   "veggies"  =>  array("beans",  "carrots", "cabbage",  "potato")
                  );

print_r($groceries);

Ejemplos php publicados por el Prof

Estos ejemplos fueron ya todos estudiados e incluidos en los ejemplos que se muestran abajo.

Examples from today's lecture on PHP code: https://repl.it/LJhN/7

Array examples from todays clas: https://repl.it/LTW8/9

Input validation examples: https://repl.it/MPVF/9

String Validation Examples: https://repl.it/MPT8/0

Ejemplos php

Concatenating strings (joining strings together)

echo "\n1."; // this just outputs a new line

$firstName = 'Sean';
$lastName = 'Citizen';
$name = $firstName." ".$lastName;

// or...

$name = "$firstName $lastName";

echo $name;

Escaping charaters

$str = "This is an example \"of a quote\" in a string";
echo $str;

Using the strlen() to find the number of characters in a string or in a number (int or float)

$str = 'Sean Citizen';
echo "The Number of characters in string is: ".strlen($str);

$a = 2353;
echo strlen($a); // 4
$b = 23.53;
echo strlen($b); // 5 (cuenta el punto)

Removing blank characters from the start and end of the string

Using the strlen() in a built php function (the function trim) to leading and trailing characters from a string, in this example we are removing blank characters from the start and end of the string:

$str = ' ab cdef ';
echo trim($str); // 'ab cdef'

Using == or === comparison operator

$one = 100;
$two = "100";

if ($one == $two)       // variables are equal
// if ($one === $two)   // variables are not equal. Este operador considera el tipo de variable.
  echo "variables are equal\n";
else
  echo "variables are not equal\n";

Array examples

Create and print an array
$fruit = array("apple","orange","pear","plum");
print_r($fruit);
Contar elementos en un array a través de la función count()
$a=array("red","green","blue");
echo "Number of elements in array = ".count($a)."\n";
Remove the last element from numeric array with array_pop
$a=array("red","green","blue");
print_r($a);
$pop_value = array_pop($a);  // Esta función elimina el último valor del arreglo y en esta caso lo almacena en $pop_value
print_r($a);                 // Aquí se deben imprimir sólo los dos primeros valores de $a
echo $pop_value;             // $pop_value debe ser igual a «blue»

Si queremos eliminar algún otro valor del arreglo (varios al mismo tiempo incluso) y reemplazarlos por otros, debemos usar la función array_splice(). Ver http://php.net/manual/en/function.array-splice.php

Add a value to an array with array_push()
$a=array("red","green","blue");
print_r($a);
array_push($a,"yellow");
print_r($a);
Exploding an array

La función explode() separa un «string» tomando en cuenta el delimitador ingresado; y almacena cada «string» en un array. En el siguiente ejemplo estamos indicando un espacio como delimitador " ". El resultado será por lo tanto, un arreglo en el que cada elemento será una de las palabras que conforman el «string» original.

$sent = "This is a new sentance that we have wrote";
$words = explode(" ",$sent);
print_r($words);
Create an associate array

En este ejemplo, a cada car estamos asociando un modelo. Luego podemos usar las funciones array_keys() and array_values() para seleccionar (en nuestro ejemplo) los carros o los modelos por separado.

$cars=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r($cars);
print_r(array_keys($cars));
print_r(array_values($cars));
Iterate over an array
$fruit = array("apple","orange","pear","plum");

foreach ($fruit as $value)
  echo $value."\n";

// Alternative
for ($i=0 ; $i<count($fruit) ; $i++)
  echo $fruit[$i]."\n";
Iterate over an accociative array
$cars=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");

foreach ($cars as $key => $value)
  echo $key." ".$value."\n";

Regular expressions

Aquí se encuentra una mejor explicación de las Regular expressions: https://www.tutorialspoint.com/php/php_regular_expression.htm

$message="abc";
if (preg_match('/^[a-zA-Z]+$/',$message))
   echo "regx message validates\n";  // True
else
   echo "regx message does not validate\n";
$message="aBc123";

if (preg_match('/^[a-zA-Z0-9]+$/',$message))
   echo "regx message validates\n";  // True
else
   echo "regx message does not validate\n";
$message="aBc_123";

if (preg_match('/^[a-zA-Z0-9]+$/',$message))
   echo "regx message validates\n";
else
   echo "regx message does not validate\n";  // Ésta será la respuesta


PHP validation - Server side

PHP Server side validation is more secure, because it is done on the server side, where there is less opportunity to manipulate the code.

What functions can we use to validate our data:

  • String function:
    • isset();
    • empty();
    • strlen();
  • Number functions:
    • is_int()
    • is_decimal()

PHP validation Functions

Comprobar si una variable:

  • No ha sido declarada.
  • ha sido declarada pero está vacía
  • Ha sido declarada e inicializada con un valor:
    • Check for «string», «string with only numbers» or «integer»

Check if the variable has been set:

The variable $message has not been declared or given a value:

if (isset($message))
   echo "message is set\n";  // 'Esta ser'a la respuesta
else 
    echo "message is not set\n";


if (empty($message))
  echo "message empty\n";    // 'Esta ser'a la respuesta
else  
  echo "message not empty\n";

Check if the variable has been set but is empty:

We now set $message to be an empty string:

$message="";  
if (isset($message))
   echo "message is set\n";    //'Esta ser'a la respuesta
else 
    echo "message is not set\n";


if (empty($message))
  echo "message empty\n";      //'Esta ser'a la respuesta
else  
  echo "message not empty\n";


We give the $message variable a value:

$message="a string";
if (isset($message))
   echo "message is set\n";    //'Esta ser'a la respuesta
else 
    echo "message is not set\n";


if (empty($message))
  echo "message empty\n";
else  
  echo "message not empty\n";  //'Esta ser'a la respuesta

Check for «string»:

$message="a string";
if (is_string($message))
  echo "Variable is a string\n";
else
  echo "Variable is not a string\n";

Check for «string with only numbers» or «integer»:

$sid = "2134567";
// $sid = 2134567;
if (is_numeric($sid))
    echo "sid contains only numbers\n";  // Ésta será la respuesta en ambos casos: "2134567" or 2134567
else
    echo "sid does not contain only numbers\n";

Comprobar si la variable es estrictamente un «entero»:

$sid = "2134567";
if (is_int($sid))
    echo "sid is integer\n";
else
    echo "sid is not integer\n" //Ésta será la respuesta

Password encryption

Encrypt any passwords (in php) before storing to database:

$phash = password_hash($password, PASSWORD_BCRYPT);  // PASSWORD_BCRYPT: algorithm type

Adding a Captcha

PHP Frameworks: The Best 10 for Modern Web Development

http://noeticforce.com/best-php-frameworks-for-modern-web-development

Laravel

Symfony

Authorization and Authentication

Say you are going to a football match... Authentication could be thought of as the process of presenting your ticket to the security staff. if you have a valid ticket you are let into the stadium. Authorization could the be thought of as which regions of the stadium am I allowed into w.g. terrace, stand etc.

Authentication

  • What tools do we have to authenticate users:
    • Database, we store user details in a database so we can verify them as valid users later at login
  • Process:
    • Allow users to register with our site and store their details
    • When users logs in they are verified against registration details
    • Security: How can we make this process more secure:
      • Encrypt any passwords (in php) before storing to database.
      • Ensure passwords are not too simple (using validation)
      • We can add a Captcha to a registration file to eliminate the use of robots registering on your form

Authorization

How do we make sure an Authenticated user has access to certain areas of the application:

  • We can use Sessions: Once a user has logged in and has been authenticated we can use sessions to keep track of data between pages.
    • Sessions mean we can pass data around an application without having to go back to the database constantly.
    • Without sessions it would be difficult to maintain state i.e. who is logged in, what their user_type is, user name etc.

Example

  • We're going to write a simple application that allows a user to login in to a form.
  • The method the form uses is a POST.
  • Once we have submitted the form we will captute the form data in some session variables using the global array variable $_SESSION
  • We will then redirect to a confirm page. Which will display the session data.
  • We will add a href link to allow the user to logout of the sesssion and redirect to the login page.
/var/www/html/webdevelopment/lecture11/login.php
<?php

session_start(); 

if($_POST){
      $_SESSION['username'] = $_POST['username'];
      $_SESSION['email']    = $_POST['email'];
      header('Location: confirm.php');
}


?>

<!DOCTYPE html>

<html>

<body>
      <form action="login.php" method="POST">
            Username: <input type='text' name='username'></input>
            Email: <input type='text' name='email' required></input>
            <input type='submit'></input>
      </form>
</body>
</html>


/var/www/html/webdevelopment/lecture11/confirm.php
<?php

session_start();

if(isset($_SESSION['username'])){
      echo '<br/>Username: '.$_SESSION['username'];
      echo '<br/>Email: '.$_SESSION['email'].'<br/>';
}else{
      header('Location: login.php');
      exit();
}

?>

<!DOCTYPE html>
<html>
<body>
      <a href='logout.php'>Logout</a>
</body>
</html>


With logout.php we want to destroy the Session we have created and return to the login page, removing all the session variables. This is very importan to prevent an unauthorized user to access pages that were authorized based on the session variables.

/var/www/html/webdevelopment/lecture11/logout.php
<?php

session_start();
session_unset();
session_destroy();
header('Location: login.php');

?>

logout.php To prove that the session has been destroyed, once logged out try and bringup the confirm.php file in the browser. You should immediately be redirected back to the login page as the $_SESSION[‘username’] should no longer be set.

Transfer data from one php file to another

  • Using sessions
  • Form POST and GET via the $_POST and $_GET global variables
  • Passing parameters in a href link (<a href="xyz.php?id=1">link</a>) then use $_GET to retreive parameter id
  • Cookies, similar to sessions but less secure.

Ejemplo 1: Forms - POST and GET requests - $_SERVER - Sessions

10 CSS HTML Form Designs (Exelente página) https://www.sanwebe.com/2014/08/css-html-forms-designs

En este ejemplo vamos a abordar:

  • Forms
  • POST and GET requests
  • The PHP global variable $_SERVER
  • Sessions
  • The PHP «header» function

To create a simple html page:

<!DOCTYPE html>
<html>
      <head>
      </head>
      <body>
      </body>
</html>

Save as 1form1.php in:

  • The htdocs folder (if using XAMPP)
  • /var/www/html/ (if using LAMP on Ubuntu)

En nuestro caso:


Forms:

Forms allow the user of a website to enter in some information to your website.

All websites use forms in some way, or use elements from forms for different purposes: Registration form, airline booking etc.

In this example, we are going to create an application that posts some «form» data to a separate php file on submission.

Add the form to your web page, between the <body> and </body> tags:

<!DOCTYPE html>
<html>
      <head>
      </head>
      <body>
            <form>
                       <!-- Form code -->
            </form>
      </body>
</html>


http://localhost/webdevelopment/ejemplo1/1form1.php
<!DOCTYPE html>

<html>

    <head>
        <link rel="stylesheet" href="style.css">
    </head>

    <body>
    <!-- Lo siguiente es equivalente a escribir el texto directamente, a continuaci'on lo colocamos
    en un PHP code a manera de ilustraci'on -->
    <?php echo 'Our first Form example'; ?>
    <h2>Form Enter</h2>
        <!-- Ejemplo 1 en el archivo 1form_posted.php (Request via POst) - Descomente la siguiente l'inea: -->
        <form class='form-style-1' action="1form_posted.php" method="POST">
        <!-- Ejemplo 2 en el archivo 1form_posted.php (Request via GET) - Descomente la siguiente l'inea:
        Note que a trav'es de una request via GET, las variables se despliegan en la barra de 
        direcci'on del navegador web. -->
        <!-- <form class='form-style-1' action="1form_posted.php" method="GET"> -->

            <label>First Name</label>
            <input type='text' name='firstname' required></input>


            <br/><br/>

            Password
            <input type='password' name='password'/>

            <br/><br/>

            <!-- Notice that in this case (type='radio') both of the names are set to the same name, this is
            because we want to treat both of these options as part of the same group. En otras palabras, la
            variable asociada a este elemento ser'a gener y valor de dicha variable puede ser 'Male' or 'Female' -->
            <input type='radio' name='gender' value='Male'>Male</input>
            <input type='radio' name='gender' value='Female'>Female</input>

            <br/><br/>

            <!-- Note que en el caso de un checkbox el name debe ser definido como un Array[] debido a que en el
            checkbox se puede seleccionar m'as de un valor. So, si el usuario selecciona 'Car' y 'Bike', el valor
            de la variable ser'a vehicle['Car','Bike'] -->
            <input type='checkbox' name='vehicle[]' value='Car'>I have a Car</input>
            <input type='checkbox' name='vehicle[]' value='Bike'>I have a Bike</input>

            <br/><br/>

            <select name='cartype'>
                <option value='Mini'>Mini</option>
                <option value='Volvo'>Volvo</option>
                <option value='BMW'>BMW</option>
                <option value='Saab'>Saab</option>
                <option value='Ford'>Ford</option>
            </select>

            <br/><br/>

            <textarea name="sometext" rows='4' cols='40'>Web develpment</textarea>

            <br/><br/>

            <input class='button' type='submit'></input>
        </form>
        <!-- Ejemplo 3 en el archivo 1form_posted.php (Request via GET fuera del la </form>)
        Descomente la siguiente l'inea:
        Note como puede ser transmitida una variable, en este ejemplo id=25 -->
        <a href="1form_posted.php?id=25" method="GET">Get Request</a>
    </body>
</html>


Create a new php program in the same folder as called 1form_posted.php

http://localhost/webdevelopment/ejemplo1/1form_posted.php
<?php


// print_r($_SERVER);


// // Ejemplo 1 - Request via POST - Hemos tambi'en colocado un if para eque el 
// // programa compruebe que la request viene via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
      // Todos los valores ingresados en la form se almacenan en la variable $_POST
      print_r($_POST);

      // "<br/>" introduce un salto de l'inea
      echo "<br/>"."First Name: ".$_POST['firstname'];
      echo "<br/>"."Gender: ".$_POST['gender'];
      echo "<br/>"."Car: ".$_POST['cartype'];
      echo "<br/>"."Text: ".$_POST['sometext'];

      // Como $vehicle es un Array[] (ver explicaci'on en 1form1.php) debemos realizar un 
      // loop para imprimir los valores almacenados en la variable $vehible:
      $vehicles = $_POST['vehicle'];
      foreach ($vehicles as $value)
            echo "<br/>Vehicle: ".$value;

      echo "<br/>"."Password: ".$_POST['password'];
      echo "<br/>";
      echo "<br/>";
}
else{
      echo "<br/>"."Bad Request , must come via POST";
}


// // Ejemplo 2 - Request via GET - Descomente la l'inea «method="GET"» en el archivo 1form1.php para este ejemplo.
// // Note que a trav'es de una request via GET, las variables se despliegan en la barra de direcci'on del navegador web.
// echo "<br/>"."First Name: ".$_GET['firstname'];
// echo "<br/>"."Gender: ".$_GET['gender'];
// echo "<br/>"."Car: ".$_GET['cartype'];
// echo "<br/>"."Text: ".$_GET['sometext'];

// $vehicles = $_GET['vehicle'];
//    foreach ($vehicles as $value)
            
// echo "<br/>Vehicle: ".$value;
// echo "<br/>"."Password: ".$_GET['password'];


// // Ejemplo 3 - Request via GET fuera del la </form>
// // Note como puede ser transmitida una variable, en este ejemplo id=25
// if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//    echo "<br/>".$_GET['id'];
//    echo "<br/>"; // line break
// }

?>


Cuando ingresamos la «form» debemos definir tres parámetros:

<form class='form-style-1' action="1form_posted.php" method="POST">
  1. class='form-style-1'
  2. action="1form_posted.php" - Este parámetro define el archivo «.php» que procesará la información ingresada en la «form». Puede ser el mismo archivo en donde se encuentra la «form» u otro archivo.
  3. The Http Request Methods: Http has a number of methods for sending a http request. We will look specifically a the GET and POST methods.
    • method="GET"
    • method="POST"

GET or POST request:

En http://localhost/webdevelopment/ejemplo1/1form1.php la información ingresada en la «form» será enviada y procesada en el archivo http://localhost/webdevelopment/ejemplo1/1form_posted.php

En http://localhost/webdevelopment/ejemplo1/1form_posted.php hemos abordado varios ejemplos para entender los métodos (GET or POST).

Cabe destacar que si usamos «method="GET"», cuando hacemos «submit», se mostrarán en la «Address bar del Web browser» todos los valores ingresados en la «form» (incluyendo el password). Para evitar esto, debemos cambiar a «method="POST"».

HTTP GET Request:
Here are few things to note while using GET method :
  • The principal problem with HTML GET method is that the values sent to the server are visible over the browser address bar, therefore sending sensitive data such as passwords, secret keys using GET method is not advisable.
  • Amount of data can be sent using this method is limited to the length of characters allowed in URL by different browsers.
  • GET parameters remain in browser history because they are part of the URL
  • GET requests can be bookmarked.
  • GET requests should never be used when dealing with sensitive data
  • GET requests have length restrictions
  • GET requests should be used only to retrieve data
Good technique and standards requirements say that you never use GET for an operation that has "side effects," or that actually does something. For example, we’re just looking at data, so no side effects affect the operation. But, ultimately, we're going to add the data to the database, which is, by definition, a side effect.
So the preferred way of sending data to server has been the POST method.
URLs With Parameters:
HTML POST request:
POST method works similar way as GET, but it is safer than GET because the values are not visible on the address bar and will not be stored in browser history.
Benefits of using POST method:
  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length
  • POST variable are not included in url address


PHP $_GET & $_POST variables:
PHP $_GET & $_POST are part of PHP global variables, and can be called anywhere in PHP scripts, both $_GET & $_POST captures data sent with HTML post and get methods.
Cuando enviamos la request, los valores ingresados en la «form» serán almacenados en la variable $_GET o $_POST. Luego podremos recuperar los valores como se hizo en 1form_posted.php:


Each form has a number of different forms elements (tags) that can be added:

  • Input field: <input>
    • Text input: <input type='text'
    • password input: <input type='password'
    • Radio Button: <input type='radio'
    • Checkbox: <input type='checkbox'
  • Select Menu
  • Text Area
  • Submit Button

En cada elemento (tag) podemos definir ciertas opciones. Por ejemplo:

  • name='nombre'
  • value='valor'
  • required

Para una lista completa de los elementos (tags) que pueden ser definidos en una «form» y de todos los elementos que pueden ser definidos en un archivo HTML acuda a: https://www.w3schools.com/tags/

Note que la importanciá de definir correctamente las opciones (campos) de cada elemento radica en el hecho de que cada elemento en la «form» estará asociado con una variable que será probablemente utilizada en el código «php». De ahí la importancia de asociar un «name» y, en muchos casos, un «value» al elemento (variable).


The PHP global variable $_SERVER:

$_SERVER is an associative array which contains a bunch of information about the http request that has been made.

En el Ejemplo 1 de http://localhost/webdevelopment/ejemplo1/1form_posted.php we have put some checking (if) to ensure it cannot be run outside of a «POST form action». To do so, we use a PHP global variable $_SERVER

We are in particular interested in the value of the element «REQUEST_METHOD» which tells us if the form action was a GET or POST (or something else).

To see all elements of the $_SERVER variable we can use the print_r() function which allows us to view the contents of an array.

En el ejemplo mostrado en http://localhost/webdevelopment/ejemplo1/1form_posted.php: If the value of $_SERVER['REQUEST_METHOD'] != "POST", then we flag an error and not continue executing.


Request en el mismo archivo:

Ahora, podría ser conveniente colocar el código que se encuentra en http://localhost/webdevelopment/ejemplo1/1form_posted.php en el mismo archivo en donde se encuentra la «form». Lo anterior se muestra en el siguiente ejemplo:

http://localhost/webdevelopment/ejemplo1/2form2.php
<?php

// Es este ejemplo hemos colocado a «1form1.php» y «1form_posted.php» en un mismo archivo.
// Note que en la l'inea <form class='form-style-1' action="2form2.php" method="POST"> se
// llama este mismo archivo «2form2.php»
// Debemos tambien notar que en este caso es apropiado que la request venga via POST
// porque la GET ser'a ejecutada autom'aticamente cuando abrimos el archivo en el
// navegador web, y queremos que la request sea ejecutada cuando el usuario lo
// indique (en este caso cuando se haga cick en el bot'on «Sumit»)


// print_r($_SERVER);


// // Ejemplo 1 - Request via POST - Hemos tambi'en colocado un if para eque el 
// // programa compruebe que la request viene via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
      // Todos los valores ingresados en la form se almacenan en la variable $_POST
      print_r($_POST);

      // "<br/>" introduce un salto de l'inea
      echo "<br/>"."First Name: ".$_POST['firstname'];
      echo "<br/>"."Gender: ".$_POST['gender'];
      echo "<br/>"."Car: ".$_POST['cartype'];
      echo "<br/>"."Text: ".$_POST['sometext'];

      // Como $vehicle es un Array[] (ver explicaci'on en 1form1.php) debemos realizar un 
      // loop para imprimir los valores almacenados en la variable $vehible:
      $vehicles = $_POST['vehicle'];
      foreach ($vehicles as $value)
            echo "<br/>Vehicle: ".$value;

      echo "<br/>"."Password: ".$_POST['password'];
      echo "<br/>";
      echo "<br/>";
}
// else{
//    echo "<br/>"."Bad Request , must come via POST";
// }


// // Ejemplo 2 - Request via GET - Descomente la l'inea «method="GET"» en el archivo 1form1.php para este ejemplo.
// // Note que a trav'es de una request via GET, las variables se despliegan en la barra de direcci'on del navegador web.
// echo "<br/>"."First Name: ".$_GET['firstname'];
// echo "<br/>"."Gender: ".$_GET['gender'];
// echo "<br/>"."Car: ".$_GET['cartype'];
// echo "<br/>"."Text: ".$_GET['sometext'];

// $vehicles = $_GET['vehicle'];
//    foreach ($vehicles as $value)
            
// echo "<br/>Vehicle: ".$value;
// echo "<br/>"."Password: ".$_GET['password'];


// // Ejemplo 3 - Request via GET fuera del la </form>
// // Note como puede ser transmitida una variable, en este ejemplo id=25
// if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//    echo "<br/>".$_GET['id'];
//    echo "<br/>"; // line break
// }

?>


<!DOCTYPE html>

<html>

      <head>
            <link rel="stylesheet" href="style.css">
      </head>

      <body>
      <!-- Lo siguiente es equivalente a escribir el texto directamente, a continuaci'on lo colocamos
      en un PHP code a manera de ilustraci'on -->
      <?php echo 'Our first Form example'; ?>
      <h2>Form Enter</h2>
            <!-- Ejemplo 1 en el archivo 1form_posted.php (Request via POst) - Descomente la siguiente l'inea: -->
            <form class='form-style-1' action="2form2.php" method="POST">
            <!-- Ejemplo 2 en el archivo 1form_posted.php (Request via GET) - Descomente la siguiente l'inea:
                   Note que a trav'es de una request via GET, las variables se despliegan en la 
                   barra de direcci'on del navegador web. -->
            <!-- <form class='form-style-1' action="2form2.php" method="GET"> -->

                  <label>First Name</label>
                  <input type='text' name='firstname' required></input>

                  <br/><br/>

                  Password
                  <input type='password' name='password'/>

                  <br/><br/>

                  <!-- Notice that in this case (type='radio') both of the names are set to the same name, this is
                  because we want to treat both of these options as part of the same group. En otras palabras, la
                  variable asociada a este elemento ser'a gener y valor de dicha variable puede ser 'Male' or 'Female'-->
                  <input type='radio' name='gender' value='Male'>Male</input>
                  <input type='radio' name='gender' value='Female'>Female</input>

                  <br/><br/>

                  <!-- Note que en el caso de un checkbox el name debe ser definido como un Array[] debido a que en el
                  checkbox se puede seleccionar m'as de un valor. So, si el usuario selecciona 'Car' y 'Bike', el valor
                  de la variable ser'a vehicle['Car','Bike'] -->
                  <input type='checkbox' name='vehicle[]' value='Car'>I have a Car</input>
                  <input type='checkbox' name='vehicle[]' value='Bike'>I have a Bike</input>

                  <br/><br/>

                  <select name='cartype'>
                        <option value='Mini'>Mini</option>
                        <option value='Volvo'>Volvo</option>
                        <option value='BMW'>BMW</option>
                        <option value='Saab'>Saab</option>
                        <option value='Ford'>Ford</option>
                  </select>

                  <br/><br/>

                  <textarea name="sometext" rows='4' cols='40'>Web develpment</textarea>

                  <br/><br/>

                  <input type='submit'></input>
            </form>
            <!-- Ejemplo 3 en el archivo 1form_posted.php (Request via GET fuera del la </form>)
                   Descomente la siguiente l'inea:
                   Note como puede ser transmitida una variable, en este ejemplo id=25 -->
            <a href="1form_posted.php?id=25" method="GET">Get Request</a>
      </body>
</html>


Sessions:

A session is a collection of data «stored on the server» and associated with a given user.

Sessions are different to Cookies. The main difference between a session and a cookie is that session data is stored on the server, whereas a cookies is a collection of data «stored by the browser» and sent to the server with every request.

Sessions are more secure than cookies as it is stored in server. Cookie can be turn off from browser and/or deleted by the client.

We can use a session to retain information from a previous page. Sessions are useful when, for example, a user has logged into an application. We can keep a record of their login details from file to file using a session.

How do we use sessions - $_SESSION: The PHP global variable $_SESSION is basically a variable that we can store values which can be later accessed from another PHP script.

$_SESSION creates a unique id for each user. PHP session can exactly identify each user and serve them stored data.


Starting PHP Session: To start a PHP session, we use session_start() function. It must be on the top of HTML or any text.

Para pasar los valores almacenados en $_SESSION a otro archivo, we can use the php header function:

header('Location: file.php');

The 'header function hace que se ejecute (que se abra por lo tanto) el archivo indicado.

Para entender mejor la utilidad y el funcionamiento de Sessions observe el siguiente ejemplo:

http://localhost/webdevelopment/ejemplo1/3session1.php
<?php

session_start();


// if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//    $_SESSION["name"] = "Adeloaleman";
//    $_SESSION['gender'] = "Male";
//    header('Location: 3session_confirm.php');
// }


// // Aqu'i estamos utilizando «sessions» para almacenar los valores introducidos en la «form»:
// // Estos parametros ser'an luego trans
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      $_SESSION['name'] = $_POST['firstname'];
      $_SESSION['gender'] = $_POST['gender'];
      header('Location: 3session_confirm.php');
}

?>


<!DOCTYPE html>

<html>

      <head>
            <link rel="stylesheet" href="style.css">
      </head>

      <body>
      <?php echo 'Our first Form example'; ?>
      <h2>Form Enter</h2>
            <form class='form-style-1' action="3session1.php" method="POST">

                  <label>First Name</label>
                  <input type='text' name='firstname' required></input>

                  <br/><br/>

                  Password
                  <input type='password' name='password'/>

                  <br/><br/>

                  <input type='radio' name='gender' value='Male'>Male</input>
                  <input type='radio' name='gender' value='Female'>Female</input>

                  <br/><br/>

                  <input type='checkbox' name='vehicle[]' value='Car'>I have a Car</input>
                  <input type='checkbox' name='vehicle[]' value='Bike'>I have a Bike</input>

                  <br/><br/>

                  <select name='cartype'>
                        <option value='Mini'>Mini</option>
                        <option value='Volvo'>Volvo</option>
                        <option value='BMW'>BMW</option>
                        <option value='Saab'>Saab</option>
                        <option value='Ford'>Ford</option>
                  </select>

                  <br/><br/>

                  <textarea name="sometext" rows='4' cols='40'>Web develpment</textarea>

                  <br/><br/>

                  <input type='submit'></input>
            </form>
      </body>
</html>


El siguiente archivo (3session_confirm.php) se ejecuta desde http://localhost/webdevelopment/ejemplo1/3session1.php. Utiliza los valores que, en 3session1.php, fueron almacenados la variable $_SESSION.

http://localhost/webdevelopment/ejemplo1/3session_confirm.php
<?php session_start(); ?>

<!DOCTYPE html>
<html>
<body>

<?php
      // Get session variables
      print_r($_SESSION);
      echo "<br/>".$_SESSION["name"];
      echo "<br/>".$_SESSION["gender"];
?>

</body>
</html>

En http://localhost/webdevelopment/ejemplo1/3session1.php:

  1. Hemos usado sessions para almacenar los valores ingresados en la form en la variable $_SESSION.
  2. Luego la función header('Location: 3session_confirm.php') hace que el archivo 3session_confirm.php se ejecute.
  3. 3session_confirm.php utiliza los valores que, en 3session1.php, fueron almacenados la variable $_SESSION.

Style

En los ejemplos anteriores, note que el archivo «style.css» ha sido integrado a nuestro archivo html de la siguiente forma:

<head>
      <link rel="stylesheet" href="style.css">
</head>

Ahora, en caso de que queramos escribirlo en el mismo file html:

<head>
      <style type="text/css">
      ... Aqu'i escribir'iamos el style
      ...
      ...
      </style>
</head>

De los ejemplos anteriores, note también que hemos agregado un class attribute to the form and input submit button:

<form class='form-style-1' action="1form_posted.php" method="POST">
<input class='button' type='submit'></input>

... estos atributos («form-style-1» «button») se encuentran, por supuesto, definidos en el archivo style.css.

El siguiente es el archivo style.css que hemos usado en este ejemplo:

http://localhost/webdevelopment//ejemplo1/style.css
.form-style-1 {
    margin:10px auto;
    max-width: 400px;
    padding: 20px 12px 10px 20px;
    font: 20px "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}
.form-style-1 li {
    padding: 0;
    display: block;
    list-style: none;
    margin: 10px 0 0 0;
}
.form-style-1 label{
    margin:0 0 3px 0;
    padding:0px;
    display:block;
    font-weight: bold;
}
.form-style-1 input[type=text],
.form-style-1 input[type=date],
.form-style-1 input[type=datetime],
.form-style-1 input[type=number],
.form-style-1 input[type=search],
.form-style-1 input[type=time],
.form-style-1 input[type=url],
.form-style-1 input[type=email],
textarea, 
select{
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    border:1px solid #BEBEBE;
    padding: 7px;
    margin:0px;
    -webkit-transition: all 0.30s ease-in-out;
    -moz-transition: all 0.30s ease-in-out;
    -ms-transition: all 0.30s ease-in-out;
    -o-transition: all 0.30s ease-in-out;
    outline: none;  
}
.form-style-1 input[type=text]:focus, 
.form-style-1 input[type=date]:focus,
.form-style-1 input[type=datetime]:focus,
.form-style-1 input[type=number]:focus,
.form-style-1 input[type=search]:focus,
.form-style-1 input[type=time]:focus,
.form-style-1 input[type=url]:focus,
.form-style-1 input[type=email]:focus,
.form-style-1 textarea:focus,
.form-style-1 select:focus{
    -moz-box-shadow: 0 0 8px #88D5E9;
    -webkit-box-shadow: 0 0 8px #88D5E9;
    box-shadow: 0 0 8px #88D5E9;
    border: 1px solid #88D5E9;
}
.form-style-1 .field-divided{
    width: 49%;
}

.form-style-1 .field-long{
    width: 100%;
}
.form-style-1 .field-select{
    width: 100%;
}
.form-style-1 .field-textarea{
    height: 100px;
}
.form-style-1 input[type=submit], .form-style-1 input[type=button]{
    background: #4B99AD;
    padding: 8px 15px 8px 15px;
    border: none;
    color: #fff;
}
.form-style-1 input[type=submit]:hover, .form-style-1 input[type=button]:hover{
    background: #4691A4;
    box-shadow:none;
    -moz-box-shadow:none;
    -webkit-box-shadow:none;
}
.form-style-1 .required{
    color:red;
}
.button {
    display: inline-block;
    background: #4B99AD;
    padding: 8px 15px 8px 15px;
    border: none;
    color: #fff;
    border-radius: 2px;
    padding: 0.48rem 0.8rem !important;
    line-height: 1.4 !important;
    position: relative;
    text-transform: uppercase;
}

Ejemplo 2 - Databases in PHP

Primero tenemos que crear la base de datos y la tabla que usaremos:

CREATE DATABASE wdtest;

USE wdtest;

CREATE TABLE users(
   id        INT(11)      UNSIGNED   NOT NULL   AUTO_INCREMENT,
   username  VARCHAR(50)  NOT NULL,
   email     VARCHAR(50)  NOT NULL,
   password  VARCHAR(50)  NOT NULL,
   date      TIMESTAMP    NOT NULL,
   PRIMARY KEY(id)
);


En http://localhost/webdevelopment/ejemplo2/1register.php se realiza una conexión con la base de datos. En dicho código This is the line that makes the DB connection:

$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

De esta forma estamos creando an instance of the PDO class, which stands for Prepared Data Object or PHP Data Objects.

Once we have the PDO instance we have available a whole bunch of functions (or methods) to help us interact with the mysql database:

  • prepare() prepare our sql statement
  • bindParam() bind input variables to sql statement
  • execute() execute the sql statement
  • fetch() fetch single row from result of execute
  • query() run a direct sql statement in no params
  • rowCount() number of rows returned from execute
  • fetchAll() returns all rows in a query
  • fetchColumn() return single column from query

The real PDO benefits are:

  • security (usable prepared statements)
  • usability (many helper functions to automate routine operations)
  • reusability (unified API to access multitude of databases, from SQLite to Oracle)

The PDO extension defines a lightweight, consistent interface for accessing databases in PHP. It means that, regardless of which database you're using, use the same functions to issue queries and fetch data. There is no need to rewrite your queries again when you change your database.

Here is a list of database supported by PDO:

  • MySQL
  • Micro Soft SQL Server
  • PostgreSQL
  • Oracle
  • Sqlite
  • IBM DB2
  • Firebird
  • INFORMIX etc.

Security:

One of the big issues with allowing people to insert or select records from forms directly to the database is SQL injection.

SQL injection is when someone adds some SQL into a form field, e.g. the username field with malicious intent to break a database.

SQL injection is a code injection technique, used to attack data-driven applications, in which nefarious SQL statements are inserted into an entry field for execution.

For example, when the insert statement goes to add the username and password into the database, a person may inject some SQL themselves such as:

DROP TABLE users;

Via an input element on the form

Si, por ejemplo, en el campo $name se añade este sentencia:

$name = "Bobby';DROP TABLE users; ";

Y la query es: (Previous versions of php mysql libraries would allow you to set up a query like this)

$query = "SELECT * FROM users WHERE name='$name'";

Se ejecutará la siguiente orden:

SELECT * FROM users WHERE name='Bobby';DROP TABLE users;


Placeholders:

El el siguiente ejemplo, los «?» son llamados Positional Placeholders

# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);

$sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?);";   // Positional Placeholders

$sth = $DBH->prepare($sql);

$sth->bindParam(1, $username);
$sth->bindParam(2, $password);
$sth->bindParam(3, $email);

$sth->execute();


Named Placeholder:

$DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q = $DBH->prepare("select * from users where username = :username and password = :password LIMIT 1");  //Named placeholders

$q->bindValue(':username', $username);
$q->bindValue(':password', $password);
$q->execute();

PDO::bindParam() binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement.

If we use PDOs to do our insert statements, and our select statements with named placeholders, or positional(?) placeholders we can help prevent SQL Injection.

Notice that bindParam only binds data to placeholders leaving unchanged the query. So there is no way to change the original SQL query, because it has already sent to the server by means of the prepare method and because you are sending SQL queries and input data separately so user entered data can't interfere with queries.

This allows SQL to insert the values into the expression, without modifying the expression itself.

So, if the user inserts something lile this:

$name = "Bobby';DROP TABLE users; ";

It simply becomes a search string rather than becoming part of the query. We would be searching for a name of "Bobby';DROP TABLE users; ". Which would be meaningless but harmless.


<?php

session_start();

$username = "";
$email = "";
$password = "";

$usernameErr = "";
$emailErr = "";
$passwordErr = "";


if($_POST){
    // Recuperaci'on de los valores introducidos en la Form:
    $username     = $_POST['username'];
    $email  = $_POST['email'];
    $password     = $_POST['password'];

      // Server Side Validation: Aqu'i nos aseguramos de que los valores introducidos  en la Form sean v'alidos:
      if (empty($username) || strlen($username) < 4 ){
            $usernameErr = 'Username is required, at least 4 chars';
      } 

      if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
            $emailErr = 'Sorry! you did not enter a correct email. ';
      }

      if (strlen($password) < 8) {
            $passwordErr = 'This password is too short!';
      }


      // Si las validaciones realizadas en el paso anterior:
      if (empty($usernameErr) && empty($emailErr) && empty($passwordErr)){
      // if (empty($usernameErr) and empty($emailErr) and empty($passwordErr)) {

            // Conecci'on con la base de datos:
            try {
                  $host       = '127.0.0.1';
                  $port       =  3306;
                  $dbname = 'wdtest';
                  $user       = 'root';
                  $pass       = 'a1640774200';

                  # MySQL with PDO_MYSQL
                  $DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);

                  $sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?);";

                  $sth = $DBH->prepare($sql);
            
                  $sth->bindParam(1, $username);
                  $sth->bindParam(2, $password);
                  $sth->bindParam(3, $email);
            
                  $sth->execute();

                  // Si hubo errores en la request queremos un mensaje de error que nos ayude a
                  // localizar el problema:
                  // We have been having problems with inserts not working and not getting any
                  // useful errors. To remedy this we can add the following after the ->execute() of
                  // our SQL statement:
                  $arr = $sth->errorInfo();
                  if (isset($arr[2])) {// if we have an error...
                        echo "<br/> Database Error Code: ".$arr[0];
                        echo "<br/> Driver Error Code: ".$arr[1];
                        echo "<br/> Database Error Message: ".$arr[2];
                        exit();
                  }

                  $_SESSION["username"] = $username;
                  $_SESSION["email"] = $email;
                  header('Location:  3confirm.php');

                  exit();
            
                  echo 'You are now registered!';
            }
            catch(PDOException $e) {echo 'Error' . $e;} 
            // catch(PDOException $e) {echo $e->getMessage();} 
      }
}

?>
<!DOCTYPE>
<html>
<head>
     <link rel="stylesheet" href="style.css">
     <style>
      .error {display: block;color: #FF0000; }
     </style>
</head>
<body>
      <h2> Registration Form</h2>
      <form class='form-style' action="1register.php" method="post">
            Username <input type="text" name="username" value="<?php echo $username; ?>"/>
                   <span class = "error"><?php echo $usernameErr;?></span>
            email        <input type="text" name="email" value="<?php echo $email; ?>"/>
                   <span class = "error"><?php echo $emailErr;?></span>
            Password <input type="password" name="password" value="<?php echo $password; ?>"/>
                   <span class = "error"><?php echo $passwordErr;?></span>
                   <input type="submit" class='button' name='submit' value= 'Register'/>
      </form>
</body>
</html>


http://localhost/webdevelopment/ejemplo2/2login.php
<?php

session_start();

$username = "";
$password = "";

$usernameErr = "";
$passwordErr = "";


if($_POST){
    $username = $_POST['username'];
    $password = $_POST['password'];

    if(empty($username) || strlen($username) < 4){
      $usernameErr = 'Username is required, at least 4 chars';
    }

    if(strlen($password) < 8){
      $passwordErr = 'password 8 or more chars';
    }
      
    if(empty($usernameErr) && empty($passwordErr)){
    
      try {
          $host = '127.0.0.1';
          $dbname = 'wdtest';
          $user = 'root';
          $pass = 'a1640774200';
          $port=3306;

          # MySQL with PDO_MYSQL
          $DBH = new PDO("mysql:host=$host;dbname=$dbname;port=$port", $user, $pass);
          $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

          $q = $DBH->prepare("select * from users where username = :username and password = :password LIMIT 1");

          $q->bindValue(':username', $username);
          $q->bindValue(':password', $password);
          $q->execute();

          // Mensaje de error si hubo problemas con la request
          $arr = $q->errorInfo();
          if (isset($arr[2])) {// if we have an error...
            echo "<br/> Database Error Code: ".$arr[0];
            echo "<br/> Driver Error Code: ".$arr[1];
            echo "<br/> Database Error Message: ".$arr[2];
              exit();
            }
                  
          $row = $q->fetch(PDO::FETCH_ASSOC);
          // returns table row(s) as an associative array of values column names to data values:
          // Array (    [id]       => 2
          //          [username]   => kike
          //          [email]      => kike@gmail.com
          //              [password]   => kikedominguez
          //              [date]         => 2017-10-27 18:07:15  )

          $message = '';
          if (!empty($row)){ //is the array empty
            $username = $row['username'];
            $email = $row['email'];

            $_SESSION["username"] = $username;
            $_SESSION["email"] = $email;
            header('Location:  3confirm.php');

            exit();
          }
            else {
            $message= 'Sorry your log in details are not correct';
          }
        }catch(PDOException $e) {echo $e->getMessage();}
    }
}
?>

<!DOCTYPE>
<html>
<head>
      <link rel="stylesheet" href="style.css">
    <style>
            .error {display: block;color: #FF0000;}
      </style>
</head>
<body>
      <h2>Login</h2><br></br>   
      <form class='form-style' action="2login.php" method="post">
            Username    <input type="text" name="username" value="<?php echo $username; ?>"/>
                        <span class="error"><?php echo $usernameErr;?></span>
            Password    <input type="password" name="password" value="<?php echo $password; ?>"/>
                        <span class="error"><?php echo $passwordErr;?></span>
                        <input type="submit" name="submit" value="Login" class='button'/>
            <?php
                if(!empty($message)){
                        echo '<br>';
                  echo $message;
                }
            ?>
      </form>
</body>
</html>


http://localhost/webdevelopment/ejemplo2/3confirm.php
<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>
<?php
      // Get session variables
      if (isset($_SESSION["username"])){
           echo "<br/>Logged in as: ".$_SESSION["username"];
           echo "<br/>email: ".$_SESSION["email"];
       }
?>
</body>
</html>

Style

El siguiente es el archivo style.css que hemos usado en este ejemplo:

http://localhost/webdevelopment/ejemplo2/style.css
.button {
    display: inline-block;
    background: #4B99AD;
    padding: 8px 15px 8px 15px;
    border: none;
    color: #fff;
    border-radius: 2px;
    padding: 0.48rem 0.8rem !important;
    line-height: 1.4 !important;
    position: relative;
    text-transform: uppercase;
}

label,input  {
    display:block;
    margin-bottom: 5px;
 
 }

.form-style input[type=text], .form-style input[type=password] {
    height: 28px;
    border-radius: 4px;
    border:1px solid #BEBEBE;
}

.form-style, h2 {
    margin:10px auto;
    max-width: 50%;
    padding: 20px 12px 10px 20px;
}

.form-style input[type=submit]:hover{
    background: #4691A4;
    box-shadow:none;
    -moz-box-shadow:none;
    -webkit-box-shadow:none;
}

.form-style {
    font: 14px "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

Ejemplo 3 - Dynamic Content

Esta sección está basada en: Media:7-ejemplo3-Dynamic_web_pages.pdf

Dynamic vs Static Web Pages:

  • Consider if you were to generate a full page for every single Amazon product, they would be next to impossible to manually manage
  • Pages would get corrupt, lost, mistagged, damaged, etc
  • Given that all of them look the same, and the data/content is different, we can look at the notion of a template
  • If we use a template, we just fill in the blanks, and alter some portions depending on what we need.
  • We need separate files for each bit of code that will be common to all files/pages


Page layout.


Index

«index.php» es al archivo que será llamado por defecto por el web browser.

Por tanto, al colocar en el web browser la dirección: http://localhost/webdevelopment/ejemplo3

... se abrirá el archivo:

http://localhost/webdevelopment/ejemplo3/index.php

<?php
include('header.php');
?>
      <h1>Welcome To our Products App</h1>
      <p>All sorts of normal content go in here</p>
<?php
include('footer.php'); // include the footer page
?>


Header

http://localhost/webdevelopment/ejemplo3/header.php

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<link rel="stylesheet" href="menu.css">
<link rel="stylesheet" href="style.css">
<ul>
      <li><a href="index.php">Home</a></li>
      <li><a href="createProduct.php">New</a></li>
      <li><a href="products.php">List</a></li>
      <li><a href="#about">About</a></li>
</ul>


http://localhost/webdevelopment/ejemplo3/menu.css

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;}
li {
float: left;}
li a {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;}
li a:hover {
background-color: #111;}

Footer

http://localhost/webdevelopment/ejemplo3/footer.php

<div id='footer' >
      <br/><br/>&copy; CCT
      College 2017
</div>
</body>
</html>

Second page

http://localhost/webdevelopment/ejemplo3/secondpage.php

<?php
      include('header.php'); // include the header page
?>

<h1>Second Page</h1>
<p>All sorts of normal content go in here</p>

<?php
      include('footer.php'); // include the footer page
?>


Generate pages based on database entries

CREATE TABLE products(
id                   INT            NOT NULL   AUTO_INCREMENT,
product_name         VARCHAR(50)    NOT NULL,  
product_description  VARCHAR(100),   
cost                 DECIMAL(8,2),   
PRIMARY KEY(id)
);

insert into products values(1, 'phone', 'Some amazing phone An', 235.43);
insert into products values(2, 'tablet', 'even better tablet Snazzy', 452.00);
insert into products values(3, 'laptop', 'laptop', 1234.54);
insert into products values(4, 'desktop', 'Big fancy gaming machine', 2345.43);
insert into products values(5, 'monitor', '32 inch flat screen', 345.32);
insert into products values(6, 'mouse', 'standard mouse', 9.99);
insert into products values(7, 'keyboard', 'wireless keyboard', 20.99);

A continuación se muestra el código que hará la conexión con la base de datos

http://localhost/webdevelopment/ejemplo3/db.php

<?php
      try{
            $host = '127.0.0.1';
            $dbname = 'wdtest';
            $user = 'root';
            $pass = '********';
            $port=3306;
            $DBH = new
            PDO("mysql:host=$host;dbname=$dbname;port=$port",$user,$pass);
      }
      catch (PDOException $e) {echo $e->getMessage();}
?>


http://localhost/webdevelopment/ejemplo3/errordb.php

<?php
      // We have been having problems with inserts not working and not getting any
      // useful errors. To remedy this we can add the following after the ->execute() of
      // our SQL statement:
      $arr = $stmt->errorInfo();
      if (isset($arr[2])) {// if we have an error...
            echo "<br/> Database Error Code: ".$arr[0];
            echo "<br/> Driver Error Code: ".$arr[1];
            echo "<br/> Database Error Message: ".$arr[2];
            exit();
      }
?>


http://localhost/webdevelopment/ejemplo3/products.php

<?php include('header.php'); ?>
<h2>Product list</h2>
<?php
      // create the connection
      include('db.php');
      // select the correct table
      $stmt = $DBH->prepare("SELECT * FROM products");
      $stmt->execute();
      include('errordb.php');
      // get the rows and put it in a variable
      $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
      echo "<table>";
      echo "<tr><th>Id</th><th>Name</th><th>Description</th></tr>";
      foreach($rows as $row){
            echo "<tr>";
            echo "<td>";
            echo $row['id'];
            echo "</td>";
            echo "<td>";
            echo $row['product_name'];
            echo "</td>";
            echo "<td>";
            echo $row['product_description'];
            echo "</td>";
            echo "<td>";
            echo "<a href=viewProduct.php?id=".$row['id'].">View</a>";
            echo "</td>";
            echo "</tr>";
      }
      echo "</table>";
?>
<?php include 'footer.php'; ?>


El siguiente código «.css» define el estilo de la tabla que es desplegada en «products.hph». Este código, sin embargo, es llamado en «header.php»

http://localhost/webdevelopment/ejemplo3/style.css

table {
      border: 1px solid black;
}
th, td {
      padding: 15px;
      text-align: left;
}
th{
      background-color: mediumseagreen;
      color: white}


http://localhost/webdevelopment/ejemplo3/viewProduct.php

<?php include('header.php'); ?>
<h2>Product</h2>
<?php
      $pid = $_GET['id'];
      include('db.php');
      $stmt = $DBH->prepare("SELECT * FROM products WHERE id= :pid");
      $stmt->bindValue(':pid', $pid);
      $stmt->execute();
      include('errordb.php');
      $row = $stmt->fetch(PDO::FETCH_ASSOC);
      echo $row['id'].", ".$row['product_name'].", ".$row['product_description'];
      echo ", ".$row['cost']."<br/>";
?>
<?php include 'footer.php'; ?>


http://localhost/webdevelopment/ejemplo3/deleteProduct.php

<?php include('header.php'); ?>
<?php
      include('db.php');
      if ($_GET){
            $pid = $_GET['id']; // from link in products.php
            $stmt = $DBH->prepare("SELECT * FROM products WHERE id= :pid");
            $stmt->bindValue(':pid', $pid);
            $stmt->execute();
            include('errordb.php');
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $product = $row['product_name'];
            $product_desc = $row['product_description'];
            $cost = $row['cost'];
      }
      if ($_POST) {
            $pid = $_POST['pid']; // from hidden input field
            $stmt = $DBH->prepare("DELETE FROM products WHERE id= :pid");
            $stmt->bindValue(':pid', $pid);
            $stmt->execute();
            include('errordb.php');
            header("Location: products.php");
      }
?>
<h2>Delete Product</h2><br></br>
<form class='form-style' action="deleteProduct.php" method="post">
      Product: <input type="text" name="product" value="<?php echo $product; ?>"
      readonly/>
      Description: <input type="text" name="description" value="<?php echo
      $product_desc; ?>" readonly/>
      Cost: <input type="text" name="cost" value="<?php echo $cost; ?>" readonly/>
      <input type="hidden" name="pid" value="<?php echo $pid; ?>" />
      <input type="submit" name="submit" value="Delete" class='button'/>
</form>
<?php include 'footer.php'; ?>



JavaScript