App inventor 2 en español
Cómo programar los teléfonos móviles con Android
mediante App inventor 2 - Juan Antonio Villalpando
-- Tutorial de iniciación de App Inventor 2 en español --
Volver al índice del tutorial
____________________________
8A.- Crear una MiniWebDB mediante PHP codificada mediante una extensión. TinyWebDB.
p8A_tinywebdb.aia
com.KIO4_SecretKey.aix (Esta extensión funciona con API 26+ (Android 8+), si lo necesitas para un Android inferior, me lo indicas.)
- Si disponemos de un hosting podemos crear una MiniWebDB (o TinyWebDB) mediante PHP como vimos en el tutorial 326A_crear_miniwebDB.htm
- Ahora voy a repetir el código de esa página y además voy a poner una extensión para enviar y guardar la información encriptada.
Colabora en el mantenimiento de esta web.
- Si te gusta este sitio web y quieres colaborar en su mantenimiento, puedes donar unos 7€ o 7$ mediante este enlace de Paypal:
- Gracias por tu colaboración. |
_________________
- Código PHP.
- Subimos este archivo a nuestro hosting.
|
<?php
// Juan Antonio Villalpando
// http://kio4.com/appinventor/8A_MiniWebDB_TinyWebDB.htm
$recibe_post = $_SERVER["REQUEST_URI"];
$etiqueta = $_POST['tag'];
$archivo = 'tinywebdb.htm';
// Si el archivo no existe, lo crea.
if (!file_exists($archivo)) {$crear = fopen($archivo, 'w');}
if(strpos($recibe_post,'storeavalue')){
/////////// Si ya existe esa Etiqueta, la BORRA.
/// para que no esté duplicada.
$arc = file($archivo);
$auxi = fopen($archivo,"w");
foreach($arc as $linea)
{ $campos = explode(":", $linea);
if ($campos[0] != $etiqueta) { fputs($auxi, $linea); }
}
fclose($auxi);
/////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// GUARDAR ETIQUETA Y VALOR.
$valorAGuardar = $_POST['value'];
$linea = $etiqueta.":".$valorAGuardar.": \n";
$auxi = fopen($archivo, 'a'); // Añade $linea al archivo tinywebdb.htm
fwrite($auxi, $linea);
} else {
///////////////////////////////////////////////////////////////////////////////////////////////////
// OBTENER EL VALOR DE LA ETIQUETA.
// Busca en el archivo "tinywebdb.htm" el Valor correspondiente a la Etiqueta pedida.
$auxi = fopen($archivo, 'r');
$existe = "";
while(!feof($auxi)){
$linea = fgets($auxi);
$campos = explode(":", $linea);
if ($campos[0] == $etiqueta) {
$valor =$campos[1];
$existe = true;
}
}
// Envía el resultado.
if ($existe){ $resultado = array("VALUE", $etiqueta, $valor);} // Envia el valor obtenido.
else { $resultado = array("VALUE", $etiqueta, "Not_found");} // Envia "No_existe" esa Etiqueta.
$resultado_en_JSON = json_encode($resultado);
echo $resultado_en_JSON;
}
fclose($auxi);
?>
|
- Con el código anterior ya tenemos un servidor de MiniWebDB (TinyWebDB), podemos utilizar ese componente normalmente.
- Debemos poner en Propiedades la dirección del nuestro hosting en donde hemos subido el archivo tinywebdb.php
- Los datos se guardarán en el archivo tinywebdb.htm.
_____________________________________________________
- TinyWebDB con datos encriptados.
p8A_tinywebdb.aia
com.KIO4_SecretKey.aix
- En el proceso anterior, tanto la subida de datos como su almacenamiento, se realiza directamente sin ninguna protección.
- Con esta extensión vamos a encriptar y desencriptar los datos. Tanto la subida de datos como su almacenamiento así como la bajada estarán encriptado.
- Observa que en las Propiedades de KIO4_SecretKey en Diseño, en tenemos dos claves de encriptación la SecretKey y la Salt. La Salt provoca un reforzamiento de la KeySecret.
___________________________________
- Diseño.
___________________________________
- Bloques.
___________________________________
- Ejemplo de archivo tinywebdb.htm en el servidor.
|
vnjIYkwtSAJMvI5YhWfnpg==:"77AFfhf7h25w5ZVp+St28vKuLj+qgOHo8ovBX5H+2Iw=":
1Fg5AVSB5CFqLJ/c71WqPg==:"Byimv8XYeqSNZ+c4gstAUkNzzW7l4wMNCTN6IEwkN+A=":
UjpIv4gqG34l61B0SZtCeg==:"DthkwsyLP5CEjVqYhRLchg==":
gsIQ+TWc0PA3HtV6eP4gng==:"Ip2gx\/lfzShn1jsxqdio9g==": |
__________________________________________________________________
https://developer.android.com/reference/javax/crypto/Cipher
https://developer.android.com/reference/javax/crypto/SecretKeyFactory
https://developer.android.com/reference/android/util/Base64
https://en.wikipedia.org/wiki/Salt_(cryptography)
|
<?php
// Juan Antonio Villalpando
// http://kio4.com/appinventor/8A_MiniWebDB_TinyWebDB.htm
$receive_post = $_SERVER["REQUEST_URI"];
$tag = $_POST['tag'];
$file = 'tinywebdb.htm';
// If file not exist, create.
if (!file_exists($file)) {$create = fopen($file, 'w');}
if(strpos($receive_post,'storeavalue')){
//////////////////////////////// If exist that tag, DELETE it
//// to avoid repeating that tag.
$arc = file($file);
$auxi = fopen($file,"w");
foreach($arc as $line)
{ $fields = explode(":", $line);
if ($fields[0] != $tag) { fputs($auxi, $line); }
}
fclose($auxi);
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// STORE TAG AND VALUE
$valueToStore = $_POST['value'];
$line = $tag.":".$valueToStore.": \n";
$auxi = fopen($file, 'a'); // Add $line to file tinywebdb.htm
fwrite($auxi, $line);
} else {
///////////////////////////////////////////////////////////////////////////////////////////////////
// GET VALUE OF TAG.
// Search in file tinywebdb.htm value for that tag.
$auxi = fopen($file, 'r');
$exist = "";
while(!feof($auxi)){
$line = fgets($auxi);
$fields = explode(":", $line);
if ($fields[0] == $tag) {
$value =$fields[1];
$exist = true;
}
}
// Sends result.
if ($exist){ $result = array("VALUE", $tag, $value);} // Send value
else { $result = array("VALUE", $tag, "Not_found");} // Send "Not_found".
$result_in_JSON = json_encode($result);
echo $result_in_JSON;
}
fclose($auxi);
?>
|
________________________________________________________________________
- TinyWebDB funcionando de forma parecida a CloudDB. En tiempo real, real time.
p8Ai_tinywebdb_Polling_4.aia
- Copiamos estos dos archivos y ponemos su dirección en la aplicación.
- En el momento que se modifica un dato, se obtiene esa modificación, parecido a CloudDB y FireBase.
- Cada vez que se modifique el archivo data.txt, que es donde están los últimos datos, se mostrará en la aplicación.
- Es una idea de Tim:
https://community.appinventor.mit.edu/t/datachanged-for-php-tinywebdb/13053
|
<?php
// Juan Antonio Villalpando
// http://kio4.com/appinventor/8A_MiniWebDB_TinyWebDB.htm
$receive_post = $_SERVER["REQUEST_URI"];
$tag = $_POST['tag'];
$file = 'tinywebdb.htm'; // ALL data base
$file_2 = 'data.txt'; // Here SAVE only last tag-value
// If file not exist, create.
if (!file_exists($file)) {$create = fopen($file, 'w');}
if (!file_exists($file_2)) {$create_2 = fopen($file_2, 'w');}
if(strpos($receive_post,'storeavalue')){
//////////////////////////////// If exist that tag, DELETE it
//// to avoid repeating that tag.
$arc = file($file);
$auxi = fopen($file,"w");
foreach($arc as $line)
{ $fields = explode(":", $line);
if ($fields[0] != $tag) { fputs($auxi, $line); }
}
fclose($auxi);
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// STORE TAG AND VALUE
$valueToStore = $_POST['value'];
$line = $tag.":".$valueToStore.":\n";
$auxi = fopen($file, 'a'); // Add $line to file tinywebdb.htm
fwrite($auxi, $line);
fclose($auxi);
$auxi = fopen($file_2, 'w'); // SAVE last tag-value in data.txt
fwrite($auxi, $line);
} else {
///////////////////////////////////////////////////////////////////////////////////////////////////
// GET VALUE OF TAG.
// Search in file tinywebdb.htm value for that tag.
$auxi = fopen($file, 'r');
$exist = "";
while(!feof($auxi)){
$line = fgets($auxi);
$fields = explode(":", $line);
if ($fields[0] == $tag) {
$value =$fields[1];
$exist = true;
}
}
// Sends result.
if ($exist){ $result = array("VALUE", $tag, $value);} // Send value
else { $result = array("VALUE", $tag, "Not_found");} // Send "Not_found".
$result_in_JSON = json_encode($result);
echo $result_in_JSON;
}
fclose($auxi);
?>
|
|
<?php
// Juan Antonio Villalpando
// http://kio4.com/appinventor/8A_MiniWebDB_TinyWebDB.htm
/**
* Server-side file.
* This file is an infinitive loop. Seriously.
* It gets the file data.txt's last-changed timestamp, checks if this is larger than the timestamp of the
* AJAX-submitted timestamp (time of last ajax request), and if so, it sends back a JSON with the data from
* data.txt (and a timestamp). If not, it waits for one seconds and then start the next while step.
*
* Note: This returns a JSON, containing the content of data.txt and the timestamp of the last data.txt change.
* This timestamp is used by the client's JavaScript for the next request, so THIS server-side script here only
* serves new content after the last file change. Sounds weird, but try it out, you'll get into it really fast!
*/
// set php runtime to unlimited
set_time_limit(0);
// where does the data come from ? In real world this would be a SQL query or something
$data_source_file = 'data.txt';
// main loop
while (true) {
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = isset($_GET['timestamp']) ? (int)$_GET['timestamp'] : null;
// PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
clearstatcache();
// get timestamp of when file has been changed the last time
$last_change_in_data_file = filemtime($data_source_file);
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $last_change_in_data_file > $last_ajax_call) {
// get content of data.txt
$data = file_get_contents($data_source_file);
// put data.txt's content and timestamp of last data.txt change into array
$result = array(
'data_from_file' => $data,
'timestamp' => $last_change_in_data_file
);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep( 1 );
continue;
}
}
|
__________________________________
|