Compare commits
33 Commits
ad40171fb4
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 35ee82dcf9 | |||
| 29f5fc3d08 | |||
| 06fc0ee834 | |||
| 2f48dbdb45 | |||
| 3439474297 | |||
| e0be3772ad | |||
| 2eb0e06e7b | |||
| cea9405670 | |||
| ac6c9c7d8a | |||
| d72a399125 | |||
| 560be43dff | |||
| d5ec1107a1 | |||
| 11eeb5339c | |||
| a37b2c9a64 | |||
| 84e6977fd7 | |||
| bb3a34af71 | |||
| 4e56440f32 | |||
|
|
8ba2e6d10b | ||
|
|
ca27b6acf6 | ||
|
|
3d907c27f1 | ||
|
|
3e83dea5d2 | ||
|
|
958814b055 | ||
| 387b4dc318 | |||
|
|
5b4e22f627 | ||
| a510b4b658 | |||
|
|
a6dd79e9c8 | ||
| 4cb6127f80 | |||
|
|
7eb369c1cd | ||
|
|
6d00e5cc0e | ||
| f482a5c3dd | |||
|
|
a32d41503d | ||
|
|
af55650a42 | ||
|
|
b83034e0ab |
48
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense para saber los atributos posibles.
|
||||||
|
// Mantenga el puntero para ver las descripciones de los existentes atributos.
|
||||||
|
// Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Listen for Xdebug",
|
||||||
|
"type": "php",
|
||||||
|
"request": "launch",
|
||||||
|
"port": 9003
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Launch currently open script",
|
||||||
|
"type": "php",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${file}",
|
||||||
|
"cwd": "${fileDirname}",
|
||||||
|
"port": 0,
|
||||||
|
"runtimeArgs": [
|
||||||
|
"-dxdebug.start_with_request=yes"
|
||||||
|
],
|
||||||
|
"env": {
|
||||||
|
"XDEBUG_MODE": "debug,develop",
|
||||||
|
"XDEBUG_CONFIG": "client_port=${port}"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Launch Built-in web server",
|
||||||
|
"type": "php",
|
||||||
|
"request": "launch",
|
||||||
|
"runtimeArgs": [
|
||||||
|
"-dxdebug.mode=debug",
|
||||||
|
"-dxdebug.start_with_request=yes",
|
||||||
|
"-S",
|
||||||
|
"localhost:0"
|
||||||
|
],
|
||||||
|
"program": "",
|
||||||
|
"cwd": "${workspaceRoot}",
|
||||||
|
"port": 9003,
|
||||||
|
"serverReadyAction": {
|
||||||
|
"pattern": "Development Server \\(http://localhost:([0-9]+)\\) started",
|
||||||
|
"uriFormat": "http://localhost:%s",
|
||||||
|
"action": "openExternally"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>OBJETOS JAVASCRIPT</title>
|
||||||
|
<script type="text/javascript">
|
||||||
|
|
||||||
|
|
||||||
|
// Definir objetos
|
||||||
|
//Metodo1
|
||||||
|
var miCoche = {
|
||||||
|
marca: "Ford",
|
||||||
|
modelo: "Mustang",
|
||||||
|
ano: 1969
|
||||||
|
};
|
||||||
|
|
||||||
|
//Metodo2
|
||||||
|
var miCoche2 = new Object();
|
||||||
|
miCoche2.marca = "Seat";
|
||||||
|
miCoche2.modelo = "2CV";
|
||||||
|
miCoche2.ano = 1969;
|
||||||
|
|
||||||
|
// Objeto vacio
|
||||||
|
var miCoche3={};
|
||||||
|
|
||||||
|
//Acceso a Propiedades
|
||||||
|
console.log(miCoche2.marca); // Imprime "Seat"
|
||||||
|
console.log(miCoche2['modelo']); // Imprime "2CV"
|
||||||
|
|
||||||
|
|
||||||
|
// Agregar propiedades
|
||||||
|
miCoche.color="white";
|
||||||
|
miCoche.peso="2000kg";
|
||||||
|
|
||||||
|
// Eliminar propiedades
|
||||||
|
delete miCoche.color;
|
||||||
|
|
||||||
|
|
||||||
|
// Definir una clase mediante función constructora
|
||||||
|
function Usuario(nombre, contraseña, email, alta) {
|
||||||
|
this.nombre=nombre;
|
||||||
|
this.contraseña =contraseña;
|
||||||
|
this.email =email;
|
||||||
|
this.alta=alta;
|
||||||
|
// Métodos del objeto
|
||||||
|
this.mostrarUsuario=function() {
|
||||||
|
var datos= "Nombre de usuario: "+this.nombre+"\n"+"E-mail: "+this.email +"\n"+ "Fecha alta: "+this.alta;
|
||||||
|
return datos;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otra manera de definir una clase, ECMAScript 6 y posterior
|
||||||
|
|
||||||
|
var Individuo=class {
|
||||||
|
constructor(nombre,contraseña,email,alta) {
|
||||||
|
this.nombre=nombre;
|
||||||
|
this.contraseña =contraseña;
|
||||||
|
this.email =email;
|
||||||
|
this.alta=alta;
|
||||||
|
this.metodo=function() { return "Hola"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Creamos un objet(Instancia de una clase)
|
||||||
|
usuario1 =new Usuario( "manolo15", "1357ade", "manologarcia@gmail.com","2019");
|
||||||
|
usuario2 =new Usuario( "paco15", "1345", "pacogarcia@gmail.com","2018");
|
||||||
|
|
||||||
|
|
||||||
|
// Añadir una nueva propiedad al prototipo de la clase
|
||||||
|
Usuario.prototype.telefono = null;
|
||||||
|
|
||||||
|
// Creamos una instancia
|
||||||
|
usuario3 =new Usuario( "Lucas", "laquesea", "lucaslaq@gmail.com","2028");
|
||||||
|
// Asignar un valor a la nueva propiedad en una instancia
|
||||||
|
usuario1.telefono = "555-1234";
|
||||||
|
|
||||||
|
|
||||||
|
// Función para el ejemplo del html
|
||||||
|
function alerta(usuario){
|
||||||
|
alert(usuario.mostrarUsuario());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
///Ejemplo
|
||||||
|
// Definir una clase Producto
|
||||||
|
var Producto = class {
|
||||||
|
constructor(precio, tipo, stock) {
|
||||||
|
this.precio = precio;
|
||||||
|
this.tipo = tipo;
|
||||||
|
this.stock = stock;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método incluido en la creación de la clase
|
||||||
|
mostrarProducto() {
|
||||||
|
let datos = "Precio: " + this.precio + "\nTipo: " + this.tipo + "\nStock: " + this.stock;
|
||||||
|
return datos;
|
||||||
|
console.log(datos);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
// Crear 2 instancias de la clase Producto
|
||||||
|
var Producto1 = new Producto(10, "suministro", true);
|
||||||
|
var Producto2 = new Producto(20, "repuesto", false);
|
||||||
|
var Producto3 = new Producto(undefined, "repuesto", false);
|
||||||
|
var Producto4 = new Producto(5, "repuesto", undefined);
|
||||||
|
|
||||||
|
// Llamar al método mostrarProducto para cada instancia
|
||||||
|
//Producto1.mostrarProducto();
|
||||||
|
//Producto2.mostrarProducto();
|
||||||
|
//Producto3.mostrarProducto();
|
||||||
|
console.log(Producto4.mostrarProducto());
|
||||||
|
|
||||||
|
// Función para el ejemplo del html
|
||||||
|
function alertaProducto(Producto){
|
||||||
|
alert(Producto.mostrarProducto());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añadimos una nueva propiedad a Producto1
|
||||||
|
Producto1.oferta=true;
|
||||||
|
|
||||||
|
//Producto1.oferta=false;
|
||||||
|
// Iterar sobre las propiedades de Producto1 con for ... in
|
||||||
|
console.log("Propiedades de Producto1:");
|
||||||
|
for (var clave in Producto1) {
|
||||||
|
console.log(clave + ': ' + Producto1[clave]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Object.keys(obj) itera sobre el objeto y devuelve sus propiedades o keys.
|
||||||
|
console.log("Keys de Producto1:", Object.keys(Producto1));
|
||||||
|
|
||||||
|
// Object.values(obj) itera sobre el objeto y devuelve los valores de sus propiedades.
|
||||||
|
console.log("Values de Producto2:", Object.values(Producto2));
|
||||||
|
|
||||||
|
// Object.entries(obj) itera sobre el objeto y devuelve los pares [key, valor].
|
||||||
|
console.log("Entries de Producto1:", Object.entries(Producto1));
|
||||||
|
|
||||||
|
// Object.fromEntries(array) construye un objeto a partir de un array de pares [key, valor].
|
||||||
|
var objetoDesdeArray = Object.fromEntries(Object.entries(Producto2));
|
||||||
|
console.log("Objeto construido desde array:", objetoDesdeArray);
|
||||||
|
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<span onclick= "alerta(usuario1);">Pulsa aquí para ver a usuario1</span><br>
|
||||||
|
<br>
|
||||||
|
<span onclick= "alerta(usuario2);">Pulsa aquí para ver a usuario2</span><br>
|
||||||
|
<br>
|
||||||
|
<span onclick= "alertaProducto(Producto1);">Pulsa aquí para ver a producto1</span><br>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
101
Practicas/Practicas JS/1 - Introduccion/11_DATE_Javascript.html
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>OBJETO DATE JAVASCRIPT</title>
|
||||||
|
<script type="text/javascript">
|
||||||
|
|
||||||
|
var meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
|
||||||
|
|
||||||
|
var dias = ["Domingo","Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
|
||||||
|
|
||||||
|
|
||||||
|
// Bibliotecas de objetos javascript
|
||||||
|
|
||||||
|
// Clase Date valores del tipo fecha
|
||||||
|
// Fecha de hoy
|
||||||
|
//new Date() Tue Jan 23 2024 19:13:13 GMT+0100
|
||||||
|
//Date.now() hora actual en milisegundos desde el 1 de Enero de 1970, 00:00:00 UTC
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
getDate() Devuelve el día del mes.
|
||||||
|
getDay() Devuelve el día de la semana.(lunes 1, martes 2, ...)
|
||||||
|
getHours() Retorna las horas. En 24H.
|
||||||
|
getMinutes() Devuelve los minutos.
|
||||||
|
getMonth() Devuelve el mes (atención al mes que empieza por 0 Enero).
|
||||||
|
getSeconds() Devuelve los segundos.
|
||||||
|
getTime() Devuelve los milisegundos desde 1970
|
||||||
|
getFullYear() Retorna el año con 4 dígitos.
|
||||||
|
-----
|
||||||
|
setDate() Actualiza el día del mes.
|
||||||
|
setHours() Actualiza la hora.
|
||||||
|
setMinutes() Cambia los minutos.
|
||||||
|
setMonth() Cambia el mes.
|
||||||
|
setSeconds() Cambia los segundos.
|
||||||
|
setTime() Actualiza la fecha completa en milisegundos
|
||||||
|
setFullYear() Cambia el año 4 dígitos
|
||||||
|
*/
|
||||||
|
|
||||||
|
var fechahoy=new Date();
|
||||||
|
var fechaM=Date.now();
|
||||||
|
document.write( "hoy es "+fechahoy);
|
||||||
|
document.write("<br>");
|
||||||
|
document.write( "hoy es "+fechaM);
|
||||||
|
document.write("<br>");
|
||||||
|
document.write(Date.now());
|
||||||
|
document.write("<br>");
|
||||||
|
// Fijar una fecha
|
||||||
|
//miFecha = new Date(año,mes,dia,hora,minutos,segundos,milisegundos)
|
||||||
|
//miFecha = new Date(año,mes,dia)
|
||||||
|
var fecha =new Date(2020,5,1); //En UTC sin tener en cuenta la diferencia horaria
|
||||||
|
var fecha2 = new Date("2020-06-01");
|
||||||
|
var fecha3 = new Date("2020-06-01T00:00:00Z");
|
||||||
|
//console.log(fecha,fecha2);
|
||||||
|
//console.log(fecha.toISOString()); // "2020-06-01T00:00:00.000Z"
|
||||||
|
//console.log(fecha2.toISOString()); // "2020-06-01T00:00:00.000Z"
|
||||||
|
//console.log(fecha3.toISOString()); // "2020-06-01T00:00:00.000Z"
|
||||||
|
|
||||||
|
// Pasar a milisegundos
|
||||||
|
var milFe=fecha.getTime();
|
||||||
|
document.write("<br>fecha " +fecha);
|
||||||
|
document.write("<br>");
|
||||||
|
document.write("<br>fecha " +milFe);
|
||||||
|
document.write("<br>");
|
||||||
|
document.write(" <br>este mes es "+meses[fecha.getMonth()]) ;
|
||||||
|
document.write("<br>");
|
||||||
|
document.write("<br> Hoy es "+dias[fechahoy.getDay()]);
|
||||||
|
document.write("<br>");
|
||||||
|
var date = new Date(872817240000);
|
||||||
|
document.write("<br>"+date);
|
||||||
|
document.write("<br>");
|
||||||
|
|
||||||
|
// valueAsNumber sacar fecha de input "date" en milisegundos
|
||||||
|
//salida=document.getElementById("fecha").valueAsNumber;
|
||||||
|
|
||||||
|
// .toDateString() Devuelve formato sólo de fecha: Fri Aug 24 2018
|
||||||
|
// .toLocaleDateString() Idem al anterior, pero en el formato regional actual: 24/8/2018
|
||||||
|
|
||||||
|
// Clase Math: permite representar y realizar cálculos matemáticos
|
||||||
|
// max y min para valor máximo y minimo
|
||||||
|
document.write("valor máximo "+Math.max(7,3,9)) ;
|
||||||
|
document.write("<br>");
|
||||||
|
// round redondeo
|
||||||
|
document.write("<br>valor redondeado con ROUND "+ Math.round(7.43));
|
||||||
|
document.write("<br>");
|
||||||
|
// Redondeo al alza
|
||||||
|
document.write("<br>valor redondeado con CEIL "+ Math.ceil(7.33));
|
||||||
|
document.write("<br>");
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<input type="date" id="fecha" value="2024-02-24"/>
|
||||||
|
<script>
|
||||||
|
let fechaInput=document.getElementById("fecha").valueAsNumber;
|
||||||
|
console.log(fechaInput);
|
||||||
|
var fechaActual = new Date(); // Fecha y hora actuales
|
||||||
|
console.log(fechaActual);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>OBJETO MATH JAVASCRIPT</title>
|
||||||
|
<script type="text/javascript">
|
||||||
|
|
||||||
|
// 1.Constantes:
|
||||||
|
// Math.PI: Devuelve el valor de PI (3.14159...).
|
||||||
|
// Math.E: Devuelve el valor de la constante de Euler (2.71828...).
|
||||||
|
console.log(Math.PI); // Muestra el valor de PI
|
||||||
|
console.log(Math.E); // Muestra el valor de la constante de Euler
|
||||||
|
|
||||||
|
//2. Funciones trigonométricas:
|
||||||
|
// Math.sin(x): Devuelve el seno de x, donde x está en radianes.
|
||||||
|
// Math.cos(x): Devuelve el coseno de x, donde x está en radianes.
|
||||||
|
// Math.tan(x): Devuelve la tangente de x, donde x está en radianes.
|
||||||
|
var angle = Math.PI / 4;// 45 grados una circunferencia tiene 2PI radianes
|
||||||
|
console.log(Math.sin(angle)); // Seno de 45 grados
|
||||||
|
console.log(Math.cos(angle)); // Coseno de 45 grados
|
||||||
|
console.log(Math.tan(angle)); // Tangente de 45 grados
|
||||||
|
|
||||||
|
//3. Funciones exponenciales y logarítmicas:
|
||||||
|
// Math.exp(x): Devuelve e elevado a la potencia x.
|
||||||
|
// Math.log(x): Devuelve el logaritmo natural de x.
|
||||||
|
// Math.pow(base, exponente): Devuelve base elevado a la potencia exponente.
|
||||||
|
// O con doble **
|
||||||
|
console.log(Math.exp(2)); // e^2
|
||||||
|
console.log(Math.log(Math.E)); // Logaritmo natural de e
|
||||||
|
// Usando Math.pow()
|
||||||
|
let resultado1 = Math.pow(2, 3); // 2^3 = 8
|
||||||
|
console.log(resultado1);
|
||||||
|
// Usando el operador de doble asterisco (**)
|
||||||
|
let resultado2 = 2 ** 3; // 2^3 = 8
|
||||||
|
console.log(resultado2);
|
||||||
|
|
||||||
|
//4. Redondeo y truncamiento:
|
||||||
|
// Math.round(x): Redondea x al entero más cercano.
|
||||||
|
// Math.floor(x): Redondea x hacia abajo al entero más cercano.
|
||||||
|
// Math.ceil(x): Redondea x hacia arriba al entero más cercano.
|
||||||
|
console.log(Math.round(2.7)); // Redondea a 3
|
||||||
|
console.log(Math.round(2.5)); // Redondea a 3
|
||||||
|
console.log(Math.floor(2.7)); // Redondea hacia abajo a 2
|
||||||
|
console.log(Math.ceil(2.1)); // Redondea hacia arriba a 3
|
||||||
|
|
||||||
|
//5. Funciones aleatorias:
|
||||||
|
// Math.random(): Devuelve un número decimal aleatorio entre 0 (inclusive) y 1 (exclusivo).
|
||||||
|
var randomNum = Math.random();
|
||||||
|
console.log(randomNum);
|
||||||
|
var numeroAleatorio3C = Math.floor(Math.random() * 1000);
|
||||||
|
console.log(numeroAleatorio3C);
|
||||||
|
//6. Valor absoluto:
|
||||||
|
// Math.abs(x): Devuelve el valor absoluto de x.
|
||||||
|
var num = -7;
|
||||||
|
console.log(Math.abs(num)); // Valor absoluto de -7 = 7
|
||||||
|
|
||||||
|
//7. Raíz cuadrada:
|
||||||
|
// Math.sqrt(x): Devuelve la raíz cuadrada de x.
|
||||||
|
var squareRoot = 25;
|
||||||
|
console.log(Math.sqrt(squareRoot)); // Raíz cuadrada de 25
|
||||||
|
|
||||||
|
//8. Mínimo y máximo:
|
||||||
|
// Math.min(x1, x2, ..., xn): Devuelve el valor más bajo entre los argumentos.
|
||||||
|
// Math.max(x1, x2, ..., xn): Devuelve el valor más alto entre los argumentos.
|
||||||
|
console.log(Math.min(10, 5, 8)); // Devuelve 5
|
||||||
|
console.log(Math.max(10, 5, 8)); // Devuelve 10
|
||||||
|
|
||||||
|
|
||||||
|
//parseInt() y parseFloat()
|
||||||
|
|
||||||
|
//parseInt(cadena, base);
|
||||||
|
var cadena = "123";
|
||||||
|
var numero = parseInt(cadena);
|
||||||
|
console.log(numero); // Resultado: 123
|
||||||
|
|
||||||
|
var cadena2 = "2.54";
|
||||||
|
var numero2 = parseInt(cadena2);
|
||||||
|
console.log(numero2); // Resultado: 2
|
||||||
|
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
32
Practicas/Practicas JS/2- Funciones/css/style.css
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
label {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="date"],
|
||||||
|
select {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
border: 1px solid;
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
padding: 0 0.6rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dateInput {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 14rem;
|
||||||
|
width: min-content;
|
||||||
|
gap: 0.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.containerFlexCol {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.containerFlexRow {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
66
Practicas/Practicas JS/2- Funciones/index.html
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="stylesheet" href="./css/style.css">
|
||||||
|
<script src="./js/main.js"></script>
|
||||||
|
<title>Funciones útiles JS</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div style="display: flex; flex-direction: column; min-width: max-content; gap: 4px;">
|
||||||
|
<div class="containerFlexRow">
|
||||||
|
<div class="dateInput">
|
||||||
|
<label for="fechaInicio">Fecha de inicio del alquiler </label><input type="date" name="fechaInicio"
|
||||||
|
id="fechaInicio">
|
||||||
|
</div>
|
||||||
|
<div class="dateInput">
|
||||||
|
<label for="fechaFin">Fecha de fin del alquiler </label><input type="date" name="fechaFin"
|
||||||
|
id="fechaFin">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dateInput">
|
||||||
|
<label for="tipoVehiculo">Tipo de vehiculo</label>
|
||||||
|
<select name="tipoVehiculo" id="tipoVehiculo">
|
||||||
|
<option value='basico' selected>Basico (45€ dia)</option>
|
||||||
|
<option value='gama_media'>Gama media (65€ dia)</option>
|
||||||
|
<option value='lujo'>Lujo (85 dia)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="sillaInfantil" id="sillaInfantil">
|
||||||
|
<label for="sillaInfantil">Silla infantil (15€ dia)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="gps" id="gps">
|
||||||
|
<label for="gps">GPS (5€ dia)</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
<input type="radio" name="seguro" value="10" checked required> Seguro a terceros obligatorio si no se
|
||||||
|
contrata otro superior (10€ dia)
|
||||||
|
</div>
|
||||||
|
<input type="radio" name="seguro" value="0"> Todo riesgo (15€ para basico 25€ para gamam media 35€ para lujo)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="menor30" id="menor30" required>
|
||||||
|
<label for="menor30">Menor de 30 años (Recargo del 30% sobre el precio final)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button onclick="calculaAlquiler()">Calcula total</button>
|
||||||
|
</div>
|
||||||
|
<span id="resultado"></span>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
32
Practicas/Practicas JS/2- Funciones/js/main.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// ******************** //
|
||||||
|
// Funciones de Fechas //
|
||||||
|
// ******************** //
|
||||||
|
/**
|
||||||
|
* Devuelve la diferencia en dias entre fechas
|
||||||
|
* @param {Date} fechaIni - Fecha inicial
|
||||||
|
* @param {Date} fechaFin - Fecha final
|
||||||
|
*/
|
||||||
|
function difFechasDias(fechaIni, fechaFin) {
|
||||||
|
const dias = Math.ceil((fechaFin - fechaIni) / (1000 * 60 * 60 * 24));
|
||||||
|
return dias;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve una fecha dada en el siguiente formato Viernes, 26 de Enero de 2024
|
||||||
|
* @param {Date} fecha - Fecha
|
||||||
|
* @returns String
|
||||||
|
*/
|
||||||
|
function formatFecha(fecha) {
|
||||||
|
//prettier-ignore
|
||||||
|
const meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
|
||||||
|
//prettier-ignore
|
||||||
|
const dias = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
|
||||||
|
const diaSemana = fecha.getDay();
|
||||||
|
const diaMes = fecha.getDate();
|
||||||
|
const mes = fecha.getMonth();
|
||||||
|
const ano = fecha.getFullYear();
|
||||||
|
return `${dias[diaSemana]}, ${diaMes} de ${meses[mes]} de ${ano}`;
|
||||||
|
}
|
||||||
139
Practicas/Practicas JS/3 - Pruebas varias/index.html
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Pruebas Varias</title>
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@200&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
outline: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-right: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl>input,
|
||||||
|
.formControl>select {
|
||||||
|
height: 2rem;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
background-color: white;
|
||||||
|
color: rgb(17, 17, 17);
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl>label {
|
||||||
|
font-size: 1em;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControlChk {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControlChk>input[type="checkbox"],
|
||||||
|
.formControlChk>input[type="radio"] {
|
||||||
|
height: 1.2rem;
|
||||||
|
width: 1.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControlChk>label {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
min-height: 2rem;
|
||||||
|
min-width: 2rem;
|
||||||
|
padding: 0.4em;
|
||||||
|
background-color: #0d6efd;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4em;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #0b5ed7;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div style="min-width: 346px;">
|
||||||
|
<h1>Alquiler de habitaciones de hotel</h1>
|
||||||
|
<form id="frmAlquiler">
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaInicio">Fecha de inicio</label><input type="date" name="fechaInicio"
|
||||||
|
id="fechaInicio">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaFinal">Fecha de fin</label><input type="date" name="fechaFinal"
|
||||||
|
id="fechaFinal">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoHabitacion">Tipo de habitacion</label>
|
||||||
|
<select name="tipoHabitacion" id="tipoHabitacion">
|
||||||
|
<option value='individual' selected>Individual</option>
|
||||||
|
<option value='doble'>Doble</option>
|
||||||
|
<option value='triple'>Triple</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2>Elementos Opcionales CheckBox</h2>
|
||||||
|
<div class="formControlChk">
|
||||||
|
<input type="checkbox" name="opc1" id="opc1">
|
||||||
|
<label for="opc1">Opc1</label>
|
||||||
|
</div>
|
||||||
|
<div class="formControlChk">
|
||||||
|
<input type="checkbox" name="opc2" id="opc2">
|
||||||
|
<label for="opc2">Opc2</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2>Elementos Opcionales Radio</h2>
|
||||||
|
<label for="genero">Género:</label>
|
||||||
|
<div class="formControlChk">
|
||||||
|
<input type="radio" name="genero" id="masculino" value="masculino" checked>
|
||||||
|
<label for="masculino">Masculino</label>
|
||||||
|
</div>
|
||||||
|
<div class="formControlChk">
|
||||||
|
<input type="radio" name="genero" id="femenino" value="femenino">
|
||||||
|
<label for="femenino">Femenino</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
<script>
|
||||||
|
|
||||||
|
|
||||||
|
function calculaTotal(){
|
||||||
|
let txtFechaInicio=document.getElementById('fechaInicio');
|
||||||
|
let txtFechaFinal=document.getElementById('fechaFinal');
|
||||||
|
let selTipoHabitacion=document.getElementById('tipoHabitacion');
|
||||||
|
let chkOpc1=document.getElementById('opc1');
|
||||||
|
let chkOpc2=document.getElementById('opc2');
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</html>
|
||||||
62
Practicas/Practicas JS/DOM 05/ejercicio05_DOM.html
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Compra caja JAVASCRIPT</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
|
||||||
|
// Escribir mensaje en el input
|
||||||
|
function mensaje() {
|
||||||
|
// Obtener datos de los inputs
|
||||||
|
let nombre = document.getElementById("nombre").value;
|
||||||
|
let material = document.getElementById("material").value;
|
||||||
|
let tamano = document.querySelector("[name=tamano]:checked").value;
|
||||||
|
let comentarios = document.getElementById("comentarios").value;
|
||||||
|
|
||||||
|
// Ver en consola
|
||||||
|
console.log(nombre, material, tamano, comentarios);
|
||||||
|
// Escribir mensaje en el input
|
||||||
|
document.getElementById("respuesta").value = "Hola " + nombre + " has pedido una caja de " + material + " de tamaño " + tamano + ". " + comentarios;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
|
||||||
|
<p>Nombre cliente</p>
|
||||||
|
<input type="text" name="nombre" id="nombre">
|
||||||
|
<p>Material de la caja
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="material" id="material">
|
||||||
|
<option value="madera">Madera</option>
|
||||||
|
<option value="metal">Metal</option>
|
||||||
|
<option value="plastico">Plástico</option>
|
||||||
|
</select></p>
|
||||||
|
|
||||||
|
<p>Seleccione un tamaño para la caja</p>
|
||||||
|
<br/>
|
||||||
|
<input type="radio" value="diminuta" name="tamano">Diminuta<br>
|
||||||
|
<input type="radio" value="mediana" name="tamano" checked>Mediana<br>
|
||||||
|
<input type="radio" value="grande" name="tamano">Grande<br>
|
||||||
|
<br>
|
||||||
|
<p>Comentarios</p>
|
||||||
|
<!-- Área de texto -->
|
||||||
|
<textarea name="opinion" rows="10" cols="60" id="comentarios"></textarea>
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<input type="submit" value="Enviar" onclick="mensaje()">
|
||||||
|
<input type="text" name="respuesta" id="respuesta" size="80">
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
BIN
Practicas/Practicas JS/DOM 05/ejercicio05_DOM.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
56
Practicas/Practicas JS/DOM 05/index.html
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<script src="./js/main.js"></script>
|
||||||
|
<title>Document</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div style="display: flex; flex-direction: column; gap: 1rem; max-width: 500px; margin: 0 auto;">
|
||||||
|
<div style="display: flex; flex-direction: column;">
|
||||||
|
<label for="nombre">Nombre del cliente</label>
|
||||||
|
<input type="text" name="nombre" id="nombre" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: flex; gap: 2px;">
|
||||||
|
<label for="tipoCaja">Material de la caja</label>
|
||||||
|
<select name="tipoCaja" id="tipoCaja" required>
|
||||||
|
<option value="Madera" selected>Madera</option>
|
||||||
|
<option value="Metal">Metal</option>
|
||||||
|
<option value="Plastico">Plastico</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: flex; flex-direction: column;">
|
||||||
|
<p style="margin: 0px;">Seleccione unas dimensiones para la caja:</p>
|
||||||
|
<div>
|
||||||
|
<input type="radio" name="dimensiones" id="diminuta" value="diminuta" readonly checked>
|
||||||
|
<label for="dimensiones">Diminuta</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="radio" name="dimensiones" id="mediana" value="mediana">
|
||||||
|
<label for="dimensiones">Mediana</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="radio" name="dimensiones" id="grande" value="grande">
|
||||||
|
<label for="dimensiones">Grande</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: flex; flex-direction: column;">
|
||||||
|
<label for="comentarios">Comentarios</label>
|
||||||
|
<textarea name="comentarios" id="comentarios" cols="30" rows="10"></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button onclick="generaPedido()"> Enviar </button>
|
||||||
|
<span id="resultado" style="border: 1px solid black;"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
11
Practicas/Practicas JS/DOM 05/js/main.js
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
|
||||||
|
function generaPedido(){
|
||||||
|
let txtNombre = document.getElementById("nombre").value;
|
||||||
|
let slbMaterial = document.getElementById("tipoCaja").value;
|
||||||
|
let chkDimensiones = document.querySelector('input[name="dimensiones"]:checked').value;
|
||||||
|
let txtComentarios = document.getElementById("comentarios").value;
|
||||||
|
let txtResultado = document.getElementById("resultado");
|
||||||
|
|
||||||
|
let resultado=` ${txtNombre} ha pedido una caja de ${slbMaterial} con unas dimensiones ${chkDimensiones}. ${txtComentarios}`
|
||||||
|
txtResultado.textContent=resultado;
|
||||||
|
}
|
||||||
79
Practicas/Practicas JS/DOM 07/index.html
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>DOM 07</title>
|
||||||
|
<script>
|
||||||
|
function muestraFechaMs() {
|
||||||
|
let ms = new Date().getTime();
|
||||||
|
alert(`Fecha en milisegundos: ${ms} `);
|
||||||
|
let manana = new Date();
|
||||||
|
manana.setDate(manana.getDate() + 1);
|
||||||
|
manana.setHours(10, 0, 0, 0);
|
||||||
|
alert(manana.getTime())
|
||||||
|
}
|
||||||
|
|
||||||
|
function fechaFormato() {
|
||||||
|
var diasSemana = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
|
||||||
|
var meses = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
|
||||||
|
let fecha = new Date();
|
||||||
|
|
||||||
|
const dia = diasSemana[fecha.getDay()]
|
||||||
|
const mes = meses[fecha.getMonth()]
|
||||||
|
const hora = fecha.getHours();
|
||||||
|
const minutos = fecha.getMinutes();
|
||||||
|
alert(`Hoy es ${dia}, ${fecha.getDate()} de ${mes} de ${fecha.getFullYear()} y son las ${hora}:${minutos}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function calcularDiasTranscurridos() {
|
||||||
|
var fechaReferencia = new Date('1950-01-01T10:00:00');
|
||||||
|
var fechaActual = new Date();
|
||||||
|
var diferenciaMilisegundos = fechaActual - fechaReferencia;
|
||||||
|
var diasTranscurridos = Math.floor(diferenciaMilisegundos / (1000 * 60 * 60 * 24));
|
||||||
|
alert('Días transcurridos desde el 1 de Enero de 1950 a las 10:00 hasta ahora: ' + diasTranscurridos + ' días.');
|
||||||
|
}
|
||||||
|
|
||||||
|
function calcularDiasFaltantes() {
|
||||||
|
var fechaInput = document.getElementById('fechaInput').value;
|
||||||
|
if (!fechaInput) {
|
||||||
|
alert('Por favor, selecciona una fecha.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var fechaSeleccionada = new Date(fechaInput);
|
||||||
|
var fechaActual = new Date();
|
||||||
|
var diferenciaMilisegundos = fechaSeleccionada - fechaActual;
|
||||||
|
var diasFaltantes = Math.ceil(diferenciaMilisegundos / (1000 * 60 * 60 * 24));
|
||||||
|
var resultadoElement = document.getElementById('resultado');
|
||||||
|
alert('Días faltantes hasta la fecha seleccionada: ' + diasFaltantes + ' días.');
|
||||||
|
}
|
||||||
|
|
||||||
|
function contarMs(){
|
||||||
|
const inicio=new Date();
|
||||||
|
prompt('Introduce el nombre');
|
||||||
|
prompt('Introduce los apellidos');
|
||||||
|
const fin=new Date();
|
||||||
|
const diferenciaMs=fin-inicio;
|
||||||
|
alert(`Has tardado ${diferenciaMs} ms en introducir los datos.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div style="display: flex; flex-direction: column; width: min-content; gap: 4px; padding: 10px;">
|
||||||
|
<button onclick="muestraFechaMs()">Ahora en Ms</button>
|
||||||
|
<button onclick="fechaFormato()">Frase con hoy</button>
|
||||||
|
<button onclick="calcularDiasTranscurridos()">dias desde 1950</button>
|
||||||
|
<div style="display: flex; width: max-content; gap: 4px;"><button onclick="calcularDiasFaltantes()">Dias que faltan</button> <input type="date" name="fecha"
|
||||||
|
id="fechaInput">
|
||||||
|
</div>
|
||||||
|
<button onclick="contarMs()">Contar Tiempo</button>
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
49
Practicas/Practicas JS/DOM 4/ejercicio04_DOM.html
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Lista de la compra JAVASCRIPT</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
function eliminar(elemento) {
|
||||||
|
// Utilizar remove
|
||||||
|
elemento.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
function anadir() {
|
||||||
|
let listaCompra = document.getElementById("listaCompra");
|
||||||
|
let nuevoItem = document.getElementById("anadir").value;
|
||||||
|
|
||||||
|
if (nuevoItem === "") {
|
||||||
|
alert("No has añadido nada");
|
||||||
|
} else {
|
||||||
|
let item = document.createElement("li");
|
||||||
|
item.textContent = nuevoItem;
|
||||||
|
item.addEventListener("dblclick", function() {
|
||||||
|
eliminar(item);
|
||||||
|
});
|
||||||
|
listaCompra.appendChild(item);
|
||||||
|
document.getElementById("anadir").value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
|
||||||
|
<label>Mi lista de la compra:</label>
|
||||||
|
<input type="text" name="campo" id="anadir">
|
||||||
|
<input type="button" value="Añadir a la lista" onclick="anadir()">
|
||||||
|
|
||||||
|
<ul id="listaCompra"></ul>
|
||||||
|
|
||||||
|
<p>Nota: Puedes eliminar elementos de la lista haciendo doble click sobre ellos</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
18
Practicas/Practicas JS/DOM 4/index.html
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<script src="./js/main.js" defer></script>
|
||||||
|
<title>Ejercicio DOM 4</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<label for="lista">Mi lista de la compra: </label> <input type="text" name="lista" id="txtlista">
|
||||||
|
<button onclick="addElement()">Añadir a la lista</button>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<ul id="listUl"></ul>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
16
Practicas/Practicas JS/DOM 4/js/main.js
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
|
||||||
|
function addElement(){
|
||||||
|
let txtElemento = document.getElementById('txtlista').value;
|
||||||
|
add(txtElemento);
|
||||||
|
}
|
||||||
|
function add(elemento){
|
||||||
|
let listUl = document.getElementById('listUl')
|
||||||
|
let listItem =document.createElement('li');
|
||||||
|
listItem.textContent=elemento;
|
||||||
|
listItem.addEventListener('dblclick',()=>{delElement(listItem)});
|
||||||
|
listUl.appendChild(listItem);
|
||||||
|
}
|
||||||
|
|
||||||
|
function delElement(elemento){
|
||||||
|
elemento.remove();
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title> Ejercicio 06 JAVASCRIPT Coste viaje</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Función que obtiene los datos
|
||||||
|
function obtener() {
|
||||||
|
//let dias=document.getElementById("dias").value;
|
||||||
|
//Calcular estancia
|
||||||
|
let salida=document.getElementById("fecha").valueAsNumber;
|
||||||
|
let vuelta=document.getElementById("fechaVuelta").valueAsNumber;
|
||||||
|
let dif=vuelta - salida;
|
||||||
|
let dias=Math.ceil(dif/(1000*60*60*24));
|
||||||
|
|
||||||
|
let destino=document.getElementById("destino").value;
|
||||||
|
|
||||||
|
|
||||||
|
//Precio coche
|
||||||
|
if (dias>7) {
|
||||||
|
cocheT=dias*40;
|
||||||
|
}else{
|
||||||
|
if (dias<4){
|
||||||
|
cocheT=dias*80;}
|
||||||
|
else{cocheT=dias*60;}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Rellenar el input
|
||||||
|
document.getElementById("coche").value=cocheT;
|
||||||
|
|
||||||
|
/*//Precio noches hotel
|
||||||
|
let hotelT=dias*90;
|
||||||
|
//Rellenar el input
|
||||||
|
document.getElementById("hotel").value=hotelT;
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//Precios viaje en función del destino
|
||||||
|
if (destino === "europa") {
|
||||||
|
//Tasas // Vuelo
|
||||||
|
document.getElementById("viaje").value=50;
|
||||||
|
document.getElementById("vuelo").value=500;
|
||||||
|
document.getElementById("hotel").value=dias*90;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (destino === "asia") {
|
||||||
|
document.getElementById("viaje").value=100;
|
||||||
|
document.getElementById("vuelo").value=1000;
|
||||||
|
document.getElementById("hotel").value=dias*110;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (destino === "africa") {
|
||||||
|
document.getElementById("viaje").value=120;
|
||||||
|
document.getElementById("vuelo").value=1200;
|
||||||
|
document.getElementById("hotel").value=dias*80;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (dias>11){
|
||||||
|
document.getElementById("viaje").value=0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let viaje=parseFloat(document.getElementById("viaje").value);
|
||||||
|
let avion=parseFloat(document.getElementById("vuelo").value);
|
||||||
|
let hotel=parseFloat(document.getElementById("hotel").value);
|
||||||
|
|
||||||
|
let total=avion+hotel+viaje+cocheT;
|
||||||
|
let totalI=(total*1.21).toFixed(2);
|
||||||
|
document.getElementById("total").value=totalI;
|
||||||
|
console.log(dias);
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
|
||||||
|
|
||||||
|
<p>Seleccione Destino
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="destino" id="destino">
|
||||||
|
<option value="europa">Europa</option>
|
||||||
|
<option value="asia">Asia</option>
|
||||||
|
<option value="africa">África</option>
|
||||||
|
</select></p>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
<p>Fechas del viaje</p>
|
||||||
|
<p>Elige el día de salida <input type="date" id="fecha"></p>
|
||||||
|
<p>Elige el día de vuelta <input type="date" id="fechaVuelta"></p>
|
||||||
|
<br>
|
||||||
|
<p>Coste vuelo <input type="text" name="vuelo" id="vuelo"></p>
|
||||||
|
<p>Coste hotel <input type="text" name="hotel" id="hotel"></p>
|
||||||
|
<p>Tasas viaje <input type="text" name="viaje" id="viaje"></p>
|
||||||
|
<p>Coste alquiler coche <input type="text" name="coche" id="coche"></p>
|
||||||
|
<p>Coste total <input type="text" name="total" id="total" ></p>
|
||||||
|
|
||||||
|
<input type="button" value="Calcular coste total" onclick="obtener();">
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<br>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
65
Practicas/Practicas JS/DOM 6 Version 2/index.html
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<script src="./js/main.js" defer></script>
|
||||||
|
<title>Document</title>
|
||||||
|
<style>
|
||||||
|
label{
|
||||||
|
display: inline-block;
|
||||||
|
width: 12rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div style="display: flex; flex-direction: column; max-width: max-content; gap: 10px;">
|
||||||
|
<!-- <div style="display: flex; flex-direction: row; gap: 4px;">
|
||||||
|
<label for="nDias">Introduzca número de dias</label>
|
||||||
|
<input type="text" name="nDias" id="nDias" required>
|
||||||
|
</div> -->
|
||||||
|
<div style="display: flex; gap: 2px;">
|
||||||
|
<label for="destino">Seleccione destino</label>
|
||||||
|
<select name="destino" id="destino" required>
|
||||||
|
<option value=500 selected>Europa</option>
|
||||||
|
<option value=1000>Asia</option>
|
||||||
|
<option value=1200>Africa</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="fechaIda">Fecha de ida</label>
|
||||||
|
<input type="date" name="fechaIda" id="fechaIda" required>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="fechaRegreso">Fecha de regreso</label>
|
||||||
|
<input type="date" name="fechaRegreso" id="fechaRegreso"required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
<div style="display: flex; flex-direction: column; gap: 10px;">
|
||||||
|
<div>
|
||||||
|
<label for="costeVuelo">Coste vuelo</label>
|
||||||
|
<input type="text" name="costeVuelo" id="costeVuelo" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="costeHotel">Coste hotel</label>
|
||||||
|
<input type="text" name="costeHotel" id="costeHotel" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="tasasViaje">Tasas viaje</label>
|
||||||
|
<input type="text" name="tasasViaje" id="tasasViaje" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="costeAlquilerCoche">Coste alquiler coche</label>
|
||||||
|
<input type="text" name="costeAlquilerCoche" id="costeAlquilerCoche" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="costeTotal">Coste total</label>
|
||||||
|
<input type="text" name="costeTotal" id="costeTotal" readonly>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<button onclick="calculaTotales()">Calcular coste total</button>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
54
Practicas/Practicas JS/DOM 6 Version 2/js/main.js
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
function calculaTotales() {
|
||||||
|
|
||||||
|
let nDias = calculaNDias();//document.getElementById("nDias").value;
|
||||||
|
|
||||||
|
let destino = document.getElementById("destino").value;
|
||||||
|
let costeVuelo = document.getElementById("costeVuelo");
|
||||||
|
let costeHotel = document.getElementById("costeHotel");
|
||||||
|
let tasasViaje = document.getElementById("tasasViaje");
|
||||||
|
let costeAlquilerCoche = document.getElementById("costeAlquilerCoche");
|
||||||
|
let costeTotal = document.getElementById("costeTotal");
|
||||||
|
|
||||||
|
let PVPHOTEL;
|
||||||
|
let PVPALQUILERCOCHE =
|
||||||
|
parseInt(nDias) >= 7 ? 40 : parseInt(nDias) <= 3 ? 80 : 60;
|
||||||
|
let IVA = 1.21;
|
||||||
|
|
||||||
|
let tasas = 0;
|
||||||
|
switch (destino) {
|
||||||
|
case "500":
|
||||||
|
tasas = 50;
|
||||||
|
PVPHOTEL = 90;
|
||||||
|
break;
|
||||||
|
case "1000":
|
||||||
|
tasas = 100;
|
||||||
|
PVPHOTEL = 110;
|
||||||
|
break;
|
||||||
|
case "1200":
|
||||||
|
tasas = 120;
|
||||||
|
PVPHOTEL = 80;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (nDias >= 12) {
|
||||||
|
tasas = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let vuelo = parseInt(destino);
|
||||||
|
let hotel = nDias * PVPHOTEL;
|
||||||
|
let alquilerCoche = nDias * PVPALQUILERCOCHE;
|
||||||
|
let total = parseFloat((vuelo + hotel + tasas + alquilerCoche) * IVA).toFixed(
|
||||||
|
2
|
||||||
|
);
|
||||||
|
|
||||||
|
costeVuelo.value = vuelo;
|
||||||
|
costeHotel.value = hotel;
|
||||||
|
tasasViaje.value = tasas;
|
||||||
|
costeAlquilerCoche.value = alquilerCoche;
|
||||||
|
costeTotal.value = total;
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculaNDias(){
|
||||||
|
let inicio=new Date(document.getElementById("fechaIda").value);
|
||||||
|
let fin=new Date(document.getElementById("fechaRegreso").value);
|
||||||
|
return Math.ceil((fin-inicio) / (1000 * 60 * 60 * 24));
|
||||||
|
}
|
||||||
15
Practicas/Practicas JS/DOM 6/Ejerccio06_DOM.txt
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
|
||||||
|
(Precios sin IVA)
|
||||||
|
Destino: 3 opciones
|
||||||
|
Vuelo: Europa=500, Asia=1000,Africa=1200
|
||||||
|
Número de noches: las que sean
|
||||||
|
Tasas del viaje: Europa=50, Asia=100, Africa=120
|
||||||
|
Coste hotel: 90 por noche
|
||||||
|
Coste alquiler coche: 60 por dia
|
||||||
|
|
||||||
|
|
||||||
|
Coste total: debemos calcularlo con IVA
|
||||||
|
|
||||||
|
|
||||||
|
----------------------------
|
||||||
|
|
||||||
BIN
Practicas/Practicas JS/DOM 6/ejercicio06_DOM.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
79
Practicas/Practicas JS/DOM 6/ejercicio06_DOM_version1.html
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title> Ejercicio 06 JAVASCRIPT Coste viaje</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Función que obtiene los datos
|
||||||
|
function obtener() {
|
||||||
|
let dias=document.getElementById("dias").value;
|
||||||
|
let destino=document.getElementById("destino").value;
|
||||||
|
|
||||||
|
|
||||||
|
//Precio coche
|
||||||
|
let cocheT=dias*60;
|
||||||
|
//Rellenar el input
|
||||||
|
document.getElementById("coche").value=cocheT;
|
||||||
|
//Precio noches hotel
|
||||||
|
let hotelT=dias*90;
|
||||||
|
//Rellenar el input
|
||||||
|
document.getElementById("hotel").value=hotelT;
|
||||||
|
|
||||||
|
//Precios viaje en función del destino
|
||||||
|
if (destino === "europa") {
|
||||||
|
//Tasas // Vuelo
|
||||||
|
document.getElementById("viaje").value=50;
|
||||||
|
document.getElementById("vuelo").value=500;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (destino === "asia") {
|
||||||
|
document.getElementById("viaje").value=100;
|
||||||
|
document.getElementById("vuelo").value=1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (destino === "africa") {
|
||||||
|
document.getElementById("viaje").value=120;
|
||||||
|
document.getElementById("vuelo").value=1200;
|
||||||
|
}
|
||||||
|
|
||||||
|
let viaje=parseFloat(document.getElementById("viaje").value);
|
||||||
|
let avion=parseFloat(document.getElementById("vuelo").value);
|
||||||
|
let hotel=parseFloat(document.getElementById("hotel").value);
|
||||||
|
|
||||||
|
let total=avion+hotel+viaje+cocheT;
|
||||||
|
let totalI=(total*1.21).toFixed(2);
|
||||||
|
document.getElementById("total").value=totalI;
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
|
||||||
|
<p>Introduzca número de dias
|
||||||
|
<input type="text" name="dias" id="dias"><br><br>
|
||||||
|
Seleccione Destino
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="destino" id="destino">
|
||||||
|
<option value="europa">Europa</option>
|
||||||
|
<option value="asia">Asia</option>
|
||||||
|
<option value="africa">África</option>
|
||||||
|
</select></p>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
<p>Elige el día de salida <input type="date" id="fecha"></p>
|
||||||
|
<br>
|
||||||
|
<p>Coste vuelo <input type="text" name="vuelo" id="vuelo"></p>
|
||||||
|
<p>Coste hotel <input type="text" name="hotel" id="hotel"></p>
|
||||||
|
<p>Tasas viaje <input type="text" name="viaje" id="viaje"></p>
|
||||||
|
<p>Coste alquiler coche <input type="text" name="coche" id="coche"></p>
|
||||||
|
<p>Coste total <input type="text" name="total" id="total" ></p>
|
||||||
|
|
||||||
|
<input type="button" value="Calcular coste total" onclick="obtener();">
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<br>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
98
Practicas/Practicas JS/DOM 6/ejercicio06_DOM_version2.html
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title> Ejercicio 06 JAVASCRIPT Coste viaje</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// Función que obtiene los datos
|
||||||
|
function obtener() {
|
||||||
|
let dias=document.getElementById("dias").value;
|
||||||
|
let destino=document.getElementById("destino").value;
|
||||||
|
|
||||||
|
|
||||||
|
//Precio coche
|
||||||
|
if (dias>7) {
|
||||||
|
cocheT=dias*40;
|
||||||
|
}else{
|
||||||
|
if (dias<4){
|
||||||
|
cocheT=dias*80;}
|
||||||
|
else{cocheT=dias*60;}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Rellenar el input
|
||||||
|
document.getElementById("coche").value=cocheT;
|
||||||
|
|
||||||
|
/*//Precio noches hotel
|
||||||
|
let hotelT=dias*90;
|
||||||
|
//Rellenar el input
|
||||||
|
document.getElementById("hotel").value=hotelT;
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//Precios viaje en función del destino
|
||||||
|
if (destino === "europa") {
|
||||||
|
//Tasas // Vuelo
|
||||||
|
document.getElementById("viaje").value=50;
|
||||||
|
document.getElementById("vuelo").value=500;
|
||||||
|
document.getElementById("hotel").value=dias*90;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (destino === "asia") {
|
||||||
|
document.getElementById("viaje").value=100;
|
||||||
|
document.getElementById("vuelo").value=1000;
|
||||||
|
document.getElementById("hotel").value=dias*110;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (destino === "africa") {
|
||||||
|
document.getElementById("viaje").value=120;
|
||||||
|
document.getElementById("vuelo").value=1200;
|
||||||
|
document.getElementById("hotel").value=dias*80;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (dias>11){
|
||||||
|
document.getElementById("viaje").value=0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let viaje=parseFloat(document.getElementById("viaje").value);
|
||||||
|
let avion=parseFloat(document.getElementById("vuelo").value);
|
||||||
|
let hotel=parseFloat(document.getElementById("hotel").value);
|
||||||
|
|
||||||
|
let total=avion+hotel+viaje+cocheT;
|
||||||
|
let totalI=(total*1.21).toFixed(2);
|
||||||
|
document.getElementById("total").value=totalI;
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
|
||||||
|
<p>Introduzca número de dias
|
||||||
|
<input type="text" name="dias" id="dias"><br><br>
|
||||||
|
Seleccione Destino
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="destino" id="destino">
|
||||||
|
<option value="europa">Europa</option>
|
||||||
|
<option value="asia">Asia</option>
|
||||||
|
<option value="africa">África</option>
|
||||||
|
</select></p>
|
||||||
|
|
||||||
|
<br>
|
||||||
|
<p>Elige el día de salida <input type="date" id="fecha"></p>
|
||||||
|
<br>
|
||||||
|
<p>Coste vuelo <input type="text" name="vuelo" id="vuelo"></p>
|
||||||
|
<p>Coste hotel <input type="text" name="hotel" id="hotel"></p>
|
||||||
|
<p>Tasas viaje <input type="text" name="viaje" id="viaje"></p>
|
||||||
|
<p>Coste alquiler coche <input type="text" name="coche" id="coche"></p>
|
||||||
|
<p>Coste total <input type="text" name="total" id="total" ></p>
|
||||||
|
|
||||||
|
<input type="button" value="Calcular coste total" onclick="obtener();">
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<br>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
56
Practicas/Practicas JS/DOM 6/index.html
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<script src="./js/main.js" defer></script>
|
||||||
|
<title>Document</title>
|
||||||
|
<style>
|
||||||
|
label{
|
||||||
|
display: inline-block;
|
||||||
|
width: 12rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div style="display: flex; flex-direction: column; max-width: max-content; gap: 10px;">
|
||||||
|
<div style="display: flex; flex-direction: row; gap: 4px;">
|
||||||
|
<label for="nDias">Introduzca número de dias</label>
|
||||||
|
<input type="text" name="nDias" id="nDias" required>
|
||||||
|
</div>
|
||||||
|
<div style="display: flex; gap: 2px;">
|
||||||
|
<label for="destino">Seleccione destino</label>
|
||||||
|
<select name="destino" id="destino" required>
|
||||||
|
<option value=500 selected>Europa</option>
|
||||||
|
<option value=1000>Asia</option>
|
||||||
|
<option value=1200>Africa</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<br>
|
||||||
|
<div style="display: flex; flex-direction: column; gap: 10px;">
|
||||||
|
<div>
|
||||||
|
<label for="costeVuelo">Coste vuelo</label>
|
||||||
|
<input type="text" name="costeVuelo" id="costeVuelo" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="costeHotel">Coste hotel</label>
|
||||||
|
<input type="text" name="costeHotel" id="costeHotel" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="tasasViaje">Tasas viaje</label>
|
||||||
|
<input type="text" name="tasasViaje" id="tasasViaje" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="costeAlquilerCoche">Coste alquiler coche</label>
|
||||||
|
<input type="text" name="costeAlquilerCoche" id="costeAlquilerCoche" readonly>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="costeTotal">Coste total</label>
|
||||||
|
<input type="text" name="costeTotal" id="costeTotal" readonly>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
<button onclick="calculaTotales()">Calcular coste total</button>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
59
Practicas/Practicas JS/DOM 6/js/main.js
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
function calculaTotales() {
|
||||||
|
let nDias = document.getElementById("nDias").value;
|
||||||
|
let destino = document.getElementById("destino").value;
|
||||||
|
let costeVuelo = document.getElementById("costeVuelo");
|
||||||
|
let costeHotel = document.getElementById("costeHotel");
|
||||||
|
let tasasViaje = document.getElementById("tasasViaje");
|
||||||
|
let costeAlquilerCoche = document.getElementById("costeAlquilerCoche");
|
||||||
|
let costeTotal = document.getElementById("costeTotal");
|
||||||
|
|
||||||
|
let PVPHOTEL;
|
||||||
|
let PVPALQUILERCOCHE =
|
||||||
|
parseInt(nDias) >= 7 ? 40 : parseInt(nDias) <= 3 ? 80 : 60;
|
||||||
|
let IVA = 1.21;
|
||||||
|
|
||||||
|
let tasas = 0;
|
||||||
|
switch (destino) {
|
||||||
|
case "500":
|
||||||
|
tasas = 50;
|
||||||
|
PVPHOTEL = 90;
|
||||||
|
break;
|
||||||
|
case "1000":
|
||||||
|
tasas = 100;
|
||||||
|
PVPHOTEL = 110;
|
||||||
|
break;
|
||||||
|
case "1200":
|
||||||
|
tasas = 120;
|
||||||
|
PVPHOTEL = 80;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (nDias >= 12) {
|
||||||
|
tasas = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
let vuelo = parseInt(destino);
|
||||||
|
let hotel = nDias * PVPHOTEL;
|
||||||
|
let alquilerCoche = nDias * PVPALQUILERCOCHE;
|
||||||
|
let total = parseFloat((vuelo + hotel + tasas + alquilerCoche) * IVA).toFixed(
|
||||||
|
2
|
||||||
|
);
|
||||||
|
|
||||||
|
costeVuelo.value = vuelo;
|
||||||
|
costeHotel.value = hotel;
|
||||||
|
tasasViaje.value = tasas;
|
||||||
|
costeAlquilerCoche.value = alquilerCoche;
|
||||||
|
costeTotal.value = total;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Persona {
|
||||||
|
constructor(a) {
|
||||||
|
this.nombre = a;
|
||||||
|
}
|
||||||
|
|
||||||
|
obtenerNombre() {
|
||||||
|
return this.nombre;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let personas = new Persona('hola, ');
|
||||||
|
console.log(personas.obtenerNombre());
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Coste viaje JAVASCRIPT</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
|
||||||
|
// Función obtener() que realizará la captación de datos,los cálculos y la escritura del mensaje de info
|
||||||
|
function obtener() {
|
||||||
|
// Declaro y obtengo las variables de número de días y tipo de vehículo
|
||||||
|
|
||||||
|
//Calcular periodo de alquiler (días)
|
||||||
|
let inicio=document.getElementById("fecha").valueAsNumber;
|
||||||
|
let fin=document.getElementById("fechaF").valueAsNumber;
|
||||||
|
let dif=fin - inicio;
|
||||||
|
let dias=Math.ceil(dif/(1000*60*60*24));
|
||||||
|
|
||||||
|
//Tipo de vehículo
|
||||||
|
let tipo=document.getElementById("tipo").value;
|
||||||
|
|
||||||
|
// Declaro las variables tipoP y riesgo que se reasignarán en los condicionales
|
||||||
|
let tipoP;
|
||||||
|
let riesgo;
|
||||||
|
|
||||||
|
if (tipo == "basico") {
|
||||||
|
tipoP=45;
|
||||||
|
riesgo=15;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tipo == "gamamedia") {
|
||||||
|
tipoP=65;
|
||||||
|
riesgo=25;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tipo == "lujo") {
|
||||||
|
tipoP=85;
|
||||||
|
riesgo=35;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculo el precio por día con tipo de vehículo y seguro
|
||||||
|
let vehiculo;
|
||||||
|
if (document.getElementById("riesgo").checked) {
|
||||||
|
vehiculo=dias*(tipoP+riesgo);
|
||||||
|
} else {vehiculo=dias*(tipoP+10)}
|
||||||
|
|
||||||
|
|
||||||
|
//Extra silla
|
||||||
|
let silla;
|
||||||
|
if (document.getElementById("silla").checked) {
|
||||||
|
silla=15;
|
||||||
|
} else { silla=0}
|
||||||
|
|
||||||
|
//Extra gps
|
||||||
|
let gps;
|
||||||
|
if (document.getElementById("gps").checked) {
|
||||||
|
gps=5;
|
||||||
|
} else { gps=0}
|
||||||
|
|
||||||
|
// Calculo el incremento de precio con extras
|
||||||
|
let extras=(silla+gps)*dias;
|
||||||
|
|
||||||
|
// Calculo el precio de vehículo + extras con IVA
|
||||||
|
let total=vehiculo+extras;
|
||||||
|
let totalI=(total*1.21);
|
||||||
|
|
||||||
|
// Aplico el incremento si es menor de 30 años
|
||||||
|
let precioMenor;
|
||||||
|
if (document.getElementById("menor").checked) {
|
||||||
|
precioMenor=totalI*0.3;
|
||||||
|
} else { precioMenor=0 }
|
||||||
|
|
||||||
|
// Calculo el precio total y los gastos de anulación
|
||||||
|
let totalF=(totalI+precioMenor).toFixed(2);
|
||||||
|
document.getElementById("total").value=totalF;
|
||||||
|
let precioAnulacion=totalF*0.3;
|
||||||
|
let precioAnulacionF=precioAnulacion.toFixed(2);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Cáculo de fechas
|
||||||
|
|
||||||
|
//Fecha del momento de la reserva
|
||||||
|
let hoy=new Date().getTime();
|
||||||
|
// Calculo los días que faltan
|
||||||
|
let dif2=inicio-hoy;
|
||||||
|
let diasF=dif2/(1000*60*60*24);
|
||||||
|
// Fecha de entrega
|
||||||
|
let entregaF=new Date(fin);
|
||||||
|
// Obtengo la fecha de entrega en formato local dd-mm-xxxx
|
||||||
|
let entregaP=entregaF.toLocaleDateString();//.toLocaleDateString()
|
||||||
|
// Obtengo la fecha límite para la anulación
|
||||||
|
let limiteAnulacion=inicio-(5*24*60*60*1000);
|
||||||
|
// Obtengo la fecha de anulación en formato local
|
||||||
|
let anulacionF=new Date(limiteAnulacion);
|
||||||
|
let anulacionP=anulacionF.toLocaleDateString();
|
||||||
|
|
||||||
|
/////////////////////
|
||||||
|
// Inicializar variables de mensaje extras
|
||||||
|
let mensajeSilla = "No has escogido silla infantil" ;
|
||||||
|
let mensajeGps = "No has escogido Gps";
|
||||||
|
let mensajeRiesgo = "No has escogido seguro a todoriesgo";
|
||||||
|
let mensajeMenor = "No tienes recargo por ser menor de 30 ";
|
||||||
|
|
||||||
|
// Resaignar valor mensaje extra si esta checked
|
||||||
|
if(document.getElementById('silla').checked){
|
||||||
|
mensajeSilla = "Has escogido silla infantil";}
|
||||||
|
|
||||||
|
if(document.getElementById('gps').checked){
|
||||||
|
mensajeGps = "Has escogido Gps";}
|
||||||
|
|
||||||
|
if(document.getElementById('riesgo').checked){
|
||||||
|
mensajeRiesgo = "Has escogido seguro a todo riesgo";}
|
||||||
|
|
||||||
|
if(document.getElementById('menor').checked){
|
||||||
|
mensajeMenor = "Tienes recargo por ser menor de 30 ";}
|
||||||
|
/////////////////////////
|
||||||
|
|
||||||
|
// Creo las variables del mensaje
|
||||||
|
let extrasT="Tus extras son los siguientes: " + "\n";
|
||||||
|
|
||||||
|
// Añado los extras al mensaje
|
||||||
|
extrasT += mensajeSilla +"\n"+ mensajeGps +"\n"+ mensajeRiesgo +"\n"+ mensajeMenor
|
||||||
|
|
||||||
|
// Creo el mensaje llamando a las variables
|
||||||
|
let frase="Faltan "+(Math.ceil(diasF))+ " días "+"para tu alquiler"+"\n"
|
||||||
|
+"Tu fecha de de entrega del vehículo es el "+entregaP+"\n"
|
||||||
|
+"Puedes anular tu reserva hasta el día "+anulacionP+"\n"
|
||||||
|
+"El coste de la anulación será de " +precioAnulacionF+ " euros"+"\n"
|
||||||
|
+ extrasT;
|
||||||
|
document.getElementById("info").value=frase;
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
<form action="gracias.html" method="get">
|
||||||
|
<h1>Alquiler de vehículo</h1>
|
||||||
|
|
||||||
|
<p>Elige la fecha de inicio del alquiler<input type="date" id="fecha"></p>
|
||||||
|
<p>Elige la fecha de fin del alquiler<input type="date" id="fechaF"></p>
|
||||||
|
<br>
|
||||||
|
<p>Seleccione el tipo de vehículo
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="tipo" id="tipo">
|
||||||
|
<option value="basico">Básico 45 Euros/día</option>
|
||||||
|
<option value="gamamedia">Gama media 65 Euros/día</option>
|
||||||
|
<option value="lujo">Lujo 85 Euros/día</option>
|
||||||
|
</select></p>
|
||||||
|
<h2>Elementos opcionales</h2>
|
||||||
|
<p>Silla Infantil * 15 Euros por día de alquiler<input type="checkbox" name="silla" id="silla" value="Silla Infantil"></p>
|
||||||
|
<p>GPS * 5 Euros por día de alquiler <input type="checkbox" name="gps" id="gps" value="Gps"></p>
|
||||||
|
<h2>Seguro</h2>
|
||||||
|
<p>** El seguro a terceros es obligatorio y tiene un coste de 10 Euros/día sin IVA</p>
|
||||||
|
<p>Seguro a todo riesgo <input type="checkbox" name="riesgo" id="riesgo" value="Seguro a todo riesgo"></p>
|
||||||
|
<p>Conductor menor de 30 años <input type="checkbox" name="menor" id="menor" value="Menor de 30"></p>
|
||||||
|
<p>Coste total <input type="text" name="total" id="total" ></p>
|
||||||
|
|
||||||
|
<input type="button" value="Calcular coste total" onclick="obtener();">
|
||||||
|
<input type="reset" value="Limpiar">
|
||||||
|
<input type="submit" value="Enviar"><br><br>
|
||||||
|
|
||||||
|
<input type="hidden" name="" id="inputAnulacion" value="" />
|
||||||
|
<textarea rows="8" cols="60" name="info" id="info"></textarea>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
Debemos adaptar el ejercicio anterior.
|
||||||
|
|
||||||
|
- Para el periodo de alquiler solicitamos dos fechas inicio y fin del alquiler.(No el número de días).
|
||||||
|
- Ahora tendra un botón para calcular el coste y sacar la información, otro para realizar el envío del formulario y otro más para limpiar los datos del formulario.
|
||||||
|
|
||||||
|
- Coste de anulación será el 30% del total con IVA incluido y solo se puede anular al menos 5 días antes del inicio del alquiler.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Mensaje en textarea:
|
||||||
|
|
||||||
|
Faltan 2 días para tu alquiler !
|
||||||
|
Tu fecha de de entrega del vehículo es el 27/1/2024 !
|
||||||
|
Puedes anular tu reserva hasta el día 21/1/2024 !
|
||||||
|
El coste de la anulación será de 155.73 euros !
|
||||||
|
Tus extras son los siguientes:
|
||||||
|
Silla Infantil
|
||||||
|
Gps
|
||||||
|
Has contratado seguro a todo riesgo !
|
||||||
|
Tienes recargo por ser menor de 30 años !
|
||||||
143
Practicas/Practicas JS/DOM Alquiler Coche V2/index.html
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
font-size: 1.2em;
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
padding: 0.2em;
|
||||||
|
color: rgb(17, 17, 17);
|
||||||
|
}
|
||||||
|
textarea{
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
padding: 0.2em;
|
||||||
|
color: rgb(17, 17, 17);
|
||||||
|
}
|
||||||
|
label {
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
padding: 0.4em;
|
||||||
|
background-color: #0d6efd;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4em;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #0b5ed7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ct_col {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: max-content;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ct_row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
width: max-content;
|
||||||
|
gap: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gap_1 {
|
||||||
|
gap: 1em;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script src="./js/main.js" defer></script>
|
||||||
|
<title>Alquiler de coche</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div class="ct_col gap_1">
|
||||||
|
<form id="formAlquiler" class="ct_col gap_1">
|
||||||
|
<div class="ct_row">
|
||||||
|
<div class="ct_col">
|
||||||
|
<label for="fechaInicio">Fecha de inicio</label><input type="date" name="fechaInicio"
|
||||||
|
id="fechaInicio">
|
||||||
|
</div>
|
||||||
|
<div class="ct_col">
|
||||||
|
<label for="fechaFin">Fecha de fin</label><input type="date" name="fechaFin" id="fechaFin">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ct_col">
|
||||||
|
<label for="tipoVehiculo">Tipo de vehiculo</label>
|
||||||
|
<select name="tipoVehiculo" id="tipoVehiculo">
|
||||||
|
<option value='basico' selected>Basico (45€ dia)</option>
|
||||||
|
<option value='gama_media'>Gama media (65€ dia)</option>
|
||||||
|
<option value='lujo'>Lujo (85 dia)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2>Elementos Opcionales</h2>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="sillainfantil" id="sillainfantil">
|
||||||
|
<label for="sillainfantil">Silla infantil (15€ por dia)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="gps" id="gps">
|
||||||
|
<label for="gps">GPS (5€ por dia)</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2>Seguro</h2>
|
||||||
|
<p>*** El seguro a terceros es obligatorio y tiene un coste de 10 €/dia
|
||||||
|
sin
|
||||||
|
IVA</p>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="segurotr" id="segurotr">
|
||||||
|
<label for="segurotr">Seguro todo riesgo</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="menor30" id="menor30">
|
||||||
|
<label for="menor30">Menor de 30 años (Recargo del 30% sobre el precio final)</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
</form>
|
||||||
|
<div class="ct_row">
|
||||||
|
<label for="total">Total Coste</label><input type="text" name="total" id="total" readonly>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="ct_row">
|
||||||
|
<button type="button" onclick="calculaAlquiler()">Calcula total</button>
|
||||||
|
<button type="button" onclick="submitForm()">Enviar Formulario</button>
|
||||||
|
<button type="button" onclick="limpiarForm()">Limpiar</button>
|
||||||
|
</div>
|
||||||
|
<textarea style="width:100%; height:30em;" name="resumen" id="resumen"></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
234
Practicas/Practicas JS/DOM Alquiler Coche V2/index_con_js.html
Normal file
@@ -0,0 +1,234 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
font-size: 1.2em;
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
padding: 0.2em;
|
||||||
|
color: rgb(17, 17, 17);
|
||||||
|
}
|
||||||
|
textarea{
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
padding: 0.2em;
|
||||||
|
color: rgb(17, 17, 17);
|
||||||
|
font-size: 0.8em;
|
||||||
|
}
|
||||||
|
label {
|
||||||
|
font-size: 1em;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
padding: 0.4em;
|
||||||
|
background-color: #0d6efd;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4em;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #0b5ed7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ct_col {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: max-content
|
||||||
|
}
|
||||||
|
|
||||||
|
.ct_row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
width: max-content;
|
||||||
|
gap: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gap_1 {
|
||||||
|
gap: 1.2em;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<title>Alquiler de coche</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div class="ct_col gap_1">
|
||||||
|
<h1>Alquiler de vehículo</h1>
|
||||||
|
<form id="formAlquiler" class="ct_col gap_1">
|
||||||
|
<div class="ct_row">
|
||||||
|
<div class="ct_col">
|
||||||
|
<label for="fechaInicio">Fecha de inicio</label><input type="date" name="fechaInicio"
|
||||||
|
id="fechaInicio">
|
||||||
|
</div>
|
||||||
|
<div class="ct_col">
|
||||||
|
<label for="fechaFin">Fecha de fin</label><input type="date" name="fechaFin" id="fechaFin">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="ct_col">
|
||||||
|
<label for="tipoVehiculo">Tipo de vehiculo</label>
|
||||||
|
<select name="tipoVehiculo" id="tipoVehiculo">
|
||||||
|
<option value='basico' selected>Basico (45€ dia)</option>
|
||||||
|
<option value='gama_media'>Gama media (65€ dia)</option>
|
||||||
|
<option value='lujo'>Lujo (85€ dia)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2>Elementos Opcionales</h2>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="sillainfantil" id="sillainfantil">
|
||||||
|
<label for="sillainfantil">Silla infantil (15€ por dia)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="gps" id="gps">
|
||||||
|
<label for="gps">GPS (5€ por dia)</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2>Seguro</h2>
|
||||||
|
<p>*** El seguro a terceros es obligatorio y tiene un coste de 10 €/dia sin IVA</p>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="segurotr" id="segurotr">
|
||||||
|
<label for="segurotr">Seguro todo riesgo (15€, 25€, 35€)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="menor30" id="menor30">
|
||||||
|
<label for="menor30">Menor de 30 años (Recargo del 30% sobre el precio final)</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div class="ct_row">
|
||||||
|
<label for="total">Total Coste</label><input type="text" name="total" id="total" readonly>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="ct_row">
|
||||||
|
<button type="button" onclick="calculaAlquiler()">Calcula total</button>
|
||||||
|
<button type="button" onclick="submitForm()">Enviar Formulario</button>
|
||||||
|
<button type="button" onclick="limpiarForm()">Limpiar</button>
|
||||||
|
</div>
|
||||||
|
<textarea style="width:100%; height:30em;" name="resumen" id="resumen"></textarea>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
<script>
|
||||||
|
const diaInicio = document.getElementById("fechaInicio");
|
||||||
|
const diaFin = document.getElementById("fechaFin");
|
||||||
|
const gamaSeleccionada = document.getElementById("tipoVehiculo");
|
||||||
|
const sillaInfantil = document.getElementById("sillainfantil");
|
||||||
|
const gps = document.getElementById("gps");
|
||||||
|
const seguroTr = document.getElementById("segurotr");
|
||||||
|
const menor30 = document.getElementById("menor30");
|
||||||
|
const total = document.getElementById("total");
|
||||||
|
const txtResumen = document.getElementById("resumen");
|
||||||
|
const GAMAVEHICULOS = ["basico", "gama_media", "lujo"];
|
||||||
|
const PVPALQUILERXDIA = [45, 65, 85];
|
||||||
|
const PVPSEGUROTR = [15, 25, 35];
|
||||||
|
|
||||||
|
function calculaAlquiler() {
|
||||||
|
if (diaInicio.value === "" || diaFin.value === "") {
|
||||||
|
alert("Debe introducir una fecha en ambos campos");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const fechaInicio = new Date(diaInicio.value);
|
||||||
|
const fechaFin = new Date(diaFin.value);
|
||||||
|
if (fechaInicio.getTime() > fechaFin.getTime()) {
|
||||||
|
alert("La fecha de inicio debe ser anterior a la de fin");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let diasAlquiler = difFechasDias(diaInicio.value, diaFin.value);
|
||||||
|
let pvpAlquilerXGama = parseInt(valorXopcion(gamaSeleccionada.value, GAMAVEHICULOS, PVPALQUILERXDIA, 0)*diasAlquiler);
|
||||||
|
let opcSillaInfantil = parseInt(totalXOpcion(sillaInfantil.checked, 15, 0)*diasAlquiler);
|
||||||
|
let opcGps = parseInt(totalXOpcion(gps.checked, 5, 0) * diasAlquiler);
|
||||||
|
let seguro = parseInt(totalXOpcion(seguroTr.checked,valorXopcion(gamaSeleccionada.value, GAMAVEHICULOS, PVPSEGUROTR, 0),10)*diasAlquiler);
|
||||||
|
let pvpSinIva = parseInt(pvpAlquilerXGama+opcSillaInfantil+opcGps+seguro);
|
||||||
|
let pvpConIva = parseFloat(pvpSinIva * 1.21);
|
||||||
|
if (menor30.checked) pvpConIva = pvpConIva * 1.3;
|
||||||
|
|
||||||
|
total.value = pvpConIva.toFixed(2);
|
||||||
|
generaResumen(pvpConIva);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function generaResumen(pvpConIva) {
|
||||||
|
const diasEntrega = difFechasDias(new Date(), diaInicio.value);
|
||||||
|
const msgDiasEntrega = `Faltan ${diasEntrega} días para tu alquiler\n`;
|
||||||
|
const msgFechaEntrega = `Tu fecha de entrega del vehiculo es: ${new Date(diaFin.value).toLocaleDateString()}\n`;
|
||||||
|
const costeAnulacion = parseFloat(pvpConIva * 0.3);
|
||||||
|
const fechaIni=new Date(diaInicio.value)
|
||||||
|
const fechaAnulacion = fechaIni.setDate(fechaIni.getDate()-5)
|
||||||
|
let msgAnulacion = `Puedes anular tu reserva hasta el dia ${new Date(fechaAnulacion).toLocaleDateString()}\n`
|
||||||
|
msgAnulacion+=`El coste de la anulacion será de ${costeAnulacion.toFixed(2)} \n`
|
||||||
|
let msgExtras = "Tus extras son los siguientes: \n";
|
||||||
|
if (sillaInfantil.checked) msgExtras += " - Silla Infantil \n";
|
||||||
|
if (gps.checked) msgExtras += " - Gps \n";
|
||||||
|
seguroTr.checked ? (msgExtras += " - Has contratado seguro a todo riesgo \n") : (msgExtras += " - Has contratado seguro basico \n");
|
||||||
|
if (menor30.checked) msgExtras += " - Tienes recargo por ser menor de 30 años \n";
|
||||||
|
let mensaje = msgDiasEntrega + msgFechaEntrega + msgAnulacion + msgExtras;
|
||||||
|
txtResumen.value = mensaje;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve la diferencia en dias entre fechas
|
||||||
|
* @param {Date} fechaIni - Fecha inicial
|
||||||
|
* @param {Date} fechaFin - Fecha final
|
||||||
|
* @returns number
|
||||||
|
*/
|
||||||
|
function difFechasDias(fechaIni, fechaFin) {
|
||||||
|
let dias = Math.ceil((new Date(fechaFin) - new Date(fechaIni)) / (1000 * 60 * 60 * 24));
|
||||||
|
return dias;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve el valor del correspondiente a una opcion seleccionada
|
||||||
|
* valorXOpcion('d',['a','d','f'],[10,20,5],0) Devolveria 20
|
||||||
|
* @param {*} opc - Opcion a bucar
|
||||||
|
* @param {*} opciones - Array de opciones
|
||||||
|
* @param {*} valores - Array de valores
|
||||||
|
* @param {*} valorDefecto - Valor defecto en caso de no encontrar la opcion
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
function valorXopcion(opc, opciones, valores, valorDefecto) {
|
||||||
|
const index = opciones.indexOf(opc);
|
||||||
|
return index !== -1 ? valores[index] : valorDefecto;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function totalXOpcion(checked, valorChecked, valorUnchecked) {
|
||||||
|
return checked ? valorChecked : valorUnchecked;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function submitForm() {
|
||||||
|
document.getElementById("formAlquiler").submit();
|
||||||
|
}
|
||||||
|
function limpiarForm() {
|
||||||
|
document.getElementById("formAlquiler").reset();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
91
Practicas/Practicas JS/DOM Alquiler Coche V2/js/main.js
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
const diaInicio = document.getElementById("fechaInicio");
|
||||||
|
const diaFin = document.getElementById("fechaFin");
|
||||||
|
const gamaSeleccionada = document.getElementById("tipoVehiculo");
|
||||||
|
const sillaInfantil = document.getElementById("sillainfantil");
|
||||||
|
const gps = document.getElementById("gps");
|
||||||
|
const seguroTr = document.getElementById("segurotr");
|
||||||
|
const menor30 = document.getElementById("menor30");
|
||||||
|
const total = document.getElementById("total");
|
||||||
|
const txtResumen = document.getElementById("resumen");
|
||||||
|
const GAMAVEHICULOS = ["basico", "gama_media", "lujo"];
|
||||||
|
const PVPALQUILERXDIA = [45, 65, 85];
|
||||||
|
const PVPSEGUROTR = [15, 25, 35];
|
||||||
|
const IVA = 1.21;
|
||||||
|
|
||||||
|
function calculaAlquiler() {
|
||||||
|
if (diaInicio.value === "" || diaFin.value === "") {
|
||||||
|
alert("Debe introducir una fecha en ambos campos");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const fechaInicio = new Date(diaInicio.value);
|
||||||
|
const fechaFin = new Date(diaFin.value);
|
||||||
|
if (fechaInicio.getTime() > fechaFin.getTime()) {
|
||||||
|
alert("La fecha de inicio debe ser anterior a la de fin");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let diasAlquiler = difFechasDias(diaInicio.value, diaFin.value);
|
||||||
|
let pvpAlquilerXGama = parseInt(valorXopcion(gamaSeleccionada.value, GAMAVEHICULOS, PVPALQUILERXDIA, 0)*diasAlquiler);
|
||||||
|
let opcSillaInfantil = parseInt(totalXOpcion(sillaInfantil.checked, 15, 0)*diasAlquiler);
|
||||||
|
let opcGps = parseInt(totalXOpcion(gps.checked, 5, 0) * diasAlquiler);
|
||||||
|
let seguro = parseInt(totalXOpcion(seguroTr.checked,valorXopcion(gamaSeleccionada.value, GAMAVEHICULOS, PVPSEGUROTR, 0),10)*diasAlquiler);
|
||||||
|
let pvpSinIva = diasAlquiler+pvpAlquilerXGama+opcSillaInfantil+opcGps+seguro;
|
||||||
|
let pvpConIva = parseFloat(pvpSinIva * IVA);
|
||||||
|
if (menor30.checked) pvpConIva = pvpConIva * 1.3;
|
||||||
|
total.value = pvpConIva.toFixed(2);
|
||||||
|
generaResumen(pvpConIva);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function generaResumen(pvpConIva) {
|
||||||
|
const diasEntrega = difFechasDias(new Date(), diaInicio.value);
|
||||||
|
const msgDiasEntrega = `Faltan ${diasEntrega} días para tu alquiler !\n`;
|
||||||
|
const msgFechaEntrega = "Tu fecha de entrega del vehiculo es: "+new Date(diaInicio.value).toLocaleString("es-ES", {day: "numeric",month: "numeric",year: "numeric",})+" !\n";
|
||||||
|
const costeAnulacion = parseFloat(pvpConIva * 1.3).toFixed(2);
|
||||||
|
const msgAnulacion = diasEntrega >= 5 ? `El coste de la anulación será de ${costeAnulacion} euros !\n` : `No se puede anular al quedar solo ${diasEntrega} dias para la entega !\n`;
|
||||||
|
let msgExtras = "Tus extras son los siguientes: \n";
|
||||||
|
if (sillaInfantil.checked) msgExtras += "Silla Infantil \n";
|
||||||
|
if (gps.checked) msgExtras += "Gps \n";
|
||||||
|
seguroTr.checked ? (msgExtras += "Has contratado seguro a todo riesgo ! \n") : (msgExtras += "Has contratado segurio basico !\n");
|
||||||
|
if (menor30.checked) msgExtras += "Tienes recargo por ser menor de 30 años !\n";
|
||||||
|
let mensaje = msgDiasEntrega + msgFechaEntrega + msgAnulacion + msgExtras;
|
||||||
|
txtResumen.value = mensaje;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve la diferencia en dias entre fechas
|
||||||
|
* @param {Date} fechaIni - Fecha inicial
|
||||||
|
* @param {Date} fechaFin - Fecha final
|
||||||
|
* @returns number
|
||||||
|
*/
|
||||||
|
function difFechasDias(fechaIni, fechaFin) {
|
||||||
|
let dias = Math.ceil(
|
||||||
|
(new Date(fechaFin) - new Date(fechaIni)) / (1000 * 60 * 60 * 24)
|
||||||
|
);
|
||||||
|
return dias;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve el valor del correspondiente a una opcion seleccionada
|
||||||
|
* valorXOpcion('d',['a','d','f'],[10,20,5],0) Devolveria 20
|
||||||
|
* @param {*} opc - Opcion a bucar
|
||||||
|
* @param {*} opciones - Array de opciones
|
||||||
|
* @param {*} valores - Array de valores
|
||||||
|
* @param {*} valorDefecto - Valor defecto en caso de no encontrar la opcion
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
|
||||||
|
function valorXopcion(opc, opciones, valores, valorDefecto) {
|
||||||
|
const index = opciones.indexOf(opc);
|
||||||
|
return index !== -1 ? valores[index] : valorDefecto;
|
||||||
|
}
|
||||||
|
function totalXOpcion(checked, valorChecked, valorUnchecked) {
|
||||||
|
return checked ? valorChecked : valorUnchecked;
|
||||||
|
}
|
||||||
|
function submitForm() {
|
||||||
|
document.getElementById("formAlquiler").submit();
|
||||||
|
}
|
||||||
|
function limpiarForm() {
|
||||||
|
document.getElementById("formAlquiler").reset();
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Coste alquiler JAVASCRIPT</title>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
// Una función para realizar todas las instrucciones
|
||||||
|
function obtener() {
|
||||||
|
// Obtengo el numero de días y el tipo de vehículo
|
||||||
|
let dias=document.getElementById("dias").value;
|
||||||
|
let tipo=document.getElementById("tipo").value;
|
||||||
|
|
||||||
|
|
||||||
|
// Asigno el seguro a todo riesgo y el precio del tipo de coche
|
||||||
|
if (tipo === "basico") {
|
||||||
|
tipoP=45;
|
||||||
|
riesgo=15;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tipo === "gamamedia") {
|
||||||
|
tipoP=65;
|
||||||
|
riesgo=25;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tipo === "lujo") {
|
||||||
|
tipoP=85;
|
||||||
|
riesgo=35;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculo el coste del vehículo + seguro
|
||||||
|
let vehiculo;
|
||||||
|
if (document.getElementById("riesgo").checked) {
|
||||||
|
vehiculo=dias*(tipoP+riesgo);
|
||||||
|
} else {vehiculo=dias*(tipoP+10)}
|
||||||
|
|
||||||
|
|
||||||
|
//Condición silla y gps
|
||||||
|
let silla;
|
||||||
|
if (document.getElementById("silla").checked) {
|
||||||
|
silla=15;
|
||||||
|
} else { silla=0}
|
||||||
|
|
||||||
|
let gps;
|
||||||
|
if (document.getElementById("gps").checked) {
|
||||||
|
gps=5;
|
||||||
|
} else { gps=0}
|
||||||
|
|
||||||
|
//Calculo coste de los extras
|
||||||
|
let extras=(silla+gps)*dias;
|
||||||
|
|
||||||
|
//Calculo vehículo + extras con IVA
|
||||||
|
let total=vehiculo+extras;
|
||||||
|
let totalI=(total*1.21);
|
||||||
|
|
||||||
|
//Calculo el recargo por menor de 30
|
||||||
|
let precioMenor;
|
||||||
|
if (document.getElementById("menor").checked) {
|
||||||
|
precioMenor=totalI*0.3;
|
||||||
|
} else { precioMenor=0 }
|
||||||
|
|
||||||
|
// Calculo el total
|
||||||
|
let totalF=(totalI+precioMenor).toFixed(2);
|
||||||
|
document.getElementById("total").value=totalF;
|
||||||
|
|
||||||
|
// Mensaje alert
|
||||||
|
//Fecha del momento de la reserva
|
||||||
|
let hoy=new Date().getTime();
|
||||||
|
//Fecha para inico del alquiler
|
||||||
|
let inicio=document.getElementById("fecha").valueAsNumber;
|
||||||
|
// Calculo los días que faltan
|
||||||
|
let dif=inicio-hoy;
|
||||||
|
let diasF=dif/(1000*60*60*24);
|
||||||
|
// Calculo la fecha de entrega
|
||||||
|
let entrega=inicio+(dias*24*60*60*1000);
|
||||||
|
let entregaF=new Date(entrega);
|
||||||
|
// Obtengo la fecha de entrega en formato local dd-mm-xxxx
|
||||||
|
let entregaP=entregaF.toLocaleDateString();//.toLocaleDateString()
|
||||||
|
//alert("Faltan "+(Math.ceil(dias))+ " días"+"\n"+"Tu fecha de entrega es el "+entregaP);
|
||||||
|
|
||||||
|
//Creo el mensaje
|
||||||
|
let frase="Faltan "+(Math.ceil(diasF))+ " días "+"para tu alquiler"+"\n"
|
||||||
|
+"Tu fecha de de entrega del vehículo es el "+entregaP+"\n";
|
||||||
|
|
||||||
|
alert(frase);
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="container">
|
||||||
|
<form>
|
||||||
|
<h1>Alquiler de vehículo</h1>
|
||||||
|
<p>Introduzca número de dias de alquiler
|
||||||
|
<input type="number" name="dias" id="dias" size="3" value="0">
|
||||||
|
<p>Elige la fecha de inicio del alquiler<input type="date" id="fecha"></p>
|
||||||
|
<br>
|
||||||
|
<p>Seleccione el tipo de vehículo
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="tipo" id="tipo">
|
||||||
|
<option value="basico">Básico 45 Euros/día</option>
|
||||||
|
<option value="gamamedia">Gama media 65 Euros/día</option>
|
||||||
|
<option value="lujo">Lujo 85 Euros/día</option>
|
||||||
|
</select></p>
|
||||||
|
<h2>Elementos opcionales</h2>
|
||||||
|
<p>Silla Infantil * 15 Euros por día de alquiler<input type="checkbox" name="silla" id="silla" value="Silla Infantil"></p>
|
||||||
|
<p>GPS * 5 Euros por día de alquiler <input type="checkbox" name="gps" id="gps" value="Gps"></p>
|
||||||
|
<h2>Seguro</h2>
|
||||||
|
<p>** El seguro a terceros es obligatorio y tiene un coste de 10 Euros/día sin IVA</p>
|
||||||
|
<p>Seguro a todo riesgo <input type="checkbox" name="riesgo" id="riesgo" value="Has contratado seguro a todo riesgo"></p>
|
||||||
|
<p>Conductor menor de 30 años <input type="checkbox" name="menor" id="menor" value="Tienes recargo por ser menor de 30 años"></p>
|
||||||
|
<p>Coste total <input type="text" name="total" id="total" ></p>
|
||||||
|
|
||||||
|
<input type="button" value="Calcular coste total" onclick="obtener();">
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
Hacer una aplicación que calcule el coste de alquiler de un vehículo con las siguientes condiciones:
|
||||||
|
|
||||||
|
- Input para indicar los días de alquiler.
|
||||||
|
- Selector de fecha de inicio del alquiler.
|
||||||
|
|
||||||
|
- Tres tipos de vehículo
|
||||||
|
Básico (45 Euros por día de alquiler)
|
||||||
|
Gama media (65 Euros por día de alquiler)
|
||||||
|
Lujo (85 Euros por día de alquiler)
|
||||||
|
|
||||||
|
- Elementos opcionales
|
||||||
|
Silla Infantil(15 Euros por día de alquiler)
|
||||||
|
Gps(5 Euros por día de alquiler)
|
||||||
|
|
||||||
|
- Seguro a terceros (10 Euros día)(Obligatorio, se informa al cliente).
|
||||||
|
|
||||||
|
- Seguro a todo riesgo (Opcional)
|
||||||
|
Para Básico (15 Euros por día de alquiler)
|
||||||
|
Para Gama media (25 Euros por día de alquiler)
|
||||||
|
Para Lujo (35 Euros por día de alquiler)
|
||||||
|
|
||||||
|
- Conductor con menos de 30 años (recargo de 30% sobre el precio final con Iva)
|
||||||
|
|
||||||
|
|
||||||
|
Debemos dar el precio final con IVA
|
||||||
|
Y mediante alerta el siguiente mensaje:
|
||||||
|
Faltan 2 días para tu alquiler !
|
||||||
|
Tu fecha de de entrega del vehículo es el 27/1/2024 !
|
||||||
59
Practicas/Practicas JS/DOM Alquiler Coche/index.html
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<script src="./js/main.js"></script>
|
||||||
|
<title>Alquiler de coche</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div style="display: flex; flex-direction: column; min-width: max-content; gap: 4px;">
|
||||||
|
<div>
|
||||||
|
<label for="diasAlquiler">Dias de alquiler </label><input type="number" name="diasAlquiler" id="diasAlquiler">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="fechaInicio">Fecha de inicio del alquiler </label><input type="date" name="fechaInicio"
|
||||||
|
id="fechaInicio">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display: flex; gap: 2px;">
|
||||||
|
<label for="tipoVehiculo">Tipo de vehiculo</label>
|
||||||
|
<select name="tipoVehiculo" id="tipoVehiculo">
|
||||||
|
<option value='basico' selected>Basico (45€ dia)</option>
|
||||||
|
<option value='gama_media'>Gama media (65€ dia)</option>
|
||||||
|
<option value='lujo'>Lujo (85 dia)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="sillaInfantil" id="sillaInfantil">
|
||||||
|
<label for="sillaInfantil">Silla infantil (15€ dia)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="gps" id="gps">
|
||||||
|
<label for="gps">GPS (5€ dia)</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div>
|
||||||
|
<input type="radio" name="seguro" value="10" checked required> Seguro a terceros obligatorio si no se
|
||||||
|
contrata otro superior (10€ dia)
|
||||||
|
</div>
|
||||||
|
<input type="radio" name="seguro" value="0"> Todo riesgo (15€ para basico 25€ para gamam media 35€ para lujo)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<input type="checkbox" name="menor30" id="menor30" required>
|
||||||
|
<label for="menor30">Menor de 30 años (Recargo del 30% sobre el precio final)</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button onclick="calculaAlquiler()">Calcula total</button>
|
||||||
|
</div>
|
||||||
|
<span id="resultado"></span>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
88
Practicas/Practicas JS/DOM Alquiler Coche/js/main.js
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
function calculaAlquiler() {
|
||||||
|
const IVA = 1.21;
|
||||||
|
const resultado = document.getElementById("resultado");
|
||||||
|
const diasAlquiler = parseInt(document.getElementById("diasAlquiler").value);
|
||||||
|
const fechaInicio = new Date(document.getElementById("fechaInicio").value);
|
||||||
|
const diasHastaRecojer = diasDiferencia(fechaInicio);
|
||||||
|
|
||||||
|
//prettier-ignore
|
||||||
|
const eurXVehiculo = parseInt(eurXTipo(document.getElementById("tipoVehiculo").value));
|
||||||
|
//prettier-ignore
|
||||||
|
const sillaInfantil = document.getElementById("sillaInfantil").checked ? 15 : 0;
|
||||||
|
const gps = document.getElementById("gps").checked ? 5 : 0;
|
||||||
|
let seguro = parseInt(
|
||||||
|
document.querySelector('input[name="seguro"]:checked').value
|
||||||
|
);
|
||||||
|
if (seguro === 0) {
|
||||||
|
seguro = parseInt(
|
||||||
|
eurXSeguro(document.getElementById("tipoVehiculo").value)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const menor30 = document.getElementById("menor30").checked;
|
||||||
|
|
||||||
|
let pvpSinIva =
|
||||||
|
eurXVehiculo * diasAlquiler +
|
||||||
|
sillaInfantil * diasAlquiler +
|
||||||
|
gps * diasAlquiler +
|
||||||
|
seguro * diasAlquiler;
|
||||||
|
|
||||||
|
let pvpConIva = 0;
|
||||||
|
if (menor30 === true) {
|
||||||
|
pvpConIva = pvpSinIva * IVA * 1.3;
|
||||||
|
} else {
|
||||||
|
pvpConIva = pvpSinIva * IVA;
|
||||||
|
}
|
||||||
|
|
||||||
|
resultado.textContent = `El total final es: ${pvpConIva.toFixed(2)}€`;
|
||||||
|
|
||||||
|
alert(
|
||||||
|
`Faltan ${diasHastaRecojer} dias para tu alquiler! \n Tu fecha de entrega del vehículo es el ${formatFecha(
|
||||||
|
fechaInicio
|
||||||
|
)} `
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function eurXTipo(tipoVehiculo) {
|
||||||
|
let valor = 0;
|
||||||
|
switch (tipoVehiculo) {
|
||||||
|
case "basico":
|
||||||
|
valor = 45;
|
||||||
|
break;
|
||||||
|
case "gama_media":
|
||||||
|
valor = 65;
|
||||||
|
break;
|
||||||
|
case "lujo":
|
||||||
|
valor = 85;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return valor;
|
||||||
|
}
|
||||||
|
|
||||||
|
function eurXSeguro(tipoVehiculo) {
|
||||||
|
let valor = 0;
|
||||||
|
switch (tipoVehiculo) {
|
||||||
|
case "basico":
|
||||||
|
valor = 15;
|
||||||
|
break;
|
||||||
|
case "gama_media":
|
||||||
|
valor = 25;
|
||||||
|
break;
|
||||||
|
case "lujo":
|
||||||
|
valor = 35;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return valor;
|
||||||
|
}
|
||||||
|
|
||||||
|
function diasDiferencia(fechaFinal) {
|
||||||
|
const fechaActual = new Date();
|
||||||
|
return Math.ceil((fechaFinal - fechaActual) / (1000 * 60 * 60 * 24));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFecha(fecha) {
|
||||||
|
var dia = fecha.getDate();
|
||||||
|
var mes = fecha.getMonth() + 1;
|
||||||
|
var ano = fecha.getFullYear();
|
||||||
|
return `${dia}/${mes}/${ano}`;
|
||||||
|
}
|
||||||
BIN
Practicas/Practicas JS/Examen MF0491_3/MF0491_3.pdf
Normal file
283
Practicas/Practicas JS/Examen MF0491_3/index.html
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- ** ** -->
|
||||||
|
<!-- ** Examen práctico MF0491_3 ** -->
|
||||||
|
<!-- ** Alumno: Marcos López Gómez ** -->
|
||||||
|
<!-- ** ** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
|
||||||
|
<title>Examen MF0491_3</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
outline: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldset {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.4em;
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-right: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl>input,
|
||||||
|
.formControl>select {
|
||||||
|
height: 2rem;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
padding: 0.2rem;
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
background-color: transparent;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl>label {
|
||||||
|
font-size: 1em;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
legend {
|
||||||
|
padding: 0.2rem;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
background-color: transparent;
|
||||||
|
color: white;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
min-height: 2rem;
|
||||||
|
min-width: 2rem;
|
||||||
|
padding: 0.4em;
|
||||||
|
background-color: #0d6efd;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4em;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #0b5ed7;
|
||||||
|
}
|
||||||
|
|
||||||
|
#botonera {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="file"] {
|
||||||
|
width: min-content;
|
||||||
|
padding: 0.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 550px) {
|
||||||
|
#botonera {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="file"] {
|
||||||
|
width: 14rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="file"]::file-selector-button {
|
||||||
|
width: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<form id="formAlquiler"
|
||||||
|
style="display: flex; flex-direction: column; gap: 1em; min-width: min-content ;max-width: 600px; background-color: #9d2236; color:white; padding: 1em;">
|
||||||
|
<h1>Reserve su habitacion</h1>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Datos de la reserva</legend>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaEntrada">Fecha de entrada</label><input type="date" name="fechaEntrada"
|
||||||
|
id="fechaEntrada">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaSalida">Fecha de Salida</label><input type="date" name="fechaSalida"
|
||||||
|
id="fechaSalida">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoHabitacion">Tipo de habitación</label>
|
||||||
|
<select name="tipoHabitacion" id="tipoHabitacion">
|
||||||
|
<option value='simple' selected>Simple</option>
|
||||||
|
<option value='doble'>Doble</option>
|
||||||
|
<option value='triple'>Triple</option>
|
||||||
|
<option value='suite'>Suite</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoRegimen">Régimen de estancia</label>
|
||||||
|
<select name="tipoRegimen" id="tipoRegimen">
|
||||||
|
<option value='desayuno' selected>Desayuno</option>
|
||||||
|
<option value='media_pension'>Media pensión</option>
|
||||||
|
<option value='pension_completa'>Pensión Completa</option>
|
||||||
|
<option value='todo_incluido'>Todo Incluido</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="costeEst">Coste de la estancia (Habitación + Comidas)</label>
|
||||||
|
<input type="number" name="costeEst" id="costeEst" readonly>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasSpa">Acceso al Spa, días</label>
|
||||||
|
<input type="number" name="diasSpa" id="diasSpa">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasGuia">Servicio de Guía, días</label>
|
||||||
|
<input type="number" name="diasGuia" id="diasGuia">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="costeTotalIva">Coste total (IVA incluido)</label>
|
||||||
|
<input type="number" name="costeTotalIva" id="costeTotalIva" readonly>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</fieldset>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Datos personales</legend>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="nombre">* Nombre</label>
|
||||||
|
<input type="text" name="nombre" id="nombre" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="email">* Correo Electronico</label>
|
||||||
|
<input type="text" name="email" id="email" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="telf">* Telefono</label>
|
||||||
|
<input type="text" name="telf" id="telf" required>
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<span>Check-in online (Opcional)</span>
|
||||||
|
<label for="dni">* Adjunte fotocopia del DNI</label>
|
||||||
|
<input type="file" name="dni" id="dni">
|
||||||
|
</div>
|
||||||
|
<div id="botonera">
|
||||||
|
<div style="display: flex; flex-direction:column; gap: 0.4rem;">
|
||||||
|
<button type="button" onclick="calculaTotales()">Calcular coste Total</button>
|
||||||
|
<button type="button" onclick="limpiarForm()">Borrar</button>
|
||||||
|
<button type="button" onclick="enviarForm()">Enviar la reserva</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea id="resultado" rows="10"></textarea>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function calculaTotales() {
|
||||||
|
|
||||||
|
const TIPOSHABITACIONES = { simple: 50, doble: 80, triple: 120, suite: 150 };
|
||||||
|
const TIPOSREGIMEN = { desayuno: 50, media_pension: 80, pension_completa: 120, todo_incluido: 150 };
|
||||||
|
|
||||||
|
const getValue = (id) => parseFloat(document.querySelector(`#${id}`).value);
|
||||||
|
const setValue = (id, value) => document.querySelector(`#${id}`).value = parseFloat(value).toFixed(2);
|
||||||
|
|
||||||
|
const fechaini = document.getElementById('fechaEntrada').value;
|
||||||
|
const fechafin = document.getElementById('fechaSalida').value;
|
||||||
|
|
||||||
|
const nDias = difFechasDias(fechaini, fechafin);
|
||||||
|
|
||||||
|
const pvpTipoHabitacion = TIPOSHABITACIONES[document.querySelector('#tipoHabitacion').value];
|
||||||
|
const pvpTipoRegimen = TIPOSREGIMEN[document.querySelector('#tipoRegimen').value];
|
||||||
|
|
||||||
|
const descXDias = nDias <= 5 ? 0 : nDias <= 10 ? 0.15 : 0.25;
|
||||||
|
const costeEstancia = nDias * (pvpTipoHabitacion + pvpTipoRegimen) * (1 - descXDias);
|
||||||
|
|
||||||
|
const diasSpa = getValue('diasSpa');
|
||||||
|
const diasGuia = getValue('diasGuia');
|
||||||
|
|
||||||
|
const pvpDiasSpa = diasSpa <= 5 ? diasSpa * 30 : diasSpa * 20;
|
||||||
|
const pvpDiasGuia = diasGuia <= 7 ? diasGuia * 50 : diasGuia * 40;
|
||||||
|
|
||||||
|
const totalSinIva = costeEstancia + pvpDiasSpa + pvpDiasGuia;
|
||||||
|
const totalConIva = (totalSinIva * 1.21).toFixed(2);
|
||||||
|
|
||||||
|
setValue('costeEst', costeEstancia);
|
||||||
|
setValue('costeTotalIva', totalConIva);
|
||||||
|
|
||||||
|
generaResumen(nDias, totalSinIva);
|
||||||
|
}
|
||||||
|
|
||||||
|
function generaResumen(nDias, totalSinIva) {
|
||||||
|
const setValue = (id, value) => document.querySelector(`#${id}`).value = value;
|
||||||
|
|
||||||
|
const txtresultado = document.querySelector('#resultado');
|
||||||
|
const diaCheckin = new Date(document.querySelector('#fechaEntrada').value);
|
||||||
|
|
||||||
|
const diasFaltantes = difFechasDias(new Date(), diaCheckin);
|
||||||
|
const pvpAnulacion = (totalSinIva * 0.20).toFixed(2);
|
||||||
|
|
||||||
|
const fechaSalida = new Date(diaCheckin);
|
||||||
|
fechaSalida.setDate(fechaSalida.getDate() + parseInt(nDias));
|
||||||
|
|
||||||
|
const fechaAnulacion = new Date(diaCheckin);
|
||||||
|
fechaAnulacion.setDate(fechaAnulacion.getDate() - 3);
|
||||||
|
|
||||||
|
|
||||||
|
const nombre = document.querySelector('#nombre').value;
|
||||||
|
|
||||||
|
|
||||||
|
const mensaje = `Hola ${nombre}\n` +
|
||||||
|
`Faltan ${diasFaltantes} días para tu viaje\n` +
|
||||||
|
`Tu fecha de regreso es ${new Date(fechaSalida).toLocaleDateString()}\n` +
|
||||||
|
`Puedes anular tu reserva hasta el: ${new Date(fechaAnulacion).toLocaleDateString()}\n` +
|
||||||
|
`El coste de la anulación será ${pvpAnulacion} euros`;
|
||||||
|
|
||||||
|
setValue('resultado', mensaje);
|
||||||
|
}
|
||||||
|
|
||||||
|
const difFechasDias = (fechaIni, fechaFin) => Math.ceil((new Date(fechaFin) - new Date(fechaIni)) / (1000 * 60 * 60 * 24));
|
||||||
|
const limpiarForm = () => document.getElementById("formAlquiler").reset();
|
||||||
|
const enviarForm = () => document.getElementById("formAlquiler").submit();
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
<!-- Examen práctico UF1842 JAVASCRIPT -->
|
||||||
|
<!Doctype html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Examen práctico UF1842 JAVASCRIPT</title>
|
||||||
|
<style>
|
||||||
|
@charset "UTF-8";
|
||||||
|
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
form {
|
||||||
|
width: 80%;
|
||||||
|
min-width: 350px;
|
||||||
|
background-color: #9d2236;
|
||||||
|
border: 2px solid #000000;
|
||||||
|
padding: 10px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
color: white;
|
||||||
|
font-size: 18px;
|
||||||
|
margin: auto;
|
||||||
|
margin-top: 20px;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldset {
|
||||||
|
background-color: #9d2236;
|
||||||
|
border: 2px solid #ffffff;
|
||||||
|
padding: 10px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
#flex {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
margin-right: 10px;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
color: white;
|
||||||
|
background-color: #9d2236;
|
||||||
|
border: 2px solid white;
|
||||||
|
padding: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
legend {
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 20px;
|
||||||
|
margin: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
select,
|
||||||
|
option {
|
||||||
|
color: white;
|
||||||
|
background-color: #9d2236;
|
||||||
|
border: 2px solid white;
|
||||||
|
padding: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
background-color: #9d2236;
|
||||||
|
width: 100%;
|
||||||
|
height: 200px;
|
||||||
|
color: white;
|
||||||
|
border: 2px solid white;
|
||||||
|
padding: 10px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin-left: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type=submit],
|
||||||
|
input[type=button],
|
||||||
|
input[type=reset] {
|
||||||
|
background-color: #9d2236;
|
||||||
|
color: white;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: lighter;
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 5px;
|
||||||
|
border: 2px solid #000000;
|
||||||
|
border-radius: 5px;
|
||||||
|
box-shadow: 1px 2px 3px #fff;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Media query para pantallas de menos de 450 píxeles de ancho */
|
||||||
|
@media (max-width: 450px) {
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#flex {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
flex-direction: column-reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
margin-left: 0px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<script>
|
||||||
|
// Función obtener() que realizará la captación de datos,los cálculos y la escritura del mensaje de info
|
||||||
|
|
||||||
|
function obtener() {
|
||||||
|
// Declaro y obtengo el valor de las variables
|
||||||
|
const noches = document.getElementById("noches").value;
|
||||||
|
const habitacion = document.getElementById("habitacion").value;
|
||||||
|
const regimen = document.getElementById("regimen").value;
|
||||||
|
const spa = document.getElementById("spa").value;
|
||||||
|
const guia = document.getElementById("guia").value;
|
||||||
|
|
||||||
|
//Cáculo extras (spa y guia)
|
||||||
|
let spaT;
|
||||||
|
|
||||||
|
if (spa > 5) {
|
||||||
|
spaT = spa * 20;
|
||||||
|
} else {
|
||||||
|
spaT = spa * 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
let guiaT;
|
||||||
|
|
||||||
|
if (guia > 7) {
|
||||||
|
guiaT = guia * 40;
|
||||||
|
} else {
|
||||||
|
guiaT = guia * 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tipo habitación
|
||||||
|
let hotel;
|
||||||
|
if (habitacion === "simple") {
|
||||||
|
hotel = 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (habitacion === "doble") {
|
||||||
|
hotel = 80;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (habitacion === "triple") {
|
||||||
|
hotel = 120;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (habitacion === "suite") {
|
||||||
|
hotel = 150;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Tipo de regimen
|
||||||
|
let comidas;
|
||||||
|
if (regimen === "desayuno") {
|
||||||
|
comidas = 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (regimen === "mediapension") {
|
||||||
|
comidas = 80;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (regimen === "pensioncompleta") {
|
||||||
|
comidas = 120;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (regimen === "todoincluido") {
|
||||||
|
comidas = 150;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gastos estancia hotel+comidas
|
||||||
|
const hotelT = hotel * noches;
|
||||||
|
const regimenT = comidas * noches;
|
||||||
|
|
||||||
|
const estancia = hotelT + regimenT;
|
||||||
|
|
||||||
|
// Descuento por larga estancia
|
||||||
|
let estanciaDescuento;
|
||||||
|
if (noches <= 4) {
|
||||||
|
estanciaDescuento = estancia;
|
||||||
|
} else if (noches >= 5 && noches <= 10) {
|
||||||
|
estanciaDescuento = estancia * 0.85;
|
||||||
|
} else if (noches >= 11) {
|
||||||
|
estanciaDescuento = estancia * 0.75;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Envío el precio total sin IVA al formulario
|
||||||
|
document.getElementById("estancia").value = estanciaDescuento;
|
||||||
|
|
||||||
|
//Coste total con extras
|
||||||
|
const total = estanciaDescuento + spaT + guiaT;
|
||||||
|
const totalI = (total * 1.21).toFixed(2);
|
||||||
|
// Envío el precio con IVA al formulario
|
||||||
|
document.getElementById("total").value = totalI;
|
||||||
|
// Precio de anulación
|
||||||
|
const precioAnulacion = (total * 0.2).toFixed(2);
|
||||||
|
|
||||||
|
|
||||||
|
// Calcular días que faltan y fecha de regreso
|
||||||
|
const hoy = new Date().getTime();// Fecha de la reserva
|
||||||
|
const entrada = document.getElementById("fecha").valueAsNumber;
|
||||||
|
const dif = entrada - hoy;
|
||||||
|
const diasFaltan = dif / (1000 * 60 * 60 * 24);// Días que faltan
|
||||||
|
const regreso = entrada + (noches * 24 * 60 * 60 * 1000);//Fecha de regreso
|
||||||
|
const regresoF = new Date(regreso);// Obtener en UTC
|
||||||
|
const regresoP = regresoF.toLocaleDateString();//Pasar fecha a formato corto dd/mm/xxxx
|
||||||
|
|
||||||
|
const anulacion = entrada - (3 * 24 * 60 * 60 * 1000);//Fecha de anulación
|
||||||
|
const anulacionF = new Date(anulacion);
|
||||||
|
const anulacionP = anulacionF.toLocaleDateString();
|
||||||
|
//Mensaje de información
|
||||||
|
const frase = "Faltan " + (Math.ceil(diasFaltan)) + " días " + "para tu viaje" + "\n"
|
||||||
|
+ "Tu fecha de regreso es el " + regresoP + "\n"
|
||||||
|
+ "Puedes anular tu reserva hasta el día " + anulacionP + "\n"
|
||||||
|
+ "El coste de la anulación será de " + precioAnulacion + " euros";
|
||||||
|
//Enviar mensaje al formulario
|
||||||
|
document.getElementById("info").value = frase;
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
<link href="css/estilo.css" rel="stylesheet">
|
||||||
|
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<h1>Reserva tu habitación</h1>
|
||||||
|
<div id="container">
|
||||||
|
<form action="gracias.html" method="post">
|
||||||
|
<p>Introduzca número de noches de su estancia <input type="number" name="noches" id="noches" value="0"
|
||||||
|
size="3"></p>
|
||||||
|
<p>Seleccione el tipo de habitación
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="habitacion" id="habitacion">
|
||||||
|
<option value="simple" required>Simple</option>
|
||||||
|
<option value="doble">Doble</option>
|
||||||
|
<option value="triple">Triple</option>
|
||||||
|
<option value="suite">Suite</option>
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<p>Seleccione el regimen de alojamiento
|
||||||
|
<!-- Lista de selección -->
|
||||||
|
<select name="regimen" id="regimen">
|
||||||
|
<option value="desayuno" required>Desayuno</option>
|
||||||
|
<option value="mediapension">Media pensión</option>
|
||||||
|
<option value="pensioncompleta">Pensión Completa</option>
|
||||||
|
<option value="todoincluido">Todo Incluido</option>
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<br>
|
||||||
|
<p>Elige la fecha de entrada <input type="date" id="fecha"></p>
|
||||||
|
<br>
|
||||||
|
<p>Coste de la estancia (Habitación + Comidas) <input type="text" name="estancia" id="estancia"></p>
|
||||||
|
<p>Acceso al Spa, elija cuantos días <input type="number" name="spa" id="spa" value="0" size="3"></p>
|
||||||
|
|
||||||
|
<p>Servicio de guía turístico, elija cuantos días <input type="number" name="guia" id="guia" value="0"
|
||||||
|
size="3"></p>
|
||||||
|
<p>Coste total con IVA incluido <input type="text" name="total" id="total"></p>
|
||||||
|
|
||||||
|
<input type="button" value="Calcular coste total" onclick="obtener()"><input type="reset" name="limpiar"
|
||||||
|
value="Borrar" /><br>
|
||||||
|
<br>
|
||||||
|
<textarea name="info" id="info" rows="10" cols="60">Información de su viaje</textarea>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<br>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
BIN
Practicas/Practicas JS/Examen UF1842/Examen UF1842 Alumano04.pdf
Normal file
277
Practicas/Practicas JS/Examen UF1842/index optimizado.html
Normal file
@@ -0,0 +1,277 @@
|
|||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- ** ** -->
|
||||||
|
<!-- ** Examen práctico MF0491_3 ** -->
|
||||||
|
<!-- ** Alumno: Marcos López Gómez ** -->
|
||||||
|
<!-- ** ** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
|
||||||
|
<title>Examen MF0491_3</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
outline: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldset {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.4em;
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-right: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl>input,
|
||||||
|
.formControl>select {
|
||||||
|
height: 2rem;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
padding: 0.2rem;
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
background-color: transparent;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formControl>label {
|
||||||
|
font-size: 1em;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
legend {
|
||||||
|
padding: 0.2rem;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
background-color: transparent;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
min-height: 2rem;
|
||||||
|
min-width: 2rem;
|
||||||
|
padding: 0.4em;
|
||||||
|
background-color: #0d6efd;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4em;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #0b5ed7;
|
||||||
|
}
|
||||||
|
|
||||||
|
#botonera {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 550px) {
|
||||||
|
#botonera {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="file"] {
|
||||||
|
width: 14rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="file"]::file-selector-button {
|
||||||
|
width: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<form id="formAlquiler"
|
||||||
|
style="display: flex; flex-direction: column; gap: 1em; max-width: 600px; background-color: #9d2236; color:white; padding: 1em;">
|
||||||
|
<h1>Reserve su habitacion</h1>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Datos de la reserva</legend>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaEntrada">Fecha de entrada</label><input type="date" name="fechaEntrada"
|
||||||
|
id="fechaEntrada">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaSalida">Fecha de Salida</label><input type="date" name="fechaSalida"
|
||||||
|
id="fechaSalida">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoHabitacion">Tipo de habitación</label>
|
||||||
|
<select name="tipoHabitacion" id="tipoHabitacion">
|
||||||
|
<option value='simple' selected>Simple</option>
|
||||||
|
<option value='doble'>Doble</option>
|
||||||
|
<option value='triple'>Triple</option>
|
||||||
|
<option value='suite'>Suite</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoRegimen">Régimen de estancia</label>
|
||||||
|
<select name="tipoRegimen" id="tipoRegimen">
|
||||||
|
<option value='desayuno' selected>Desayuno</option>
|
||||||
|
<option value='media_pension'>Media pensión</option>
|
||||||
|
<option value='pension_completa'>Pensión Completa</option>
|
||||||
|
<option value='todo_incluido'>Todo Incluido</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="costeEst">Coste de la estancia (Habitación + Comidas)</label>
|
||||||
|
<input type="number" name="costeEst" id="costeEst" readonly>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasSpa">Acceso al Spa, días</label>
|
||||||
|
<input type="number" name="diasSpa" id="diasSpa">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasGuia">Servicio de Guía, días</label>
|
||||||
|
<input type="number" name="diasGuia" id="diasGuia">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="costeTotalIva">Coste total (IVA incluido)</label>
|
||||||
|
<input type="number" name="costeTotalIva" id="costeTotalIva" readonly>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</fieldset>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Datos personales</legend>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="nombre">* Nombre</label>
|
||||||
|
<input type="text" name="nombre" id="nombre" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="email">* Correo Electronico</label>
|
||||||
|
<input type="text" name="email" id="email" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="telf">* Telefono</label>
|
||||||
|
<input type="text" name="telf" id="telf" required>
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<span>Check-in online (Opcional)</span>
|
||||||
|
<label for="dni">* Adjunte fotocopia del DNI</label>
|
||||||
|
<input type="file" name="dni" id="dni">
|
||||||
|
</div>
|
||||||
|
<div id="botonera">
|
||||||
|
<div style="display: flex; flex-direction:column; gap: 0.4rem;">
|
||||||
|
<button type="button" onclick="calculaTotales()">Calcular coste Total</button>
|
||||||
|
<button type="button" onclick="limpiarForm()">Borrar</button>
|
||||||
|
<button type="button" onclick="enviarForm()">Enviar la reserva</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea id="resultado" rows="10"></textarea>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function calculaTotales() {
|
||||||
|
|
||||||
|
const TIPOSHABITACIONES = { simple: 50, doble: 80, triple: 120, suite: 150 };
|
||||||
|
const TIPOSREGIMEN = { desayuno: 50, media_pension: 80, pension_completa: 120, todo_incluido: 150 };
|
||||||
|
|
||||||
|
const getValue = (id) => parseFloat(document.querySelector(`#${id}`).value);
|
||||||
|
const setValue = (id, value) => document.querySelector(`#${id}`).value = parseFloat(value).toFixed(2);
|
||||||
|
|
||||||
|
const fechaini = document.getElementById('fechaEntrada').value;
|
||||||
|
const fechafin = document.getElementById('fechaSalida').value;
|
||||||
|
|
||||||
|
const nDias = difFechasDias(fechaini, fechafin);
|
||||||
|
|
||||||
|
const pvpTipoHabitacion = TIPOSHABITACIONES[document.querySelector('#tipoHabitacion').value];
|
||||||
|
const pvpTipoRegimen = TIPOSREGIMEN[document.querySelector('#tipoRegimen').value];
|
||||||
|
|
||||||
|
const descXDias = nDias <= 5 ? 0 : nDias <= 10 ? 0.15 : 0.25;
|
||||||
|
const costeEstancia = nDias * (pvpTipoHabitacion + pvpTipoRegimen) * (1 - descXDias);
|
||||||
|
|
||||||
|
const diasSpa = getValue('diasSpa');
|
||||||
|
const diasGuia = getValue('diasGuia');
|
||||||
|
|
||||||
|
const pvpDiasSpa = diasSpa <= 5 ? diasSpa * 30 : diasSpa * 20;
|
||||||
|
const pvpDiasGuia = diasGuia <= 7 ? diasGuia * 50 : diasGuia * 40;
|
||||||
|
|
||||||
|
const totalSinIva = costeEstancia + pvpDiasSpa + pvpDiasGuia;
|
||||||
|
const totalConIva = (totalSinIva * 1.21).toFixed(2);
|
||||||
|
|
||||||
|
setValue('costeEst', costeEstancia);
|
||||||
|
setValue('costeTotalIva', totalConIva);
|
||||||
|
|
||||||
|
generaResumen(nDias, totalSinIva);
|
||||||
|
}
|
||||||
|
|
||||||
|
function generaResumen(nDias, totalSinIva) {
|
||||||
|
const setValue = (id, value) => document.querySelector(`#${id}`).value = value;
|
||||||
|
|
||||||
|
const txtresultado = document.querySelector('#resultado');
|
||||||
|
const diaCheckin = new Date(document.querySelector('#fechaEntrada').value);
|
||||||
|
|
||||||
|
const diasFaltantes = difFechasDias(new Date(), diaCheckin);
|
||||||
|
const pvpAnulacion = (totalSinIva * 0.20).toFixed(2);
|
||||||
|
|
||||||
|
const fechaSalida = new Date(diaCheckin);
|
||||||
|
fechaSalida.setDate(fechaSalida.getDate() + parseInt(nDias));
|
||||||
|
|
||||||
|
const fechaAnulacion = new Date(diaCheckin);
|
||||||
|
fechaAnulacion.setDate(fechaAnulacion.getDate() - 3);
|
||||||
|
|
||||||
|
|
||||||
|
const nombre = document.querySelector('#nombre').value;
|
||||||
|
|
||||||
|
|
||||||
|
const mensaje = `Hola ${nombre}\n` +
|
||||||
|
`Faltan ${diasFaltantes} días para tu viaje\n` +
|
||||||
|
`Tu fecha de regreso es ${new Date(fechaSalida).toLocaleDateString()}\n` +
|
||||||
|
`Puedes anular tu reserva hasta el: ${new Date(fechaAnulacion).toLocaleDateString()}\n` +
|
||||||
|
`El coste de la anulación será ${pvpAnulacion} euros`;
|
||||||
|
|
||||||
|
setValue('resultado', mensaje);
|
||||||
|
}
|
||||||
|
|
||||||
|
const difFechasDias = (fechaIni, fechaFin) => Math.ceil((new Date(fechaFin) - new Date(fechaIni)) / (1000 * 60 * 60 * 24));
|
||||||
|
const limpiarForm = () => document.getElementById("formAlquiler").reset();
|
||||||
|
const enviarForm = () => document.getElementById("formAlquiler").submit();
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
210
Practicas/Practicas JS/Examen UF1842/index.html
Normal file
@@ -0,0 +1,210 @@
|
|||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- ** ** -->
|
||||||
|
<!-- ** Examen práctico UF1842 ** -->
|
||||||
|
<!-- ** Alumno: Marcos López Gómez ** -->
|
||||||
|
<!-- ** ** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
<!-- *********************************** -->
|
||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
|
||||||
|
<title>Examen UF1842</title>
|
||||||
|
<style>
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
text-decoration: none;
|
||||||
|
outline: none;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-family: 'Roboto', sans-serif;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
padding: 1em;
|
||||||
|
}
|
||||||
|
.formControl {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-right: 1rem;
|
||||||
|
}
|
||||||
|
.formControl>input,
|
||||||
|
.formControl>select {
|
||||||
|
height: 2rem;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
padding: 0.2rem;
|
||||||
|
border: 1px solid rgb(202, 207, 211);
|
||||||
|
border-radius: 0.3em;
|
||||||
|
background-color: white;
|
||||||
|
color: rgb(17, 17, 17);
|
||||||
|
}
|
||||||
|
.formControl>label {
|
||||||
|
font-size: 1em;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
min-height: 2rem;
|
||||||
|
min-width: 2rem;
|
||||||
|
padding: 0.4em;
|
||||||
|
background-color: #0d6efd;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0.4em;
|
||||||
|
color: white;
|
||||||
|
font-size: 1.2em;
|
||||||
|
}
|
||||||
|
button:hover {
|
||||||
|
background-color: #0b5ed7;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<form id="formAlquiler" style="display: flex; flex-direction: column; gap: 1em; max-width: 400px;">
|
||||||
|
<h1>Alquiler de habitacion</h1>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasAlquiler">Introduza el numero de noches de su estancia</label>
|
||||||
|
<input type="number" name="diasAlquiler" id="diasAlquiler">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoHabitacion">Tipo de habitacion</label>
|
||||||
|
<select name="tipoHabitacion" id="tipoHabitacion">
|
||||||
|
<option value='simple' selected>Simple</option>
|
||||||
|
<option value='doble'>Doble</option>
|
||||||
|
<option value='triple'>Triple</option>
|
||||||
|
<option value='suite'>Suite</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="tipoRegimen">Regimen de estancia</label>
|
||||||
|
<select name="tipoRegimen" id="tipoRegimen">
|
||||||
|
<option value='desayuno' selected>Desayuno</option>
|
||||||
|
<option value='media_pension'>Media pension</option>
|
||||||
|
<option value='pension_completa'>Pension Completa</option>
|
||||||
|
<option value='todo_incluido'>Todo Incluido</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="fechaEntrada">Fecha de entrada</label><input type="date" name="fechaEntrada"
|
||||||
|
id="fechaEntrada">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="costeEst">Coste de la estancia (Habitacion + Comidas)</label>
|
||||||
|
<input type="number" name="costeEst" id="costeEst" readonly>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasSpa">Acceso al Spa, días</label>
|
||||||
|
<input type="number" name="diasSpa" id="diasSpa">
|
||||||
|
</div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="diasGuia">Servicio de Guia, días</label>
|
||||||
|
<input type="number" name="diasGuia" id="diasGuia">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="formControl">
|
||||||
|
<label for="costeTotalIva">Coste total (Iva incluido)</label>
|
||||||
|
<input type="number" name="costeTotalIva" id="costeTotalIva" readonly>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button type="button" onclick="calculaTotales()">Calcular coste Total</button>
|
||||||
|
<button type="button" onclick="limpiarForm()">Borrar</button>
|
||||||
|
</div>
|
||||||
|
<textarea id="resultado" rows="10"></textarea>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
<script>
|
||||||
|
function calculaTotales() {
|
||||||
|
if (!datosCorrectos()) return;
|
||||||
|
const TIPOSHABITACIONES = ["simple", "doble", "triple", "suite"];
|
||||||
|
const TIPOSREGIMEN = ["desayuno", "media_pension", "pension_completa", "todo_incluido"];
|
||||||
|
|
||||||
|
let txtDiasAlquiler = document.getElementById('diasAlquiler');
|
||||||
|
let cboTipoHabitacion = document.getElementById('tipoHabitacion');
|
||||||
|
let cboTipoRegimen = document.getElementById('tipoRegimen');
|
||||||
|
let txtCosteTotalEstancia = document.getElementById('costeEst');
|
||||||
|
let txtCosteTotalIva = document.getElementById('costeTotalIva');
|
||||||
|
|
||||||
|
let nDias = parseInt(txtDiasAlquiler.value);
|
||||||
|
let pvpTipoHabitacion = parseInt(valorXopcion(cboTipoHabitacion.value, TIPOSHABITACIONES, [50, 80, 120, 150], 0))
|
||||||
|
let pvpTipoRegimen = parseInt(valorXopcion(cboTipoRegimen.value, TIPOSREGIMEN, [50, 80, 120, 150]))
|
||||||
|
|
||||||
|
let descXDias = nDias <= 5 ? 0 : nDias <= 10 ? parseFloat(0.15) : parseFloat(0.25)
|
||||||
|
let costeEstancia = (nDias * pvpTipoHabitacion) + (nDias * pvpTipoRegimen) - ((nDias * pvpTipoHabitacion) + (nDias * pvpTipoRegimen)) * descXDias
|
||||||
|
|
||||||
|
let diasSpa = parseInt(document.getElementById('diasSpa').value);
|
||||||
|
let diasGuia = parseInt(document.getElementById('diasGuia').value);
|
||||||
|
|
||||||
|
let pvpDiasSpa = diasSpa <= 5 ? diasSpa * 30 : diasSpa * 20;
|
||||||
|
let pvpDiasGuia = diasGuia <= 7 ? diasGuia * 50 : diasGuia * 40;
|
||||||
|
|
||||||
|
let totalSinIva = costeEstancia + pvpDiasSpa + pvpDiasGuia;
|
||||||
|
let totalConIva = parseFloat(totalSinIva * 1.21).toFixed(2);
|
||||||
|
|
||||||
|
txtCosteTotalEstancia.value = costeEstancia;
|
||||||
|
txtCosteTotalIva.value = totalConIva;
|
||||||
|
generaResumen(nDias, totalSinIva);
|
||||||
|
}
|
||||||
|
|
||||||
|
function datosCorrectos() {
|
||||||
|
let diasAlquiler = document.getElementById('diasAlquiler').value;
|
||||||
|
let diaCheckin = new Date(document.getElementById('fechaEntrada').value);
|
||||||
|
let diasSpa = parseInt(document.getElementById('diasSpa').value);
|
||||||
|
let diasGuia = parseInt(document.getElementById('diasGuia').value);
|
||||||
|
|
||||||
|
if (diasAlquiler <= 0 || isNaN(diasAlquiler)) { alert('El numero de dias de alquier debe ser superior a 0'); return 0; }
|
||||||
|
if (diasSpa < 0 || diasSpa > diasAlquiler || isNaN(diasSpa)) { alert('El acceso al Spa no puede ser menor que cero o ser superior a los dias de estancia'); return 0; }
|
||||||
|
if (diasGuia < 0 || diasGuia > diasAlquiler || isNaN(diasGuia)) { alert('El servicio de guia no puede ser menor que cero o ser superior a los dias de estancia'); return 0 }
|
||||||
|
if (diaCheckin.getTime() < new Date().getTime() || isNaN(diaCheckin.getTime())) { alert('La fecha de entrada no puede ser inferior a la actual'); return 0 }
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generaResumen(nDias, totalSinIva) {
|
||||||
|
let txtresultado = document.getElementById('resultado');
|
||||||
|
let diaCheckin = new Date(document.getElementById('fechaEntrada').value);
|
||||||
|
|
||||||
|
const diasFaltantes = difFechasDias(new Date(), diaCheckin);
|
||||||
|
const pvpAnulacion = parseFloat((totalSinIva) * 0.20);
|
||||||
|
|
||||||
|
let fechaSalida = new Date(diaCheckin);
|
||||||
|
fechaSalida.setDate(fechaSalida.getDate() + parseInt(nDias));
|
||||||
|
|
||||||
|
let fechaAnulacion = new Date(diaCheckin);
|
||||||
|
fechaAnulacion.setDate(fechaAnulacion.getDate() - 3);
|
||||||
|
|
||||||
|
let mensaje = `Faltan ${diasFaltantes} dias para tu viaje\n`
|
||||||
|
mensaje += `Tu fecha de regreso es ${new Date(fechaSalida).toLocaleDateString()}\n`
|
||||||
|
mensaje += `Puedes anular tu reserva hasta el: ${new Date(fechaAnulacion).toLocaleDateString()}\n`
|
||||||
|
mensaje += `El coste de la anulacion sera ${pvpAnulacion.toFixed(2)} euros`
|
||||||
|
|
||||||
|
txtresultado.value = mensaje
|
||||||
|
}
|
||||||
|
|
||||||
|
function difFechasDias(fechaIni, fechaFin) {
|
||||||
|
let dias = Math.ceil((new Date(fechaFin) - new Date(fechaIni)) / (1000 * 60 * 60 * 24));
|
||||||
|
return dias;
|
||||||
|
}
|
||||||
|
|
||||||
|
function valorXopcion(opc, opciones, valores, valorDefecto) {
|
||||||
|
const index = opciones.indexOf(opc);
|
||||||
|
return index !== -1 ? valores[index] : valorDefecto;
|
||||||
|
}
|
||||||
|
|
||||||
|
function limpiarForm() {
|
||||||
|
document.getElementById("formAlquiler").reset();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
117
Practicas/Practicas_PHP/POO/INTRO8_PHP_POO.php
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO8 POO EN PHP</title>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>POO EN PHP</h1>
|
||||||
|
<h2>Clases en POO</h2>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Definición de la clase
|
||||||
|
class Coche {
|
||||||
|
// Propiedades
|
||||||
|
public $marca;
|
||||||
|
public $modelo;
|
||||||
|
public $color;
|
||||||
|
|
||||||
|
// Método constructor
|
||||||
|
public function __construct($marca, $modelo, $color) {
|
||||||
|
$this->marca = $marca;
|
||||||
|
$this->modelo = $modelo;
|
||||||
|
$this->color = $color;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método para mostrar la información del coche
|
||||||
|
public function mostrarInformacion() {
|
||||||
|
echo "Marca: " . $this->marca . "<br>";
|
||||||
|
echo "Modelo: " . $this->modelo . "<br>";
|
||||||
|
echo "Color: " . $this->color . "<br>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creación de un objeto (instancia de la clase Coche)
|
||||||
|
$miCoche = new Coche("Toyota", "Corolla", "Rojo");
|
||||||
|
|
||||||
|
var_dump($miCoche);
|
||||||
|
$miCoche->marca = "Seat"; // Modificar una propiedad
|
||||||
|
var_dump($miCoche);
|
||||||
|
|
||||||
|
|
||||||
|
// Acceso a las propiedades del objeto y llamada a un método
|
||||||
|
echo "<h2>Información de mi coche:</h2>";
|
||||||
|
$miCoche->mostrarInformacion();
|
||||||
|
|
||||||
|
//Herencia
|
||||||
|
// Definición de la clase hija CocheDeportivo que hereda de Coche (Superclase y subclase)
|
||||||
|
class CocheDeportivo extends Coche {
|
||||||
|
// Propiedades adicionales para un coche deportivo
|
||||||
|
public $potencia;
|
||||||
|
public $aceleracion;
|
||||||
|
|
||||||
|
// Método constructor
|
||||||
|
public function __construct($marca, $modelo, $color, $potencia, $aceleracion) {
|
||||||
|
// Llamada al constructor de la clase padre
|
||||||
|
parent::__construct($marca, $modelo, $color);
|
||||||
|
// Asignación de las propiedades adicionales
|
||||||
|
$this->potencia = $potencia;
|
||||||
|
$this->aceleracion = $aceleracion;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Método para mostrar información específica de un coche deportivo
|
||||||
|
public function mostrarInformacionDeportiva() {
|
||||||
|
//parent::mostrarInformacion();
|
||||||
|
echo "Potencia: " . $this->potencia . "<br>";
|
||||||
|
echo "Aceleración: " . $this->aceleracion . "<br>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creación de un objeto CocheDeportivo
|
||||||
|
$miCocheDeportivo = new CocheDeportivo("Ferrari", "458 Italia", "Rojo", "570 CV", "3,4 segundos");
|
||||||
|
|
||||||
|
// Acceso a los métodos de la clase base y de la clase hija
|
||||||
|
echo "<h2>Información de mi coche deportivo:</h2>";
|
||||||
|
$miCocheDeportivo->mostrarInformacion(); // Método de la clase base
|
||||||
|
$miCocheDeportivo->mostrarInformacionDeportiva(); // Método de la clase hija
|
||||||
|
|
||||||
|
|
||||||
|
// Encapsulación
|
||||||
|
class Persona {
|
||||||
|
private $nombre;
|
||||||
|
private $edad;
|
||||||
|
|
||||||
|
public function __construct($nombre, $edad) {
|
||||||
|
$this->nombre = $nombre;
|
||||||
|
$this->edad = $edad;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getNombre() {
|
||||||
|
return $this->nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setNombre($nombre) {
|
||||||
|
$this->nombre = $nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getEdad() {
|
||||||
|
return $this->edad;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setEdad($edad) {
|
||||||
|
$this->edad = $edad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$persona = new Persona("Juan", 30);
|
||||||
|
|
||||||
|
//$persona->nombre = "Pedro";Acceso privado
|
||||||
|
//echo $persona->nombre; // Acceso privado
|
||||||
|
echo "Nombre: " . $persona->getNombre() . ", Edad: " . $persona->getEdad();
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
116
Practicas/Practicas_PHP/codigo/INTRO1_PHP_ARRAYS.php
Executable file
@@ -0,0 +1,116 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Intro1 PHP</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>Ubicación PHP</h2>
|
||||||
|
<?php
|
||||||
|
// El PHP puede ir:
|
||||||
|
// En una página dedicada(todo PHP)
|
||||||
|
// O incrustado en el Html(como en este ejemplo), se guarda como .php
|
||||||
|
echo 'Este texto está hecho en PHP';
|
||||||
|
echo '<br>';
|
||||||
|
?>
|
||||||
|
<h2>Echo PHP</h2>
|
||||||
|
<?php
|
||||||
|
//"echo" se utiliza para imprimir en pantalla
|
||||||
|
echo '<p>Y funciona perfecto!</p>';
|
||||||
|
//Para varias líneas . PHP_EOL .
|
||||||
|
echo '<p>En un lugar de la mancha,</p>' . '<p>de cuyo nombre no quiero acordarme...</p>';
|
||||||
|
echo '<p>En un lugar de la mancha,</p>' . '<p>de cuyo nombre no quiero acordarme...</p>';
|
||||||
|
// Concatenar con el "."
|
||||||
|
echo "John Lennon " . "y" . " Paul McCartney";
|
||||||
|
|
||||||
|
//Comentarios como en Javascript y tambien con #
|
||||||
|
//Esto es un comentario
|
||||||
|
echo "<p>Esto es una prueba</p>";
|
||||||
|
#Esto es un comentario
|
||||||
|
echo "Esto es otra prueba<br>";
|
||||||
|
/* Y este otro de varias
|
||||||
|
lineas*/
|
||||||
|
echo "Esto es la última prueba<br>";
|
||||||
|
|
||||||
|
?>
|
||||||
|
<h2>Variables en PHP</h2>
|
||||||
|
<?php
|
||||||
|
//Variables en PHP
|
||||||
|
//Tipado automático y dinámico
|
||||||
|
//NOMBRADO:No pueden empezar por números, se preceden de $, se distinguen mayúsculas y minúsculas, no espacios si guión bajo, evitar caractéres especiales.
|
||||||
|
$dato='Rojo';
|
||||||
|
//Constantes con mayusculas y precedidas de const, sin $
|
||||||
|
define("NOMBRE_CONSTANTE", "valor de la constante"); // Una forma
|
||||||
|
const GRAVEDAD=9.8;// Otra forma
|
||||||
|
echo GRAVEDAD; // Puede ser llamada sin $
|
||||||
|
echo '<br>';
|
||||||
|
//Los strings pueden ir entre comillas simples ' o comillas dobles ", se utilizan dobles cuando contiene una $variable
|
||||||
|
?>
|
||||||
|
<h2>Arrays en PHP</h2>
|
||||||
|
<?php
|
||||||
|
//Arrays
|
||||||
|
//Crear array
|
||||||
|
$semana = ['Lunes','Martes','Miércoles','Jueves','Viernes','Sábado','Domingo'];// Con corchetes
|
||||||
|
$colores = array("rojo", "verde", "azul"); // Función array
|
||||||
|
//var_dump para acceder a las características del array o de cualquier variable
|
||||||
|
var_dump($semana);
|
||||||
|
echo '<br>';
|
||||||
|
//
|
||||||
|
// Array de partida
|
||||||
|
$planetas = ['Marte', 'Tierra', 'Venus'];
|
||||||
|
//Anadir un elemento
|
||||||
|
$planetas[] = 'Alderaan';
|
||||||
|
// Añadimos elementos o arrays
|
||||||
|
//Elementos
|
||||||
|
array_push($planetas,'Ratuculín');
|
||||||
|
//Unir en un array nuevo
|
||||||
|
$nuevosPlanetas = array_merge($planetas, ['Mercurio']);
|
||||||
|
//Contar elementos del array
|
||||||
|
echo count($nuevosPlanetas);
|
||||||
|
echo '<br>';
|
||||||
|
//Modificar elementos
|
||||||
|
$planetas[2] = 'Saturno';
|
||||||
|
//Borrar
|
||||||
|
unset($planetas[1]);
|
||||||
|
var_dump($planetas);
|
||||||
|
echo '<br>';
|
||||||
|
echo count($planetas);
|
||||||
|
echo '<br>';
|
||||||
|
// Reindexar el array
|
||||||
|
$planetas=array_values($planetas);
|
||||||
|
var_dump($planetas);
|
||||||
|
echo '<br>';
|
||||||
|
echo count($planetas);
|
||||||
|
echo '<br>';
|
||||||
|
// Los strings se comportan como arrays
|
||||||
|
$palabra = 'abcdef';
|
||||||
|
echo $palabra[2]; // c
|
||||||
|
echo '<br>';
|
||||||
|
// Convertir un string a un array preg_split
|
||||||
|
//$array_resultante = preg_split(regExp, subject, limite)
|
||||||
|
$frase = 'En un lugar de la mancha';
|
||||||
|
$arrayDeFrase = preg_split('/[\s,]+/', $frase);
|
||||||
|
echo $arrayDeFrase[2];// "lugar"
|
||||||
|
echo '<br>';
|
||||||
|
//Diccionario o array asociativo, las claves (key) pueden ser definidas por nosotros
|
||||||
|
$empleados = ['Juan' => 34,'Luisa' => 56];
|
||||||
|
// Accedemos a un valor utilizando la clave
|
||||||
|
echo $empleados["Juan"]." ". "años" ;
|
||||||
|
echo '<br>';
|
||||||
|
//asort ordena de menor a mayor los valores
|
||||||
|
//arsort ordena de mayor a menor
|
||||||
|
arsort($empleados);
|
||||||
|
//ksort ordena por claves
|
||||||
|
ksort($empleados);
|
||||||
|
//ksort ordena por claves inversa
|
||||||
|
krsort($empleados);
|
||||||
|
var_dump($empleados);
|
||||||
|
echo '<br>';
|
||||||
|
// Recorrrer un array
|
||||||
|
foreach ($empleados as $clave => $valor) {
|
||||||
|
echo $clave . ": " . $valor . '<br>';
|
||||||
|
}
|
||||||
|
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
49
Practicas/Practicas_PHP/codigo/INTRO2_PHP_BUCLES.php
Executable file
@@ -0,0 +1,49 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Intro2 PHP</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Bucles</h1>
|
||||||
|
<?php
|
||||||
|
// foreach
|
||||||
|
$animalesFantasticos = ['fénix', 'dragón', 'grifo', 'pegaso', 'cerbero'];
|
||||||
|
foreach ($animalesFantasticos as $animal) {
|
||||||
|
echo $animal . ' ';
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
//si necesitamos la key
|
||||||
|
foreach ($animalesFantasticos as $posicion => $animal) {
|
||||||
|
echo "El animal $animal ocupa la posición $posicion";
|
||||||
|
echo '<br>';
|
||||||
|
}
|
||||||
|
//range crea un array entre un rango especificado
|
||||||
|
//range($inicio, $fin, $pasos);//Esquema
|
||||||
|
foreach (range(1, 5) as $num) {echo $num;};
|
||||||
|
|
||||||
|
//for
|
||||||
|
//Estructura for (variable inicio; condicional; incremento) {...}
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 0; $i < 10; $i++) {
|
||||||
|
echo $i;
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
//while
|
||||||
|
// Estructura while (condicional) {...}
|
||||||
|
$i = 1;
|
||||||
|
while ($i < 12) {
|
||||||
|
echo $i++;
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
//do-while
|
||||||
|
// Estructura do {...} while (condicional) una vez siempre
|
||||||
|
$i = 1;
|
||||||
|
do {
|
||||||
|
echo $i++;
|
||||||
|
} while ($i < 10);
|
||||||
|
echo '<br>';
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
84
Practicas/Practicas_PHP/codigo/INTRO3_PHP_CONDICIONALES.php
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Intro3 PHP</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Condicionales</h1>
|
||||||
|
<?php
|
||||||
|
//IF
|
||||||
|
// Estructura if (condición) {...}
|
||||||
|
/*Posibles condiciones
|
||||||
|
> es mayor que if (1 > 0)
|
||||||
|
< es menor que if (1 < 0)
|
||||||
|
&& y if (1 > 0 && 67 > 0)
|
||||||
|
|| o if (1 > 10 || 67 > 0)
|
||||||
|
! no if (!(1 > 0))
|
||||||
|
== es igual en valor if ('3' == 3)
|
||||||
|
=== es igual en valor y tipo if ('3' === '3')
|
||||||
|
!= no es igual if ('Doctor' != 'Who')
|
||||||
|
!== no es igual en valor o tipo if ('Doctor' !== 'Who')
|
||||||
|
>= es mayor o igual que if (10 >= 10)
|
||||||
|
<= es menor o igual que if (10 <= 20)
|
||||||
|
<=> -1, 0 y 1 dependiendo de los valores si son superados (10 <=> 20) // 1
|
||||||
|
True Verdad if (True)
|
||||||
|
False Falso if (False)
|
||||||
|
*/
|
||||||
|
if (10 > 2 && True && 'PACO' != 'PEDRO') {
|
||||||
|
echo 'Entro seguro';
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
//else
|
||||||
|
//if ('Ghibli' == 'Ghibli') {echo 'Bienvenido'} else {echo 'No eres bien recibido'}
|
||||||
|
if ('Ghibli' == 'Ghibli') {
|
||||||
|
echo 'Bienvenido';
|
||||||
|
} else {
|
||||||
|
echo 'No eres bien recibido';
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
//if (condición1) { ... } elseif (condición2){ ... } } else { ... }
|
||||||
|
//Operador ternario ? :
|
||||||
|
// SI SI NO
|
||||||
|
// (condicional) ? 'Valor si se cumple' : 'Valor si no se cumple';
|
||||||
|
/*Estructura <?php (condicional) ? 'Valor si se cumple' : 'Valor si no se cumple'; ?>*/
|
||||||
|
echo (5 > 10) ? 'Es verdad' : 'Es mentira';
|
||||||
|
echo '<br>';
|
||||||
|
//Switch
|
||||||
|
$num=2;
|
||||||
|
switch ($num) {
|
||||||
|
case 0:
|
||||||
|
echo "num es igual a 0";
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
echo "num es igual a 1";
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
echo "num es igual a 2";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
echo "No se a que es igual";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
//Condiciones con strings
|
||||||
|
//str_contains (¿Contiene este texto este otro texto?)
|
||||||
|
if (str_contains('La duda es uno de los nombres de la inteligencia', 'duda')) {
|
||||||
|
echo 'Si está contenido';
|
||||||
|
}
|
||||||
|
//str_starts_with (¿Empieza este texto con este otro texto?)
|
||||||
|
//str_end_with (¿Termina este texto con este otro texto?)
|
||||||
|
|
||||||
|
//Rand uso aleatorio
|
||||||
|
//rand( int $min , int $max )
|
||||||
|
|
||||||
|
echo '<br>';
|
||||||
|
echo rand(), "\n";
|
||||||
|
echo '<br>';
|
||||||
|
echo rand(), "\n";
|
||||||
|
echo '<br>';
|
||||||
|
echo rand(1,6), "\n";
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
127
Practicas/Practicas_PHP/codigo/INTRO3_PHP_FUNCIONES.php
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Intro3 PHP FUNCIONES</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Funciones en PHP</h1>
|
||||||
|
<form>
|
||||||
|
<?php
|
||||||
|
//--- Declarar
|
||||||
|
/*function nombre_de_funcion(tipo_de_parametro $parametros): tipo_return
|
||||||
|
{ ...
|
||||||
|
return ...;
|
||||||
|
}*/
|
||||||
|
//--- Llamar
|
||||||
|
//nombre_de_funcion($parametros);
|
||||||
|
//--- Estructura correcta
|
||||||
|
/**
|
||||||
|
* Función con educación
|
||||||
|
* @return {string}
|
||||||
|
*/
|
||||||
|
function saludar_ahora(): string
|
||||||
|
{
|
||||||
|
return 'Hola, soy una función';
|
||||||
|
}
|
||||||
|
echo saludar_ahora();
|
||||||
|
echo '<br>';
|
||||||
|
// Hola, soy una función
|
||||||
|
|
||||||
|
|
||||||
|
// --- Nuestros parámetros de entrada pueden tener un valor por defecto.
|
||||||
|
/**
|
||||||
|
* Saluda a una persona
|
||||||
|
* @param {string} - Nombre
|
||||||
|
* @return {string}
|
||||||
|
*/
|
||||||
|
function saludar(string $nombre = 'Anónimo'): string
|
||||||
|
{
|
||||||
|
return 'Hola, persona llamada ' . $nombre ;
|
||||||
|
}
|
||||||
|
echo saludar();
|
||||||
|
echo '<br>';
|
||||||
|
// Hola, persona llamada Anónimo.
|
||||||
|
echo saludar('Picasso');
|
||||||
|
echo '<br>';
|
||||||
|
// Hola, persona llamada Picasso.
|
||||||
|
|
||||||
|
//De forma automática PHP arreglará las incompatibilidades de tipos.
|
||||||
|
function incrementar(int $num): int
|
||||||
|
{
|
||||||
|
return $num + 1;
|
||||||
|
}
|
||||||
|
echo incrementar(4.5);
|
||||||
|
echo '<br>';
|
||||||
|
// 5
|
||||||
|
|
||||||
|
//Podemos declarar el modo estricto para que no admita errores de tipo
|
||||||
|
//declare(strict_types=1);
|
||||||
|
|
||||||
|
//Return con posibilidad de null
|
||||||
|
//function nombre(): ?string {...}
|
||||||
|
|
||||||
|
//Es posible indicar 2 tipos diferentes de parametros
|
||||||
|
//function nombre(): int|string
|
||||||
|
|
||||||
|
// -------------- Algunas funciones de arrays ------------
|
||||||
|
|
||||||
|
// Diccionario
|
||||||
|
$apartamentos = [
|
||||||
|
[
|
||||||
|
'precio/noche' => 40,
|
||||||
|
'ciudad' => 'Valencia',
|
||||||
|
'wifi' => True,
|
||||||
|
'pagina web' => 'https://hotel.com'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'precio/noche' => 87,
|
||||||
|
'ciudad' => 'Calpe',
|
||||||
|
'wifi' => True,
|
||||||
|
'pagina web' => 'https://calpe.com'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'precio/noche' => 67,
|
||||||
|
'ciudad' => 'Valencia',
|
||||||
|
'wifi' => False,
|
||||||
|
'pagina web' => 'https://denia.com'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'precio/noche' => 105,
|
||||||
|
'ciudad' => 'Benidorm',
|
||||||
|
'wifi' => False,
|
||||||
|
'pagina web' => 'https://benidorm.com'
|
||||||
|
]
|
||||||
|
];
|
||||||
|
//array_walk (Iterar) // Puede modificar el array original
|
||||||
|
array_walk($apartamentos, function ($apartamento, $posicion) {
|
||||||
|
echo $posicion+1 .' '. $apartamento['ciudad'] . '<br>';
|
||||||
|
});
|
||||||
|
|
||||||
|
/*
|
||||||
|
1 Valencia
|
||||||
|
2 Calpe
|
||||||
|
3 Valencia
|
||||||
|
4 Benidorm
|
||||||
|
*/
|
||||||
|
echo '<br>';
|
||||||
|
//array_filter (filtrar) // No modifica el original
|
||||||
|
$todosLosApartamentosValencia = array_filter($apartamentos, function ($apartamento) {
|
||||||
|
return $apartamento['ciudad'] === 'Valencia';
|
||||||
|
});
|
||||||
|
// Extraería los dos array con ciudad Valencia
|
||||||
|
|
||||||
|
//array_map (modificar)
|
||||||
|
$apartamentosMasBaratos = array_map(function ($apartamento) {
|
||||||
|
return array_merge($apartamento, ['precio/noche' => $apartamento['precio/noche'] - 1]);
|
||||||
|
}, $apartamentos);
|
||||||
|
// Le restará a todos los precio/noche
|
||||||
|
|
||||||
|
//array_reduce (calcular)
|
||||||
|
$media = array_reduce($apartamentos, function ($acumulador, $apartamento) {
|
||||||
|
return $apartamento['precio/noche'] + $acumulador;
|
||||||
|
}, 0) / count($apartamentos);
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
119
Practicas/Practicas_PHP/codigo/INTRO4_PHP_FECHAS.php
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Intro4 FECHAS PHP</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>FECHAS</h1>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Establecer la zona horaria a tu zona local
|
||||||
|
date_default_timezone_set('Europe/Madrid');
|
||||||
|
|
||||||
|
// Fecha UNIX a formato normal(ISO)
|
||||||
|
$origin_date = '1654560000'; // Fecha UNIX, podemos utilizar time() para obtenerla en segundos.
|
||||||
|
// Función date(formato,tiempo UNIX) obtiene un string con formato de fecha.
|
||||||
|
$iso_date = date('d-m-Y', intval($origin_date)); // intval(pasar a número) pasar a formato ISO la fecha
|
||||||
|
// new DateTime() crea un objeto de fecha, podemos pasarle un timestamp o una fecha(string)
|
||||||
|
$date = new DateTime($iso_date);
|
||||||
|
/*
|
||||||
|
METODO FORMAT
|
||||||
|
Y: Año con cuatro dígitos (por ejemplo, 2024).
|
||||||
|
y: Año con dos dígitos (por ejemplo, 24).
|
||||||
|
m: Mes con dos dígitos (por ejemplo, 02 para febrero).
|
||||||
|
d: Día del mes con dos dígitos (por ejemplo, 06).
|
||||||
|
w: Día de la semana (0 Domingo).
|
||||||
|
H: Hora en formato de 24 horas con dos dígitos (por ejemplo, 17 para las 5 p.m.).
|
||||||
|
i: Minutos con dos dígitos (por ejemplo, 30).
|
||||||
|
s: Segundos con dos dígitos (por ejemplo, 45).
|
||||||
|
Día de la semana: D (abreviatura de tres letras), l (nombre completo del día de la semana).
|
||||||
|
*/
|
||||||
|
echo $date->format('d/m/Y'); // 07/06/2022
|
||||||
|
echo '<br>';
|
||||||
|
// Obtener el día del mes
|
||||||
|
echo $date->format('d'); // 07
|
||||||
|
echo '<br>';
|
||||||
|
// Obtener el día del año
|
||||||
|
echo $date->format('z'); // 157
|
||||||
|
echo '<br>';
|
||||||
|
// Obtener el nombre del mes
|
||||||
|
echo $date->format('F'); // June
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
//strtotime
|
||||||
|
// Convertir una cadena de fecha y hora en un timestamp Unix
|
||||||
|
$timestamp_fecha_hora = strtotime('2022-12-25 18:30:00');
|
||||||
|
echo "Timestamp de 25 de diciembre de 2022 a las 18:30:00: $timestamp_fecha_hora\n";
|
||||||
|
echo '<br>';
|
||||||
|
// Manejo de cadenas relativas
|
||||||
|
$timestamp_manana = strtotime('tomorrow');
|
||||||
|
echo "Timestamp de mañana: $timestamp_manana\n";
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
echo date('d-m-Y', intval($timestamp_manana));
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
//Obtener la fecha y hora actual:
|
||||||
|
//Como objeto de fecha DateTime
|
||||||
|
$fechaActual = new DateTime();
|
||||||
|
echo $fechaActual->format('Y-m-d H:i:s');
|
||||||
|
echo '<br>';
|
||||||
|
var_dump($fechaActual);
|
||||||
|
echo '<br>';
|
||||||
|
// Solo fecha
|
||||||
|
echo $fechaActual->format('d-m-Y');
|
||||||
|
// Dia semana tres letras en inglés
|
||||||
|
echo '<br>';
|
||||||
|
echo $fechaActual->format('D');
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
// Pasar una fecha string a un objeto date
|
||||||
|
$fechaString = '2024-02-06';
|
||||||
|
$fechaX = new DateTime($fechaString);
|
||||||
|
echo $fechaX->format('d-m-Y');
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
// METODO MODIFY
|
||||||
|
// Sumar o restar días a una fecha:
|
||||||
|
$fechaZ = new DateTime('2024-02-06');
|
||||||
|
$fechaZ->modify('+10 days');
|
||||||
|
echo $fechaZ->format('Y-m-d');
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
// METODO DIFF // Objeto DateInterval
|
||||||
|
// Calcular la diferencia entre hoy y otra fecha
|
||||||
|
$fechaHoy = new DateTime();
|
||||||
|
var_dump($fechaHoy);
|
||||||
|
echo '<br>';
|
||||||
|
echo $fechaHoy->format('Y-m-d');
|
||||||
|
echo '<br>';
|
||||||
|
$fecha2 = new DateTime('2027-02-10');
|
||||||
|
$diferencia = $fechaHoy->diff($fecha2);// Objeto DateInterval
|
||||||
|
var_dump($diferencia);
|
||||||
|
echo '<br>';
|
||||||
|
echo $diferencia->days;// Días totales del intervalo
|
||||||
|
echo '<br>';
|
||||||
|
echo $diferencia->h;
|
||||||
|
echo '<br>';
|
||||||
|
echo "Faltan $diferencia->days días , $diferencia->h horas y $diferencia->i minutos";
|
||||||
|
echo '<br>';
|
||||||
|
// Convierte la diferencia en días con decimales
|
||||||
|
$diasDecimales = $diferencia->days + ($diferencia->h / 24) + ($diferencia->i / 1440);
|
||||||
|
echo ceil($diasDecimales);
|
||||||
|
echo '<br>';
|
||||||
|
// Calcula la diferencia total en minutos
|
||||||
|
$totalMinutos = ($diferencia->days * 24 * 60) + ($diferencia->h * 60) + $diferencia->i;
|
||||||
|
echo "$totalMinutos minutos";
|
||||||
|
echo '<br>';
|
||||||
|
echo $diasDiferencia = $diferencia->days;
|
||||||
|
// Y entre dos fechas
|
||||||
|
echo '<br>';
|
||||||
|
$fecha1X = new DateTime('2024-02-06'); // De 00:00:00 a 00:00:00
|
||||||
|
$fecha2X = new DateTime('2024-02-10');
|
||||||
|
$diferencia = $fecha1X->diff($fecha2X);
|
||||||
|
echo $diferencia->format('%R%a días');
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
79
Practicas/Practicas_PHP/codigo/INTRO5_PHP_FORMULARIOS_V1.php
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Intro5 PHP FORMULARIOS</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Formularios</h1>
|
||||||
|
<form action="" method="get">
|
||||||
|
<label for="nombre">Nombre:</label>
|
||||||
|
<input type="text" id="nombre" name="nombre"><br><br>
|
||||||
|
<label for="email">Email:</label>
|
||||||
|
<input type="email" id="email" name="email"><br><br>
|
||||||
|
<label for="telefono">Teléfono:</label>
|
||||||
|
<input type="text" id="telefono" name="telefono"><br><br>
|
||||||
|
<label for="nombre1">Nombre 1:</label>
|
||||||
|
<input type="text" id="nombre1" name="nombres[]"><br>
|
||||||
|
<label for="nombre2">Nombre 2:</label>
|
||||||
|
<input type="text" id="nombre2" name="nombres[]"><br>
|
||||||
|
<label for="nombre3">Nombre 3:</label>
|
||||||
|
<input type="text" id="nombre3" name="nombres[]"><br><br>
|
||||||
|
<input type="reset" value="Limpiar datos" /><br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
//En el formulario method indica como se envía la información(get y post)
|
||||||
|
//En el formulario action indica a donde se envía la información, si no indicamos nada va a la misma página
|
||||||
|
|
||||||
|
// Variables superglobales en PHP son variables predefinidas que están disponibles en todos los ámbitos (locales, globales, funciones, etc.)
|
||||||
|
|
||||||
|
//$_REQUEST es un array asociativo con los datos que llegan del formulario $_GET, $_POST y $_COOKIE
|
||||||
|
//var_dump($_REQUEST) para consultarlo
|
||||||
|
//
|
||||||
|
//Accedo al array para obtener el dato nombre
|
||||||
|
//echo $_REQUEST['nombre'];
|
||||||
|
//$_REQUEST su uso se desaconseja por seguridad
|
||||||
|
//$_GET datos enviados a través de la URL con el método GET name=>value --- key=>value
|
||||||
|
//$_POST datos enviados a través del cuerpo de la solicitud con el método POST
|
||||||
|
|
||||||
|
|
||||||
|
// Verificamos si el formulario fue enviado
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "GET") {
|
||||||
|
|
||||||
|
// Verificamos si se han enviado datos
|
||||||
|
if (isset($_GET["nombre"]) && isset($_GET["email"])) {
|
||||||
|
|
||||||
|
// Obtenemos los datos del formulario
|
||||||
|
$nombre = $_GET["nombre"];
|
||||||
|
$email = $_GET["email"];
|
||||||
|
var_dump($_REQUEST);
|
||||||
|
// Accedo a los datos
|
||||||
|
echo "<h2>Variables enviadas</h2>";
|
||||||
|
echo "Nombre: " . $nombre . "<br>";
|
||||||
|
echo "Email: " . $email . "<br>";
|
||||||
|
} else {
|
||||||
|
echo "Por favor, complete todos los campos del formulario.";
|
||||||
|
}
|
||||||
|
// Captar una variable con operador ternario
|
||||||
|
$telefono = isset($_GET['telefono']) ? $_GET['telefono'] : null;
|
||||||
|
}
|
||||||
|
//var_dump($_REQUEST);
|
||||||
|
echo "<br>";
|
||||||
|
echo $telefono;
|
||||||
|
echo "<br>";
|
||||||
|
// ---Usar campos para enviar arrays, debemos poner el mismo name
|
||||||
|
//<input type="text" id="nombre1" name="nombres[]">
|
||||||
|
$array_nombres = isset($_GET['nombres']) ? $_GET['nombres'] : [];
|
||||||
|
echo "<br>";
|
||||||
|
//var_dump($array_nombres);
|
||||||
|
echo "<br>";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO 5 FORMULARIOS PHP SUBIR ARCHIVOS</title>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1. SUBIR ARCHIVOS</h2>
|
||||||
|
<!-- Formulario -->
|
||||||
|
<form method="post" enctype="multipart/form-data">
|
||||||
|
<p>
|
||||||
|
<!-- Campo archivo -->
|
||||||
|
Adjuntar* <input type="file" name="fichero_usuario" required>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<!-- Campo archivo -->
|
||||||
|
Adjuntar* <input type="file" name="fichero_usuario2" required>
|
||||||
|
</p>
|
||||||
|
<!-- Campo archivo -->
|
||||||
|
<p>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<!-- Botón limpiar -->
|
||||||
|
<input type="reset" value="Limpiar">
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<!-- Botón submit -->
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Necesitaremos usar siempre el method POST y añadir enctype="multipart/form-data". Por último usar el input de tipo archivo (file).
|
||||||
|
// $_FILES variable superglobal, es un array multidimendional que recoge la informacion de los archivos subidos
|
||||||
|
|
||||||
|
//Acceso a los datos de cada fichero
|
||||||
|
//El nombre original del fichero en la máquina del cliente.
|
||||||
|
// $_FILES['fichero_usuario']['name']
|
||||||
|
|
||||||
|
//El tamaño, en bytes, del fichero subido.
|
||||||
|
//$_FILES['fichero_usuario']['size']
|
||||||
|
|
||||||
|
//El nombre temporal del fichero en el cual se almacena el fichero subido en el servidor.
|
||||||
|
//$_FILES['fichero_usuario']['tmp_name']
|
||||||
|
|
||||||
|
// Para realizar la gestión del archivo se utiliza:
|
||||||
|
//move_uploaded_file(ruta_archivo_temporal, ruta_destino)
|
||||||
|
|
||||||
|
|
||||||
|
// Verificar que hay archivos que subir
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["fichero_usuario"]) && isset($_FILES["fichero_usuario2"])) {
|
||||||
|
|
||||||
|
// Definir directorio donde se guardará
|
||||||
|
$dir_subida = 'uploads/';
|
||||||
|
|
||||||
|
//datos del arhivo
|
||||||
|
$nombre_archivo = $_FILES['fichero_usuario']['name']; // Nombre original archivo
|
||||||
|
$tipo_archivo = $_FILES['fichero_usuario']['type'];
|
||||||
|
$tamano_archivo = $_FILES['fichero_usuario']['size'];
|
||||||
|
$ruta_archivo_temporal= $_FILES['fichero_usuario']['tmp_name'];
|
||||||
|
$tamano_archivo2 = $_FILES['fichero_usuario2']['size'];
|
||||||
|
|
||||||
|
// Definir la ruta final del archivo
|
||||||
|
$ruta_destino = $dir_subida .$_FILES['fichero_usuario']['name'];
|
||||||
|
$ruta_destino2 = $dir_subida .$_FILES['fichero_usuario2']['name'];
|
||||||
|
//Variable llamada $_FILES
|
||||||
|
print_r($_FILES);
|
||||||
|
|
||||||
|
//Limitación de tamaño
|
||||||
|
$max_file_size=1000000;
|
||||||
|
|
||||||
|
if ($tamano_archivo<$max_file_size && $tamano_archivo2<$max_file_size) {
|
||||||
|
// Moverlo de la carpeta temporal a la definitiva, usando el método move_uploaded_file().
|
||||||
|
//move_uploaded_file($archivo_temporal, $ruta_destino)
|
||||||
|
move_uploaded_file($_FILES['fichero_usuario']['tmp_name'], $ruta_destino);
|
||||||
|
move_uploaded_file($_FILES['fichero_usuario2']['tmp_name'], $ruta_destino2);
|
||||||
|
echo "<p>Archivo subido correctamente</p>";
|
||||||
|
} else {echo "<p>Los archivos son demasido grandes</p>";}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Función pathinfo()
|
||||||
|
// $archivo='/ruta/del/archivo/nombre_archivo.txt';
|
||||||
|
//$extension = pathinfo($archivo, PATHINFO_EXTENSION);// 'txt'
|
||||||
|
//PATHINFO_DIRNAME: Devuelve el directorio padre del archivo.
|
||||||
|
//PATHINFO_BASENAME: Devuelve el nombre base del archivo, incluida la extensión.
|
||||||
|
//PATHINFO_EXTENSION: Devuelve la extensión del archivo.
|
||||||
|
//PATHINFO_FILENAME: Devuelve el nombre del archivo sin la extensión.
|
||||||
|
|
||||||
|
//Buscar elementos en un array
|
||||||
|
//in_array($elemento_buscado, $array)
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO6 PHP ESCRIBIR ARCHIVOS</title>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1. ESCRIBIR ARCHIVOS</h2>
|
||||||
|
<?php
|
||||||
|
// Manejo de archivos en PHP
|
||||||
|
|
||||||
|
//Verificar si existe un archivo
|
||||||
|
$nombre_fichero='escritura/prueba.txt';
|
||||||
|
|
||||||
|
if (file_exists($nombre_fichero)) {
|
||||||
|
echo "El fichero $nombre_fichero existe";
|
||||||
|
} else {
|
||||||
|
echo "El fichero $nombre_fichero no existe";
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
// Verificar si es editable
|
||||||
|
//is_writable()
|
||||||
|
|
||||||
|
|
||||||
|
//Abrir archivos fopen()
|
||||||
|
//Devuelvo 0 si no va, o coloca el puntero en una posición del archivo.
|
||||||
|
//$fp = fopen("miarchivo.txt", "r");
|
||||||
|
//Modo Descripción
|
||||||
|
//r Apertura para lectura. Puntero principio
|
||||||
|
//r+ Apertura para lectura y escritura. Puntero principio
|
||||||
|
//w Apertura para escritura. Puntero principio sobreescribe.No existe se intenta crear.
|
||||||
|
//w+ Apertura para lectura y escritura. Puntero principio sobreescribe. Si no existe se intenta crear.
|
||||||
|
//a Apertura para escritura. Puntero final. Si no existe se intenta crear.
|
||||||
|
//a+ Apertura para lectura y escritura. Puntero final. Si no existe se intenta crear.
|
||||||
|
//x Creación y apertura para sólo escritura. Puntero principio del archivo. Si el archivo ya existe dará error E_WARNING. Si no existe se intenta crear.
|
||||||
|
//x+ Creación y apertura para lectura y escritura.
|
||||||
|
//c Apertura para escritura. Si no existe se crea. Si existe no se sobreescribe ni da ningún error. Puntero principio.
|
||||||
|
//c+ Apertura para lectura y escritura. Mismo comportamiento que C.
|
||||||
|
|
||||||
|
|
||||||
|
//Abrir archivo con fopen()
|
||||||
|
$nombre_archivo = "escritura/letra.txt";
|
||||||
|
$conexion = fopen($nombre_archivo, "r");
|
||||||
|
echo '<br>';
|
||||||
|
if (!$conexion) { echo("Error abriendo archivo"); }
|
||||||
|
|
||||||
|
echo '<hr/>';
|
||||||
|
//Leer el archivo con fgets() o fread()
|
||||||
|
//fgets() lee solo una línea, se puede usar en bucles línea por línea
|
||||||
|
//fread() un tamaño de bytes
|
||||||
|
// Conocer tamaño de un archivo
|
||||||
|
//filesize($archivo)
|
||||||
|
//Ejemplo con fgets()
|
||||||
|
$tamanio_bufer =100; # bytes letras
|
||||||
|
$contenido=fread($conexion, $tamanio_bufer); // Nota: aquí podrías concatenar en una cadena, guardarlo por ahí, etcétera
|
||||||
|
echo "\nLeído: " .$contenido.'<br>';
|
||||||
|
|
||||||
|
// Cerrar archivo tras la lectura
|
||||||
|
fclose($conexion);
|
||||||
|
|
||||||
|
echo '<hr/>';
|
||||||
|
|
||||||
|
//Leer el contenido con file_get_contents()
|
||||||
|
//Lee todo el contenido no requiere fopen y fclose
|
||||||
|
// Obtener contenido de archivo como string
|
||||||
|
$todo_contenido = file_get_contents($nombre_archivo);
|
||||||
|
echo "El contenido es: " . "<pre>$todo_contenido</pre>";
|
||||||
|
|
||||||
|
echo '<hr/>';
|
||||||
|
|
||||||
|
|
||||||
|
//Escribir en archivos con php
|
||||||
|
//Método 1 fwrite()
|
||||||
|
$nombreArchivo = "escritura/hola.txt";
|
||||||
|
$archivo = fopen($nombreArchivo, "w");
|
||||||
|
//Con w lo crea si no existe y lo sobreescribe
|
||||||
|
fwrite($archivo, "Hola mundo azúl!"."\n"."Cómo va lo mío? ");
|
||||||
|
fclose($archivo);
|
||||||
|
|
||||||
|
//Metodo 2 file_put_contents()
|
||||||
|
//No requiere fopen y fclose, no sobrescribe
|
||||||
|
$nombreArchivo2 = "escritura/direccion.txt";
|
||||||
|
$datos = "New New York #456";
|
||||||
|
file_put_contents($nombreArchivo2, $datos ,FILE_APPEND | LOCK_EX);
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
<?php
|
||||||
|
//Abrir un directorio y obtener un identificador de directorio
|
||||||
|
//$conexion=opendir($ruta);
|
||||||
|
|
||||||
|
// Leer el directorio (lee tanto archivos como subdirectorios) va de uno en uno.
|
||||||
|
//readdir($conexion);
|
||||||
|
|
||||||
|
// Saber si es un archivo o un subdirectorio
|
||||||
|
//is_dir($ruta_archivo) Verifica si una ruta dada es un directorio.
|
||||||
|
//is_file($ruta_archivo) Verifica si una ruta dada es un archivo.
|
||||||
|
|
||||||
|
// Cerrar conexión
|
||||||
|
//closedir($conexion);
|
||||||
|
|
||||||
|
|
||||||
|
///// Otras operaciones con directorios
|
||||||
|
//rewinddir(): Reinicia el puntero del directorio al principio del directorio
|
||||||
|
//scandir(): Devuelve un array de nombres de archivos y subdirectorios
|
||||||
|
//mkdir($ruta_nuevo_directorio): Crea un nuevo directorio
|
||||||
|
//rmdir(): Elimina un directorio vacío.
|
||||||
|
//chdir(): Cambia el directorio actual a la ruta especificada.
|
||||||
|
//getcwd(): Devuelve el directorio de trabajo actual.
|
||||||
|
//realpath(): Devuelve la ruta real absoluta de un archivo o directorio
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
////Operaciones para la gestión de archivos
|
||||||
|
//file_exists() Comprueba si un archivo o directorio
|
||||||
|
//filesize() Obtiene el tamaño del archivo en bytes.
|
||||||
|
//rename() Cambia el nombre de un archivo o directorio.
|
||||||
|
//rename($viejo_nombre, $nuevo_nombre)
|
||||||
|
|
||||||
|
//unlink() Elimina un archivo.
|
||||||
|
|
||||||
|
//copy() Copia un archivo.
|
||||||
|
//copy($archivo_origen, $archivo_destino)
|
||||||
|
|
||||||
|
//Ejemplo
|
||||||
|
//echo getcwd();
|
||||||
|
//mkdir("prueba/");
|
||||||
|
//rmdir("prueba/");
|
||||||
|
//chdir("prueba/");
|
||||||
|
//echo getcwd();
|
||||||
|
//scandir();
|
||||||
|
//var_dump(scandir(.));
|
||||||
|
//echo realpath("prueba/");
|
||||||
|
//unlink("prueba_1.txt");
|
||||||
44
Practicas/Practicas_PHP/codigo/INTRO7_PHP_ENVIAR_CORREOS.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO7 PHP ENVIAR EMAIL</title>
|
||||||
|
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1. ENVIAR EMAIL</h2>
|
||||||
|
<?php
|
||||||
|
// Envío de mail en PHP
|
||||||
|
|
||||||
|
// Necesitamos un servidor SMTP (Postfix, Sendmail,Exim o Mercury Mail).
|
||||||
|
// Configuración del servidor SMTP (En UNISERVER MSMTP).
|
||||||
|
// Nosotros lo usaremos con la cuenta de Gmail del curso.
|
||||||
|
|
||||||
|
// Función mail()
|
||||||
|
//mail(dirección del destinatario, el asunto,cuerpo del mensaje, encabezados)
|
||||||
|
//Headers////////////"\r\n"
|
||||||
|
//Remitente $headers = 'From: miemail@example.com';
|
||||||
|
//Asunto $headers = 'Subject: Asunto del correo';
|
||||||
|
//Responder a $headers = 'Reply-To: responder@example.com';
|
||||||
|
//Con copia $headers = 'Cc: copia1@example.com, copia2@example.com';
|
||||||
|
//Con copia oculta $headers = 'Bcc: oculta1@example.com, oculta2@example.com';
|
||||||
|
//Cabecera tipo MIME $headers = "MIME-Version: 1.0" . "\r\n";
|
||||||
|
//Cabecera Tipo contenido para HTML $headers = "Content-type:text/html;charset=UTF-8" . "\r\n";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//Prueba de envío
|
||||||
|
$destinatario ="appasin12@gmail.com";
|
||||||
|
$asunto="Prueba correo desde PHP";
|
||||||
|
$mensaje="Esta es una prueba de envío de correo desde mi servidor PHP \r\n Y ha salido muy bien";
|
||||||
|
$headers='Bcc: otrocorreo@gmail.com'."\r\n".'Reply-To: appasin04@gmail.com'. "\r\n";
|
||||||
|
if (mail($destinatario,$asunto,$mensaje,$headers)) {
|
||||||
|
echo "Correo enviado";
|
||||||
|
} else { echo "No se ha podido enviar el correo";}
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
38
Practicas/Practicas_PHP/codigo/INTRO_PHP_HEADER.php
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
// La función header() permite enviar encabezados HTTP desde el servidor al cliente.
|
||||||
|
//Para que:
|
||||||
|
|
||||||
|
//- Tipo de Contenido (Content-Type): Especificar el tipo de contenido
|
||||||
|
header('Content-Type: text/html');
|
||||||
|
|
||||||
|
//- Redirecciones: Redirigir al usuario a otra página utilizando el encabezado Location.
|
||||||
|
header('Location: http://www.ejemplo.com/nueva_pagina.php');
|
||||||
|
|
||||||
|
//- Redirigir despues de un tiempo - header('Refresh: segundos; url=URL');
|
||||||
|
header('Refresh: 5; url=http://www.ejemplo.com/otra_pagina.php');
|
||||||
|
|
||||||
|
//-Control de Caché: Controlar cómo se almacenan en caché las páginas web.
|
||||||
|
header('Cache-Control: no-cache, no-store, must-revalidate');
|
||||||
|
|
||||||
|
//- Codificación (Content-Encoding): Especificar la codificación del contenido que se está enviando.
|
||||||
|
header('Content-Type: text/html; charset=utf-8');
|
||||||
|
|
||||||
|
//- Descarga de Archivos: Forzar la descarga de archivos adjuntos mediante encabezados específicos.
|
||||||
|
header('Content-Type: application/pdf');
|
||||||
|
header('Content-Disposition: attachment; filename="nombre_archivo.pdf"');
|
||||||
|
|
||||||
|
//- Control de Cookies: Configurar cookies para ser enviadas al cliente.
|
||||||
|
header('Set-Cookie: nombre=valor; expires=Fecha; path=Ruta; domain=Dominio', false);
|
||||||
|
|
||||||
|
/////Construir una URL que incluya parámetros GET (LOCATION,REFRESH)
|
||||||
|
|
||||||
|
$pagina = 'pagina.php';
|
||||||
|
$id = 123;
|
||||||
|
$nombre = 'Ejemplo';
|
||||||
|
|
||||||
|
$url = $pagina . '?id=' . urlencode($id) . '&nombre=' . urlencode($nombre);
|
||||||
|
echo $url;
|
||||||
|
|
||||||
|
//pagina.php?id=123&nombre=Ejemplo
|
||||||
|
|
||||||
|
?>
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
/***** Explicación *****/
|
||||||
|
// array_diff: Compara $claves_a_comprobar con $___SESSION y devuelve los valores de $claves_a_comprobar que no estén presentes en $___SESSION (si están todas, devuelve un array vacío)
|
||||||
|
// array_keys: Devuelve un array con todas las claves de array
|
||||||
|
|
||||||
|
// Comprobación básica => array_diff($claves_a_comprobar, array_keys($___SESSION)
|
||||||
|
// Forma 1 => array_diff($claves_a_comprobar, array_keys($___SESSION)) === []
|
||||||
|
// Forma 2 => empty(array_diff($claves_a_comprobar, array_keys($___SESSION)))
|
||||||
|
// Forma 3 => count(array_diff($claves_a_comprobar, array_keys($___SESSION))) === 0
|
||||||
|
|
||||||
|
/***** Ejemplo *****/
|
||||||
|
$___SESSION = [
|
||||||
|
'cero' => 0,
|
||||||
|
'uno' => '1',
|
||||||
|
'dos' => 'dos',
|
||||||
|
'tres' => 3,
|
||||||
|
'cuatro' => '4',
|
||||||
|
];
|
||||||
|
|
||||||
|
/*----- Caso 1: Todas las claves existen -----*/
|
||||||
|
$claves_a_comprobar = ['uno', 'dos', 'tres'];
|
||||||
|
|
||||||
|
// Forma 1
|
||||||
|
if(array_diff($claves_a_comprobar, array_keys($___SESSION)) === []) {
|
||||||
|
echo 'OK-[]' . PHP_EOL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
echo 'NOOOO-[]' . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forma 2
|
||||||
|
if(empty(array_diff($claves_a_comprobar, array_keys($___SESSION)))) {
|
||||||
|
echo 'OK-EMPTY' . PHP_EOL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
echo 'NOOOO-EMPTY' . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forma 3
|
||||||
|
if(count(array_diff($claves_a_comprobar, array_keys($___SESSION))) === 0) {
|
||||||
|
echo 'OK-COUNT' . PHP_EOL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
echo 'NOOOO-COUNT' . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*----- Caso 2: No existen todas las claves -----*/
|
||||||
|
$claves_a_comprobar = ['uno', 'two', 'tres'];
|
||||||
|
|
||||||
|
// Forma 1
|
||||||
|
if(array_diff($claves_a_comprobar, array_keys($___SESSION)) === []) {
|
||||||
|
echo 'OK-[]' . PHP_EOL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
echo 'NOOOO-[]' . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forma 2
|
||||||
|
if(empty(array_diff($claves_a_comprobar, array_keys($___SESSION)))) {
|
||||||
|
echo 'OK-EMPTY' . PHP_EOL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
echo 'NOOOO-EMPTY' . PHP_EOL;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forma 3
|
||||||
|
if(count(array_diff($claves_a_comprobar, array_keys($___SESSION))) === 0) {
|
||||||
|
echo 'OK-COUNT' . PHP_EOL;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
echo 'NOOOO-COUNT' . PHP_EOL;
|
||||||
|
}
|
||||||
21
Practicas/Practicas_PHP/codigo/cookies/INTRO_COOKIES_PHP.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// Mecanismo cookies
|
||||||
|
//1.Creación en el servidor
|
||||||
|
//2.Almacenamiento en el cliente
|
||||||
|
//3.Envío al servidor con cada solicitud Http
|
||||||
|
//4.Procesamiento en el servidor
|
||||||
|
//5.Actualización o eliminación
|
||||||
|
|
||||||
|
|
||||||
|
// Establecer cookies -- No estrán disponibles hasta la siguiente petición HTTP.
|
||||||
|
//setcookie($nombre, $valor = "", $vencimiento = 0, $ruta = "", $dominio = "", $seguro = false, $httponly = false)
|
||||||
|
//$vencimiento en tiempo UNIX si se establece en 0 se convierte en cookie de sesión.
|
||||||
|
//$ruta en la que estará disponible, por defecto directorio actual, si se establece '/' será valida para todo el dominio.
|
||||||
|
//$dominio en el que estará disponible, por defecto para el dominio actual.
|
||||||
|
//$seguro si se envía solo por https(true)
|
||||||
|
//$httponly si es accesible desde javascript (false)
|
||||||
|
setrawcookie("nombre", "Juan", time() + 3600, "/"); // Cookie con nombre "nombre" y valor "Juan", válida por una hora
|
||||||
|
setcookie("idioma", "es", time() + (86400 * 30), "/"); // Cookie con nombre "idioma" y valor "es", válida por 30 días
|
||||||
|
setcookie("ultima_visita", date("Y-m-d H:i:s"), time() + 3600, "/"); // Cookie con nombre "ultima_visita" y valor de la fecha y hora actual, válida por una hora
|
||||||
|
?>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
// Acceder a las cookies desde otra página
|
||||||
|
|
||||||
|
|
||||||
|
// Leer cookies
|
||||||
|
$nombre = $_COOKIE['nombre'];
|
||||||
|
$idioma = $_COOKIE['idioma'];
|
||||||
|
$ultimaVisita = $_COOKIE['ultima_visita'];
|
||||||
|
|
||||||
|
var_dump($_COOKIE);
|
||||||
|
|
||||||
|
// Mostrar valores de las cookies
|
||||||
|
echo "Hola, $nombre. ";
|
||||||
|
echo "Tu idioma preferido es $idioma. ";
|
||||||
|
echo "Tu última visita fue el $ultimaVisita.";
|
||||||
|
?>
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
// Sesiones en PHP
|
||||||
|
//Pasos uso de sesiones en PHP
|
||||||
|
/*
|
||||||
|
1. Identificación de sesión: se le asigna un identificador y se guarda en una cookie del navegador.
|
||||||
|
|
||||||
|
2. Almacenamiento de datos de sesión: variable superglobal $_SESSION se utiliza para acceder y modificar estos datos.
|
||||||
|
|
||||||
|
3. Inicio y cierre de sesión: Inicio de sesión session_start(). Esto inicializa o reanuda una sesión existente.
|
||||||
|
Una vez que la sesión ha comenzado, se pueden guardar y recuperar datos utilizando la superglobal $_SESSION.
|
||||||
|
Finalizar una sesión, se utiliza session_destroy(), elimina todos los datos y destruye la sesión.
|
||||||
|
|
||||||
|
4. Configuración de sesiones: configuración php.ini o mediante funciones como session_set_cookie_params().
|
||||||
|
*/
|
||||||
|
|
||||||
|
//Crear una Sesión
|
||||||
|
session_start(); // Lo primero que debe aparecer en la página
|
||||||
|
// Definir Variables
|
||||||
|
$_SESSION['nombre'] = 'Juan';
|
||||||
|
$_SESSION['apellido'] = 'Perez';
|
||||||
|
// Modificar variables
|
||||||
|
$_SESSION['apellido'] = 'Porto';
|
||||||
|
// Consultar la sesión
|
||||||
|
echo '<br>';
|
||||||
|
var_dump($_SESSION);
|
||||||
|
// Añadir variables
|
||||||
|
$_SESSION['apodo'] = 'Totoki';
|
||||||
|
// ID de sesión la indentifica
|
||||||
|
echo '<br>';
|
||||||
|
echo session_id();
|
||||||
|
echo '<br>';
|
||||||
|
var_dump($_SESSION);
|
||||||
|
// Destruir la sesión
|
||||||
|
//$_SESSION = []; // Borra las variables pero la sesión sigue activa
|
||||||
|
//session_destroy() // Finaliza la sesión y borra los datos
|
||||||
|
echo '<br>';
|
||||||
|
//var_dump($_SESSION);
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO8 PHP SESIONES</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<a href="INTRO8_PHP_SESIONES2.php">Continuar sesión</a>
|
||||||
|
<a href="destruir_sesion.php">Cerrar sesión</a>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO8 PHP SESIONES2</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
|
||||||
|
//Conectar a una Sesión
|
||||||
|
session_start();
|
||||||
|
|
||||||
|
//Añadimos una variable
|
||||||
|
$_SESSION['edad'] = '30';
|
||||||
|
// Accedo a datos de la sesión
|
||||||
|
echo $_SESSION['nombre'];
|
||||||
|
echo '<br>';
|
||||||
|
echo $_SESSION['apellido'];
|
||||||
|
echo '<br>';
|
||||||
|
echo $_SESSION['apodo'];
|
||||||
|
echo '<br>';
|
||||||
|
echo $_SESSION['edad'];
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>INTRO8 PHP SESIONES3</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Sesiones en PHP
|
||||||
|
// Nombrar la sesión o consultar su nombre , por defecto(PHPSESSID)
|
||||||
|
session_name("ejemplo1");// Se debe usar antes de iniciar la sesión
|
||||||
|
echo session_name();//Consultar nombre de sesión
|
||||||
|
//Parametros de la cookie de sesión
|
||||||
|
//session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
|
||||||
|
session_set_cookie_params(
|
||||||
|
0,//Tiempo de vida de la cookie de sesión, definido en segundos.
|
||||||
|
'/',//Ruta en el servidor donde la cookie trabajará.
|
||||||
|
'www.php.net',//Dominio de la cookie, por ejemplo 'www.php.net'.
|
||||||
|
false,//Si es true la cookie sólo será enviada sobre conexiones seguras.
|
||||||
|
false // Si es false puede ser accesible por javascript.
|
||||||
|
);
|
||||||
|
session_start();//Inicio la sesión
|
||||||
|
// Para consultar los parametros de la cookie de sesión
|
||||||
|
var_dump(session_get_cookie_params());
|
||||||
|
//Borrar todos los valores de $_SESSION
|
||||||
|
//session_unset();
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
44
Practicas/Practicas_PHP/codigo/sesiones/login.php
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<form method="post">
|
||||||
|
<p>
|
||||||
|
<input type="text" name="usuario" placeholder="Usuario">
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<input type="password" name="contraseña" placeholder="Contraseña">
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<input type="submit" value="Entrar">
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Comprobamos que nos llega los datos del formulario
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
|
||||||
|
|
||||||
|
// Variables que teóricamente estarían en una base de datos o en un archivo
|
||||||
|
$usuarioBueno = 'flecha';
|
||||||
|
$contraseñaBuena = '5454';
|
||||||
|
|
||||||
|
// Variables del formulario
|
||||||
|
$usuario = isset($_POST['usuario']) ? $_POST['usuario'] : null;
|
||||||
|
$contraseña = isset($_POST['contraseña']) ? $_POST['contraseña'] : null;
|
||||||
|
|
||||||
|
// Comprobamos si los datos son correctos
|
||||||
|
if ($usuarioBueno === $usuario && $contraseñaBuena === $contraseña) {
|
||||||
|
// Si son correctos, creamos la sesión
|
||||||
|
session_start();
|
||||||
|
$_SESSION['usuario'] = $_POST['usuario'];
|
||||||
|
// Redireccionamos a la página personalizada
|
||||||
|
header('Location: perfil.php');
|
||||||
|
die();
|
||||||
|
} else {
|
||||||
|
// Si no son correctos, informamos al usuario
|
||||||
|
echo '<p style="color: red">El apodo o la contraseña es incorrecta.</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
9
Practicas/Practicas_PHP/codigo/sesiones/logout.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
// Iniciamos las sesiones
|
||||||
|
session_start();
|
||||||
|
// Destruimos las sesiones
|
||||||
|
session_destroy();
|
||||||
|
// Llevamos a login.php
|
||||||
|
header('Location: login.php');
|
||||||
|
// Cortamos el script
|
||||||
|
die();
|
||||||
18
Practicas/Practicas_PHP/codigo/sesiones/perfil.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
// Comprobamos si existe la sesión de apodo
|
||||||
|
session_start();
|
||||||
|
if (!isset($_SESSION['usuario'])) {
|
||||||
|
// En caso contrario devolvemos a la página login.php
|
||||||
|
header('Location: login.php');
|
||||||
|
die();
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<!-- Saludamos -->
|
||||||
|
<h1>Bienvenido <?php echo $_SESSION['usuario']; ?></h1>
|
||||||
|
<!-- Botón para cerrar la sesión -->
|
||||||
|
<a href="logout.php">Cerrar sesión</a>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
80
Practicas/Practicas_PHP/ejercicios/EJERCICIO1_PHP.php
Executable file
@@ -0,0 +1,80 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>EJERCICIO1 PHP</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<h2>1.</h2>
|
||||||
|
<?php
|
||||||
|
//1. Asigna este texto (Hoy, es un buen día para aprender a programar en PHP.) a una variable llamada: $texto, y haz que se imprima en pantalla.
|
||||||
|
$texto = 'Hoy, es un buen día para aprender a programar en PHP.';
|
||||||
|
echo $texto; ?>
|
||||||
|
<h2>2.</h2>
|
||||||
|
<?php
|
||||||
|
//2. Crea dos variables una para tu nombre y otra para tu edad, y haz que salga en pantalla la frase " Soy Juan y tengo 33 años".
|
||||||
|
$nombre = 'Paco';
|
||||||
|
$edad = 33;
|
||||||
|
echo 'Soy ' . $nombre . ' y tengo ' . $edad . ' años';
|
||||||
|
echo '<br>';
|
||||||
|
echo "Soy $nombre y tengo $edad años";
|
||||||
|
?>
|
||||||
|
<h2>3.</h2>
|
||||||
|
<?php
|
||||||
|
//3. Crea una función que calcule el area de una esfera, y aplicala para un radio de 10 metros y para un radio de 4 metros. Saca las respuestas por pantalla.
|
||||||
|
$radio;
|
||||||
|
const PI = 3.1416;
|
||||||
|
function areaEsfera($radio)
|
||||||
|
{
|
||||||
|
return 4 * PI * $radio ** 2;
|
||||||
|
}
|
||||||
|
echo 'El área de una esfera de 10 metros de radio es ' . round(areaEsfera(10), 2) . ' metros cuadrados.';
|
||||||
|
echo '<br>';
|
||||||
|
echo 'El área de una esfera de 4 metros de radio es ' . round(areaEsfera(4), 2) . ' metros cuadrados.';
|
||||||
|
?>
|
||||||
|
<h2>4.</h2>
|
||||||
|
<?php
|
||||||
|
//4. Debemos escribir esta frase en pantalla: Las siglas de HTML significan "HyperText Markup language".
|
||||||
|
$frase = "Las siglas de HTML significan \"HyperText Markup language\"";
|
||||||
|
echo 'Las siglas de HTML significan "HyperText Markup language"';
|
||||||
|
echo '<br>';
|
||||||
|
echo $frase;
|
||||||
|
?>
|
||||||
|
<h2>5.</h2>
|
||||||
|
<?php
|
||||||
|
//5. Concatena estos tres colores guardados en variables para formar una frase como esta: "Los colores guardados en las variables son rojo, azul y verde."
|
||||||
|
$rojo = 'rojo';
|
||||||
|
$azul = 'azul';
|
||||||
|
$verde = 'verde';
|
||||||
|
echo "Los colores guardados en las variables son $rojo, $azul y $verde.";
|
||||||
|
?>
|
||||||
|
<h2>6.</h2>
|
||||||
|
<?php
|
||||||
|
/*Se ha convocado un concurso de micro relatos sobre personas estrañas. El límite de palabras para ser enviadas son de 20.
|
||||||
|
- Crea una variable con el micro relato.
|
||||||
|
- Muestra el número de palabras usando preg_split y count.*/
|
||||||
|
$micro = 'Un desconocido de baja estatura apareció en la noche cautivando a todos con sus extraños ojos nacarados brillando como diamantes';
|
||||||
|
$arrayMicro = preg_split('/[\s,]+/', $micro);
|
||||||
|
echo count($arrayMicro);
|
||||||
|
str_word_count($micro);
|
||||||
|
?>
|
||||||
|
<h2>7.</h2>
|
||||||
|
<?php
|
||||||
|
/*7. Crea un diccionario con el censo de población de: España, Portugal, Francia, Italia y Grecia. Ayudate de Wikipedia.
|
||||||
|
- Ordenalos con arsort de mayor a menor.*/
|
||||||
|
$paises = ['España' => 47435597, 'Portugal' => 10352042, 'Francia' => 67407241, 'Italia' => 59853482, 'Grecia' => 11086406];
|
||||||
|
arsort($paises);
|
||||||
|
var_dump($paises);
|
||||||
|
echo '<br>';
|
||||||
|
echo '<ol>';
|
||||||
|
foreach ($paises as $key => $val) {
|
||||||
|
echo "<li>$key = $val </li>";
|
||||||
|
}
|
||||||
|
echo '</ol>';
|
||||||
|
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
112
Practicas/Practicas_PHP/ejercicios/EJERCICIO2_PHP.php
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>EJERCICIO2 PHP</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1.</h2>
|
||||||
|
<?php
|
||||||
|
/*
|
||||||
|
1.Guarda en un array tus 6 películas favoritas.
|
||||||
|
-Imprime en párrafos con el siguiente formato: ‘Película: Los Vengadores’
|
||||||
|
-Añade la posición de la película a la lista: ‘Película 4: Godzilla’
|
||||||
|
-Despues imprime en lugar de párrafos… ¡una lista!
|
||||||
|
*/
|
||||||
|
$peliculas=['Amancord','Pulp Fiction','El padrino','Uno de los nuestros','Memento','Cadena perpetua'];
|
||||||
|
foreach ($peliculas as $nombreP) {
|
||||||
|
echo "<p>Película : $nombreP<p>";
|
||||||
|
};
|
||||||
|
echo '<br>';
|
||||||
|
foreach ($peliculas as $posicion=>$nombreP) {
|
||||||
|
$posicion=$posicion+1;
|
||||||
|
echo "<p>Película $posicion: $nombreP</p>";
|
||||||
|
};
|
||||||
|
echo '<br>';
|
||||||
|
echo '<ul>';
|
||||||
|
foreach ($peliculas as $posicion=>$nombreP) {
|
||||||
|
$posicion=$posicion+1;
|
||||||
|
echo "<li>Película $posicion: $nombreP</li>";
|
||||||
|
};
|
||||||
|
echo '</ul>';
|
||||||
|
?>
|
||||||
|
<h2>2.</h2>
|
||||||
|
<?php
|
||||||
|
/*2.Utilizando bucles:
|
||||||
|
|
||||||
|
*/
|
||||||
|
//Imprime los números del 1 al 10.
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 1; $i < 10; $i++) {
|
||||||
|
echo "$i, ";
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
//Imprime los números de 60 al 70.
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 60; $i < 70; $i++) {
|
||||||
|
echo "$i, ";
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
//Imprime los números del 20 al 1.
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 20; $i >1; $i--) {
|
||||||
|
echo "$i, ";
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
//Imprime los números del 1 al 1000
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 1; $i < 1000; $i++) {
|
||||||
|
echo "$i, ";
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
//Imprime la tabla del 5.
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 1; $i < 11; $i++) {
|
||||||
|
echo "5 x $i = ";
|
||||||
|
echo 5*$i;
|
||||||
|
echo '<br>';
|
||||||
|
}
|
||||||
|
//Imprimir los números pares que hay dentro de los 100 primeros números enteros.
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 0; $i < 100; $i=$i+2) {
|
||||||
|
echo "$i, ";
|
||||||
|
}
|
||||||
|
echo $i;
|
||||||
|
echo '<br>';
|
||||||
|
//Escribe un script PHP que muestre los números del 1 al 10 en una tabla de una fila y 10 columnas. Utiliza un bucle while
|
||||||
|
echo '<table border="2">';
|
||||||
|
echo '<tr>';
|
||||||
|
$i=0;
|
||||||
|
while ($i<10) {
|
||||||
|
$i++;
|
||||||
|
echo "<td>$i</td>";
|
||||||
|
}
|
||||||
|
echo '</tr>';
|
||||||
|
echo '</table>';
|
||||||
|
?>
|
||||||
|
<h2>3.</h2>
|
||||||
|
<?php
|
||||||
|
/*3. -Crea un select para pedir el dia de nacimiento: 1 al 31. Usa un foreach.
|
||||||
|
*/
|
||||||
|
echo '<select>';
|
||||||
|
foreach (range(1, 31) as $num) {
|
||||||
|
echo "<option value=\"$num\">$num</option>";
|
||||||
|
};
|
||||||
|
echo '</select>';
|
||||||
|
//-A su otro lado select para pedir el mes de nacimiento: 1 al 12. Usa un for.
|
||||||
|
echo '<select>';
|
||||||
|
for ($i = 1; $i < 13; $i++) {
|
||||||
|
echo "<option value=\"$i\">$i</option>";
|
||||||
|
};
|
||||||
|
echo '</select>';
|
||||||
|
//-Y a continuación otro select para pedir el año de nacimiento: 1900 al año actual. Usa un while
|
||||||
|
echo '<select>';
|
||||||
|
$i=1899;
|
||||||
|
while ($i<2024) {
|
||||||
|
$i++;
|
||||||
|
echo "<option value=\"$i\">$i</option>";
|
||||||
|
};
|
||||||
|
echo '</select>';
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
237
Practicas/Practicas_PHP/ejercicios/EJERCICIO3_PHP.php
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>EJERCICIO3 PHP CONDICIONALES</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1.</h2>
|
||||||
|
<?php
|
||||||
|
//1. Comprueba las siguientes condiciones, e indica si se entra o no en el condicional:
|
||||||
|
echo 1;
|
||||||
|
if (True && True) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 2;
|
||||||
|
if (False && True) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 3;
|
||||||
|
if (1 == 1 && 2 == 1) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 4;
|
||||||
|
if ("test" == "test") {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 5;
|
||||||
|
if (1 == 1 || 2 != 1) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 6;
|
||||||
|
if (True && 1 == 1) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 7;
|
||||||
|
if (False && 0 != 0) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 8;
|
||||||
|
if (True || 1 == 1) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 9;
|
||||||
|
if ("test" == "testing") {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 10;
|
||||||
|
if (1 != 0 && 2 == 1) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 11;
|
||||||
|
if ("test" != "testing") {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 12;
|
||||||
|
if ("test" == 1) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 13;
|
||||||
|
if (!(True && False)) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 14;
|
||||||
|
if (!(1 == 1 && 0 != 1)) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 15;
|
||||||
|
if (!(10 == 1 || 1000 == 1000)) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 16;
|
||||||
|
if (!(1 != 10 || 3 == 4)) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 17;
|
||||||
|
if (!("testing" == "testing" && "Zed" == "Cool Guy")) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 18;
|
||||||
|
if (1 == 1 && (!("testing" == 1 || 1 == 0))) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 19;
|
||||||
|
if ("chunky" == "bacon" && (!(3 == 4 || 3 == 3))) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
echo 20;
|
||||||
|
if (3 == 3 && (!("testing" == "testing" || "PHP" == "Fun"))) {
|
||||||
|
echo "Entro en el condicional";
|
||||||
|
} else {
|
||||||
|
echo "No entro en el condicional";}
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
|
||||||
|
?>
|
||||||
|
<h2>2.</h2>
|
||||||
|
<?php
|
||||||
|
/*2. Control de acceso por edad:
|
||||||
|
(Obten el año de nacimiento con un random entre 1900 y 2023)
|
||||||
|
(Obten el año actual del sistema en lugar de escribirlo a mano en una variable con date('Y'))
|
||||||
|
|
||||||
|
-Calcula la edad.
|
||||||
|
-Si es mayor de edad, dile que puede pasar dentro.
|
||||||
|
-Si es menor, dile que no puede pasar.
|
||||||
|
-Si tiene más de 65 años, dile que es demasiado mayor para entrar.*/
|
||||||
|
|
||||||
|
$actual=date("Y");
|
||||||
|
$nacido=rand(1900,2023);
|
||||||
|
$edad=$actual-$nacido;
|
||||||
|
echo $edad;
|
||||||
|
echo '<br>';
|
||||||
|
if ($edad<18) { echo 'No puedes pasar';} else if ($edad>65) {echo 'Eres muy mayor';} else {echo 'Puedes pasar';}
|
||||||
|
echo '<br>';
|
||||||
|
?>
|
||||||
|
<h2>3.</h2>
|
||||||
|
<?php
|
||||||
|
/*3. La función date() con el parametro 'D' nos devuelve las tres primeras letras del día de la semana en inglés: Mon, Tue, Wed, Thu, Fri, Sat, Sun.
|
||||||
|
Ej.echo date('D'); // Salida Mon
|
||||||
|
Empleando switch debemos hacer que en la página salga un mensaje como este con el día en español "Hoy es XXXX".*/
|
||||||
|
echo date('D');
|
||||||
|
echo '<br>';
|
||||||
|
//Switch
|
||||||
|
//Mon, Tue, Wed, Thu, Fri, Sat, Sun
|
||||||
|
$diaIngles=date('D');
|
||||||
|
switch ($diaIngles) {
|
||||||
|
case 'Mon':
|
||||||
|
echo "Hoy es Lunes";
|
||||||
|
break;
|
||||||
|
case 'Tue':
|
||||||
|
echo "Hoy es Martes";
|
||||||
|
break;
|
||||||
|
case 'Wed':
|
||||||
|
echo "Hoy es miercoles";
|
||||||
|
break;
|
||||||
|
case 'Thu':
|
||||||
|
echo "Hoy es Jueves";
|
||||||
|
break;
|
||||||
|
case 'Fri':
|
||||||
|
echo "Hoy es Viernes";
|
||||||
|
break;
|
||||||
|
case 'Sat':
|
||||||
|
echo "Hoy es Sabado";
|
||||||
|
break;
|
||||||
|
case 'Sun':
|
||||||
|
echo "Hoy es Domingo";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
echo "No se a que es igual";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
?>
|
||||||
|
|
||||||
|
<h2>4.</h2>
|
||||||
|
<?php
|
||||||
|
/*4.Crea un simulador de tirada de dados dobles:
|
||||||
|
- Da la puntuación de la tirada.
|
||||||
|
- Debe indicarnos si la tirada es par o impar.
|
||||||
|
- Si sacamos una tirada doble debe indicarlo.*/
|
||||||
|
//Ahora lo pasamos a tres dados indica cuando se saca un doble y un trio
|
||||||
|
echo 'Con dos dados';
|
||||||
|
echo '<br>';
|
||||||
|
$dado1=rand(1,6);
|
||||||
|
$dado2=rand(1,6);
|
||||||
|
$tirada=$dado1+$dado2;
|
||||||
|
echo $dado1;
|
||||||
|
echo '<br>';
|
||||||
|
echo $dado2;
|
||||||
|
echo '<br>';
|
||||||
|
echo "Tu tirada es $tirada";
|
||||||
|
echo '<br>';
|
||||||
|
if ($dado1 == $dado2) {echo 'Tu tirada es doble';} else {echo 'Tu tirada no es doble';}
|
||||||
|
echo '<br>';
|
||||||
|
if (($tirada%2)==0){echo 'Tu trirada es par';} else {echo 'Tu trirada es impar';};
|
||||||
|
//Ahora lo pasamos a tres dados indica cuando se saca un doble y un trio
|
||||||
|
echo '<br>';
|
||||||
|
echo '<br>';
|
||||||
|
echo 'Con tres dados';
|
||||||
|
echo '<br>';
|
||||||
|
$dado1=rand(1,6);
|
||||||
|
$dado2=rand(1,6);
|
||||||
|
$dado3=rand(1,6);
|
||||||
|
$tirada=$dado1+$dado2+$dado3;
|
||||||
|
echo $dado1;
|
||||||
|
echo '<br>';
|
||||||
|
echo $dado2;
|
||||||
|
echo '<br>';
|
||||||
|
echo $dado3;
|
||||||
|
echo '<br>';
|
||||||
|
echo "Tu tirada es $tirada";
|
||||||
|
echo '<br>';
|
||||||
|
if (($tirada%2)==0){echo 'Tu trirada es par';} else {echo 'Tu trirada es impar';};
|
||||||
|
echo '<br>';
|
||||||
|
if ($dado1 == $dado2 && $dado2 == $dado3) {echo 'Tu tirada es triple';} else
|
||||||
|
if ($dado1 == $dado2 || $dado2 == $dado3 || $dado1 == $dado3) {echo 'Tu tirada es doble';}
|
||||||
|
echo '<br>';
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
149
Practicas/Practicas_PHP/ejercicios/EJERCICIO4_PHP_Fechas.php
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>EJERCICIO4 PHP con FECHAS</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>Forma 1 Calcula tu edad con años, meses y días.</h2>
|
||||||
|
<?php
|
||||||
|
// Fecha de nacimiento de la persona
|
||||||
|
//$fecha_nacimiento = '1987-06-15';
|
||||||
|
|
||||||
|
$fecha_randon=date("Y-m-d", rand(-500000000, 500000000));
|
||||||
|
$fecha_nacimiento=$fecha_randon;
|
||||||
|
// Convertir la fecha de nacimiento a objeto de fecha
|
||||||
|
$fecha_nacimiento_obj = new DateTime($fecha_nacimiento);
|
||||||
|
|
||||||
|
// Fecha actual
|
||||||
|
$fecha_actual = new DateTime();
|
||||||
|
|
||||||
|
// Calcular la diferencia entre las fechas (la edad)
|
||||||
|
$diferencia = $fecha_actual->diff($fecha_nacimiento_obj);
|
||||||
|
//var_dump($diferencia);
|
||||||
|
// Obtener los componentes de la diferencia
|
||||||
|
$años = $diferencia->y;
|
||||||
|
$meses = $diferencia->m;
|
||||||
|
$dias = $diferencia->d;
|
||||||
|
|
||||||
|
// Mostrar la edad
|
||||||
|
echo "La edad de la persona es: $años años, $meses meses y $dias días";
|
||||||
|
?>
|
||||||
|
<h2>Forma 2 Calcula tu edad con años, meses y días.</h2>
|
||||||
|
<?php
|
||||||
|
// Fecha de nacimiento de la persona
|
||||||
|
$fecha_nacimiento = '15-06-1987';
|
||||||
|
|
||||||
|
// Convertir la fecha de nacimiento a UNIX
|
||||||
|
$fecha_nacimiento_unix = strtotime($fecha_nacimiento);
|
||||||
|
|
||||||
|
// Fecha actual
|
||||||
|
$fecha_actual =time();
|
||||||
|
|
||||||
|
// Calcular la diferencia entre las fechas (la edad)
|
||||||
|
$diferencia_segundos = $fecha_actual - $fecha_nacimiento_unix;
|
||||||
|
|
||||||
|
// Calcular años, meses y días
|
||||||
|
$años = floor($diferencia_segundos / (365 * 24 * 60 * 60)); // Asumiendo un año de 365 días
|
||||||
|
$meses = floor(($diferencia_segundos % (365 * 24 * 60 * 60)) / (30 * 24 * 60 * 60)); // Asumiendo un mes de 30 días
|
||||||
|
$dias = floor(($diferencia_segundos % (30 * 24 * 60 * 60)) / (24 * 60 * 60)); // Asumiendo un día de 24 horas
|
||||||
|
|
||||||
|
// Mostrar la edad
|
||||||
|
echo "La edad de la persona es: $años años, $meses meses y $dias días";
|
||||||
|
?>
|
||||||
|
<h2>Calcula la fecha de vencimiento de una factura a 30 días desde hoy</h2>
|
||||||
|
<?php
|
||||||
|
// Plazo de pago en días
|
||||||
|
$plazo_pago_dias = 30;
|
||||||
|
|
||||||
|
// Obtener la fecha actual
|
||||||
|
$fecha_actual_emision = new DateTime();
|
||||||
|
|
||||||
|
// Sumar el plazo de pago en días para obtener la fecha de vencimiento
|
||||||
|
$fecha_vencimiento_obj = $fecha_actual_emision->modify("+$plazo_pago_dias days");
|
||||||
|
|
||||||
|
// Obtener la fecha de vencimiento en formato legible
|
||||||
|
$fecha_vencimiento = $fecha_vencimiento_obj->format('d-m-Y');
|
||||||
|
|
||||||
|
// Mostrar la fecha de vencimiento
|
||||||
|
echo "La fecha de vencimiento de la factura es: $fecha_vencimiento";
|
||||||
|
?>
|
||||||
|
|
||||||
|
<h2>Calcula los días que faltan para tu cumpleaños partiendo de la fecha de nacimiento</h2>
|
||||||
|
<?php
|
||||||
|
// Fecha de nacimiento de la persona
|
||||||
|
$fecha_nacimiento = '07-02-1974';
|
||||||
|
|
||||||
|
// Nacimiento en tiempo UNIX
|
||||||
|
$fecha_nacimiento_unix = strtotime($fecha_nacimiento);
|
||||||
|
|
||||||
|
// Fecha actual
|
||||||
|
$fecha_actual = date('d-m-Y');
|
||||||
|
|
||||||
|
// Próximo cumpleaños
|
||||||
|
$proximo_cumpleaños = date('d-m', $fecha_nacimiento_unix) . '-' . date('Y');
|
||||||
|
if ($proximo_cumpleaños < $fecha_actual) {
|
||||||
|
$proximo_cumpleaños = date('d-m', $fecha_nacimiento_unix) . '-' . (date('Y') + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($proximo_cumpleaños == $fecha_actual) {
|
||||||
|
echo 'Hoy es tu cumpleaños';
|
||||||
|
echo '<br>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creo los objetos de las fechas
|
||||||
|
$fecha_actual_obj = new DateTime($fecha_actual);
|
||||||
|
$proximo_cumpleaños_obj = new DateTime($proximo_cumpleaños);
|
||||||
|
|
||||||
|
// Calcular la diferencia entre las fechas
|
||||||
|
$diferencia = $fecha_actual_obj->diff($proximo_cumpleaños_obj);
|
||||||
|
|
||||||
|
// Acceder a los días del intervalo
|
||||||
|
$dias = $diferencia->days;
|
||||||
|
|
||||||
|
// Faltan x días
|
||||||
|
echo "Faltan $dias días para tu cumpleaños";
|
||||||
|
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
<h2>Crea una función para saber si una fecha es fin de semana</h2>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Función para verificar si una fecha es un fin de semana
|
||||||
|
function esFinDeSemana($fecha) {
|
||||||
|
// Convertir la fecha a un objeto DateTime
|
||||||
|
$fecha_obj = new DateTime($fecha);
|
||||||
|
|
||||||
|
// Obtener el día de la semana (0 para domingo, 6 para sábado)
|
||||||
|
global $dia_semana;
|
||||||
|
$dia_semana = $fecha_obj->format('w');
|
||||||
|
|
||||||
|
// Verificar si el día de la semana es sábado o domingo
|
||||||
|
return ($dia_semana == 0 || $dia_semana == 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ejemplo de fecha
|
||||||
|
$fecha_ejemplo = '1987-06-25'; // Viernes
|
||||||
|
|
||||||
|
// Array días semana Español
|
||||||
|
$dias_semana = [
|
||||||
|
'domingo',
|
||||||
|
'lunes',
|
||||||
|
'martes',
|
||||||
|
'miércoles',
|
||||||
|
'jueves',
|
||||||
|
'viernes',
|
||||||
|
'sábado'
|
||||||
|
];
|
||||||
|
|
||||||
|
// Verificar si la fecha es un fin de semana
|
||||||
|
if (esFinDeSemana($fecha_ejemplo)) {
|
||||||
|
echo "$fecha_ejemplo es un fin de semana. Es $dias_semana[$dia_semana]. ";
|
||||||
|
} else {
|
||||||
|
echo "$fecha_ejemplo no es un fin de semana. Es $dias_semana[$dia_semana].";
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>EJERCICIO5 PHP FORMULARIOS V1</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1. Datos formulario</h2>
|
||||||
|
<form method="post">
|
||||||
|
<p>Nombre <input type="text" name="nombre"></p>
|
||||||
|
<p>Teléfono <input type="tel" name="telefono"></p>
|
||||||
|
<p>Correo <input type="mail" name="correo"></p>
|
||||||
|
<p>Mensaje <input type="text" name="mensaje"></p>
|
||||||
|
<p><input type="submit" value="Enviar"></p>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
/*
|
||||||
|
Realiza un formulario con los siguientes datos: nombre, telefono, email y mensaje.
|
||||||
|
Cuando se pulse en enviar debe mostrar la siguiente plantilla.
|
||||||
|
“Hola nombre!
|
||||||
|
Te voy a enviar spam a correo y te llamaré de madrugada a telefono.
|
||||||
|
mensaje
|
||||||
|
Enviado desde un iPhone”*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$nombre = isset($_POST['nombre']) ? $_POST['nombre'] : null;
|
||||||
|
$telefono = isset($_POST['telefono']) ? $_POST['telefono'] : null;
|
||||||
|
$correo = isset($_POST['correo']) ? $_POST['correo'] : null;
|
||||||
|
$mensaje = isset($_POST['mensaje']) ? $_POST['mensaje'] : null;
|
||||||
|
|
||||||
|
if ( $nombre != null && $telefono != null && $correo != null && $mensaje != null ) {
|
||||||
|
echo '<br>';
|
||||||
|
echo "Hola $nombre";
|
||||||
|
echo '<br>';
|
||||||
|
echo "Te voy a enviar spam a $correo y te llamaré de madrugada al $telefono .";
|
||||||
|
echo '<br>';
|
||||||
|
echo $mensaje;
|
||||||
|
echo '<br>';
|
||||||
|
echo 'Enviado desde mi Iphone';
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
<h2>2. ¿Quien saca al perro?</h2>
|
||||||
|
<form method="post">
|
||||||
|
<textarea name="nombres"></textarea>
|
||||||
|
<p><input type="reset" value="Limpiar"></p>
|
||||||
|
<p><input type="submit" value="Enviar"></p>
|
||||||
|
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
//¿Quién saca al perro?
|
||||||
|
/*
|
||||||
|
Escribe en un textarea una lista de nombres.
|
||||||
|
Cuando pulses un botón debes mostrar un nombre aleatorio. (Será el encargado de sacar al perro)
|
||||||
|
Muestra la respuesta con la siguiente plantilla: nombre sacará el perro a pasear.*/
|
||||||
|
|
||||||
|
|
||||||
|
$nombres=isset($_POST['nombres'])? $_POST['nombres'] : '';
|
||||||
|
if ( $nombres != '') {
|
||||||
|
$arrayNombres=preg_split('/[\s,]+/', $nombres);
|
||||||
|
$num=count($arrayNombres)-1;
|
||||||
|
$ale=rand(0,$num);
|
||||||
|
echo '<br>';
|
||||||
|
echo "$arrayNombres[$ale] sacará el perro a pasear";
|
||||||
|
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
?>
|
||||||
|
<h2>3. Adivinanza</h2>
|
||||||
|
<p> “Esta cosa se devora a todas las cosas;<br>
|
||||||
|
Pájaros, bestias, árboles, flores;<br>
|
||||||
|
Carcome el hierro, muerde el acero;<br>
|
||||||
|
Muele duras piedras y las reduce a harina;<br>
|
||||||
|
Mata al rey, arruina la ciudad,<br>
|
||||||
|
Y derriba a la montaña.”</p>
|
||||||
|
<form method="post">
|
||||||
|
<p>Respuesta <input type="text" name="respuesta"></p>
|
||||||
|
<p><input type="submit" value="Enviar"></p>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
/*3.Adivinanza:
|
||||||
|
“Esta cosa se devora a todas las cosas;
|
||||||
|
Pájaros, bestias, árboles, flores;
|
||||||
|
Carcome el hierro, muerde el acero;
|
||||||
|
Muele duras piedras y las reduce a harina;
|
||||||
|
Mata al rey, arruina la ciudad,
|
||||||
|
Y derriba a la montaña.”
|
||||||
|
- En un input, pide la respuesta.
|
||||||
|
- Añade un botón de submit.
|
||||||
|
- Si se pulsa el botón debes comprobar si ha acertado. La respuesta es: Tiempo.
|
||||||
|
- Si acierta felicítale.
|
||||||
|
- Si pierde, muestra la respuesta y dile que es un burricán.*/
|
||||||
|
$respuesta='tiempo';
|
||||||
|
$respuestaU=isset($_POST['respuesta'])? strtolower($_POST['respuesta']) : '';
|
||||||
|
|
||||||
|
if ($respuestaU != '') {
|
||||||
|
if ($respuesta == $respuestaU || (str_contains($respuestaU,$respuesta))) {echo '<p>Enhorabuena !!</p><p>Has acertado</p>';}
|
||||||
|
else {echo '<p>No has acertado !!</p><p>Eres un burrican , la respuesta es: tiempo</p>';}
|
||||||
|
} else { echo 'Debes responder en la casilla'; }
|
||||||
|
?>
|
||||||
|
<h2>4. Calculadora de IVA</h2>
|
||||||
|
<form method="post">
|
||||||
|
<p>Introduce el precio sin IVA <input type="text" name="precioneto" value="0"></p>
|
||||||
|
<p><input type="submit" value="Enviar"></p>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
//Calculadora de IVA
|
||||||
|
// Debemos crear una calculadora de IVA, el usuario introduce el precio en un input y le damos el precio con IVA.
|
||||||
|
$precioneto=isset($_POST['precioneto'])? $_POST['precioneto'] : '';
|
||||||
|
$precio=round(floatval($precioneto)*1.21,2);
|
||||||
|
echo "<p>El precio con IVA es de $precio Euros</p>";
|
||||||
|
?>
|
||||||
|
<h2>5. Lista de películas</h2>
|
||||||
|
<form method="post">
|
||||||
|
<p>Película 1 <input type="text" name="peliculas[]" ></p>
|
||||||
|
<p>Película 2 <input type="text" name="peliculas[]" ></p>
|
||||||
|
<p>Película 3 <input type="text" name="peliculas[]" ></p>
|
||||||
|
<p>Película 4 <input type="text" name="peliculas[]" ></p>
|
||||||
|
<p>Película 5 <input type="text" name="peliculas[]" ></p>
|
||||||
|
<p><input type="submit" name="enviar" value="Añadir"></p>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
/*5.Listado de películas
|
||||||
|
Crea 5 inputs y un botón de submit.
|
||||||
|
Rellena cada campo de los inputs con el nombre de una película.
|
||||||
|
Cuando se pulse debe guardar el contenido en un array.
|
||||||
|
Imprime el resultado en una tabla en cada fila la posición de la pelicula y el nombre en distintas celdas*/
|
||||||
|
|
||||||
|
$peliculas=[];
|
||||||
|
echo "<br>";
|
||||||
|
$peliculas=isset($_POST['peliculas']) ? $_POST['peliculas'] : [];
|
||||||
|
echo "<br>";
|
||||||
|
echo '<table border="2">';
|
||||||
|
foreach ($peliculas as $posicion=>$nombre) {
|
||||||
|
$posicion=$posicion+1;
|
||||||
|
echo "<tr><td>$posicion</td><td>$nombre</td></tr>";
|
||||||
|
}
|
||||||
|
echo '</table>';
|
||||||
|
echo "<br>";
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Subir Archivo de DNI</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>Subir Archivo de DNI</h2>
|
||||||
|
<form action="" method="post" enctype="multipart/form-data">
|
||||||
|
<label for="name">* Nombre:</label><br>
|
||||||
|
<input type="text" id="nombre" name="nombre" required><br><br>
|
||||||
|
|
||||||
|
<label for="email">* Correo Electrónico:</label><br>
|
||||||
|
<input type="email" id="email" name="email" required><br><br>
|
||||||
|
|
||||||
|
<label for="dniFile">* Subir DNI (jpg o pdf, tamaño máximo 5MB):</label><br>
|
||||||
|
<input type="file" id="dniFile" name="dniFile" accept=".jpg,.pdf" required><br><br>
|
||||||
|
|
||||||
|
<input type="submit" value="Enviar" name="submit">
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Verifica si el formulario ha sido enviado
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["dniFile"])) {
|
||||||
|
// Nombre y correo electrónico del usuario
|
||||||
|
$nombre = $_POST["nombre"];
|
||||||
|
$email = $_POST["email"];
|
||||||
|
|
||||||
|
// Directorio donde se guardarán los archivos subidos
|
||||||
|
$directorio_subida = "dni_usuarios/";
|
||||||
|
|
||||||
|
// Nombre del archivo y ruta de destino
|
||||||
|
$nombre_archivo=$_FILES["dniFile"]["name"];
|
||||||
|
$nombre_archivo_final = time().'_'.rand(100,999).'_'.$email.'_'.$nombre_archivo;
|
||||||
|
$ruta_archivo = $directorio_subida . $nombre_archivo_final;
|
||||||
|
|
||||||
|
// Tamaño máximo permitido (5MB)
|
||||||
|
$tamano_maximo = 5 * 1024 * 1024;
|
||||||
|
|
||||||
|
// Obtiene la extensión del archivo
|
||||||
|
$extension_archivo = strtolower(pathinfo($_FILES["dniFile"]["name"], PATHINFO_EXTENSION));
|
||||||
|
|
||||||
|
// Array de extensiones permitidas
|
||||||
|
$extensiones_permitidas = array("jpg", "jpeg", "pdf");
|
||||||
|
|
||||||
|
// Verifica si el archivo es una extensión permitida y no excede el tamaño máximo
|
||||||
|
if (in_array($extension_archivo, $extensiones_permitidas) && $_FILES["dniFile"]["size"] <= $tamano_maximo) {
|
||||||
|
// Verifica si hubo algún error durante la subida del archivo
|
||||||
|
if ($_FILES["dniFile"]["error"] === 0) {
|
||||||
|
// Intenta mover el archivo al directorio de destino
|
||||||
|
if (move_uploaded_file($_FILES["dniFile"]["tmp_name"], $ruta_archivo)) {
|
||||||
|
echo "El archivo " . htmlspecialchars($nombre_archivo) . " ha sido subido exitosamente.";
|
||||||
|
|
||||||
|
} else {
|
||||||
|
echo "Lo siento, hubo un error al subir el archivo.";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo "Error: " . $_FILES["dniFile"]["error"];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo "Lo siento, solo se permiten archivos en formato JPG o PDF con un tamaño máximo de 5MB.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
<?php
|
||||||
|
$archivo = "formularios/registro.txt";
|
||||||
|
|
||||||
|
// Verifico si existe
|
||||||
|
if (file_exists($archivo)) {
|
||||||
|
/*
|
||||||
|
//Con file_get_contents
|
||||||
|
// Leo el contenido del archivo
|
||||||
|
$contenido = file_get_contents($archivo);
|
||||||
|
|
||||||
|
// Divide el contenido en líneas
|
||||||
|
$lineas = explode("\n", $contenido);
|
||||||
|
array_pop($lineas);// Borro la última línea vacia
|
||||||
|
//var_dump($lineas);
|
||||||
|
// Comienzo la tabla HTML
|
||||||
|
echo "<table border='1'>";
|
||||||
|
echo "<tr><th>Número</th><th>Nombre</th><th>Email</th><th>Ruta de Archivo</th></tr>";
|
||||||
|
|
||||||
|
// Itero sobre cada línea
|
||||||
|
$num=0;
|
||||||
|
foreach ($lineas as $linea) {
|
||||||
|
// Divido los datos de la línea utilizando el delimitador "/_/"
|
||||||
|
$datos = explode("/_/", $linea);
|
||||||
|
$num++;
|
||||||
|
// Muestra los datos en una fila de la tabla
|
||||||
|
echo "<tr>";
|
||||||
|
echo "<td>" . $num . "</td>"; // Número
|
||||||
|
echo "<td>" . $datos[0] . "</td>"; // Nombre
|
||||||
|
echo "<td>" . $datos[1] . "</td>"; // Email
|
||||||
|
echo "<td>" . $datos[2] . "</td>"; // Ruta de Archivo
|
||||||
|
echo "</tr>";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cierro la tabla HTML
|
||||||
|
echo "</table>";
|
||||||
|
} else {
|
||||||
|
echo "El archivo no existe.";
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Con fgets
|
||||||
|
// Abrir el archivo en modo lectura
|
||||||
|
$gestor = fopen($archivo, "r");
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Comienzo la tabla HTML
|
||||||
|
echo "<table border='1'>";
|
||||||
|
echo "<tr><th>Número</th><th>Nombre</th><th>Email</th><th>Ruta de Archivo</th></tr>";
|
||||||
|
|
||||||
|
$num = 0;
|
||||||
|
|
||||||
|
// Iterar sobre cada línea del archivo
|
||||||
|
while (($linea = fgets($gestor)) !== false) {
|
||||||
|
|
||||||
|
// Dividir los datos de la línea utilizando el delimitador "/_/"
|
||||||
|
$datos = explode("/_/", $linea);
|
||||||
|
|
||||||
|
// Incrementar el número de fila
|
||||||
|
$num++;
|
||||||
|
|
||||||
|
// Mostrar los datos en una fila de la tabla
|
||||||
|
echo "<tr>";
|
||||||
|
echo "<td>" . $num . "</td>"; // Número
|
||||||
|
echo "<td>" . $datos[0] . "</td>"; // Nombre
|
||||||
|
echo "<td>" . $datos[1] . "</td>"; // Email
|
||||||
|
echo "<td>" . $datos[2] . "</td>"; // Ruta de Archivo
|
||||||
|
echo "</tr>";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cerrar el archivo
|
||||||
|
fclose($gestor);
|
||||||
|
|
||||||
|
// Cerrar la tabla HTML
|
||||||
|
echo "</table>";
|
||||||
|
} else {
|
||||||
|
echo "El archivo no existe.";
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
// Con fgetcsv
|
||||||
|
|
||||||
|
echo '<table border="2">';
|
||||||
|
$archivo = fopen($nombre_archivo,'r');
|
||||||
|
while(($linea = fgetcsv($archivo, 0, ';'))) {
|
||||||
|
echo '<tr>';
|
||||||
|
echo '<td>' . $linea[0] . '</td>';
|
||||||
|
echo '<td>' . $linea[1] . '</td>';
|
||||||
|
echo '<td>' . $linea[2] . '</td>';
|
||||||
|
echo '</tr>';
|
||||||
|
}
|
||||||
|
echo '<table>';
|
||||||
|
fclose($archivo);
|
||||||
|
*/
|
||||||
60
Practicas/Practicas_PHP/ejercicios/Ejercicio1_04.php
Executable file
@@ -0,0 +1,60 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Document</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<?php
|
||||||
|
function areaEsfera($radio)
|
||||||
|
{
|
||||||
|
$area = 4 * pi() * pow($radio, 2);
|
||||||
|
return $area;
|
||||||
|
}
|
||||||
|
|
||||||
|
$texto = '<p>Hoy, es un buen día para aprender a programar en PHP.</p>';
|
||||||
|
echo $texto;
|
||||||
|
$nombre = 'Marcos Lopez';
|
||||||
|
$edad = 46;
|
||||||
|
echo '<p>Soy ' . $nombre . ' y tengo ' . $edad . ' años<p>';
|
||||||
|
|
||||||
|
|
||||||
|
$radio1 = 10;
|
||||||
|
$area1 = areaEsfera($radio1);
|
||||||
|
echo "El area de una esfera de $radio1 metros de radio es: $area1 <br>";
|
||||||
|
$radio2 = 4;
|
||||||
|
$area2 = areaEsfera($radio2);
|
||||||
|
echo "El area de una esfera de $radio2 metros de radio es: $area2 <br>";
|
||||||
|
|
||||||
|
|
||||||
|
echo '<p>Las siglas de HTML significan "HyperText Markup language"</p>';
|
||||||
|
$rojo = 'rojo';
|
||||||
|
$azul = 'azul';
|
||||||
|
$verde = 'verde';
|
||||||
|
echo "Los colores guardados en las variables son $rojo, $azul, $verde";
|
||||||
|
|
||||||
|
$microrelato = 'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eaque quidem omnis sequi delectus fugiat sint, veniam adipisci officiis. Molestias aperiam non inventore possimus alias minima obcaecati odio ab nisi quos!';
|
||||||
|
$numeroPalabras = str_word_count($microrelato);
|
||||||
|
echo '<br>';
|
||||||
|
echo $microrelato;
|
||||||
|
echo '<br>';
|
||||||
|
echo "Nº de palabras: $numeroPalabras";
|
||||||
|
$poblaciones = ["España" => 47329981, "Portugal" => 10341330, "Francia" => 65273111, "Italia" => 60461826, "Grecia" => 10724599];
|
||||||
|
arsort($poblaciones);
|
||||||
|
echo '<ol>';
|
||||||
|
|
||||||
|
foreach ($poblaciones as $pais => $poblacion) {
|
||||||
|
echo "<li> $pais - $poblacion </li>";
|
||||||
|
}
|
||||||
|
echo '</ol>';
|
||||||
|
|
||||||
|
var_dump($poblaciones);
|
||||||
|
|
||||||
|
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
110
Practicas/Practicas_PHP/ejercicios/Ejercicio2_04.php
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Document</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// 1.Guarda en un array tus 6 películas favoritas.
|
||||||
|
// -Imprime en párrafos con el siguiente formato: ‘Película: Los Vengadores’
|
||||||
|
// -Añade la posición de la película a la lista: ‘Película 4: Godzilla’
|
||||||
|
// -Despues imprime en lugar de párrafos… ¡una lista!
|
||||||
|
$peliculas = ['La Comunidad del anilllo', 'Las dos Torres', 'El retorno del Rey', 'Regreso al futuro I', 'Regreso al futuro II', 'Regreso al futuro III'];
|
||||||
|
foreach ($peliculas as $pelicula) {
|
||||||
|
echo "<p>Pelicula $pelicula</p>";
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($peliculas as $index => $pelicula) {
|
||||||
|
echo "<p>Pelicula " . ($index + 1) . " - $pelicula</p>";
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '<ul>';
|
||||||
|
foreach ($peliculas as $index => $pelicula) {
|
||||||
|
echo "<li>Pelicula " . ($index + 1) . " - $pelicula</li>";
|
||||||
|
}
|
||||||
|
echo '</ul>';
|
||||||
|
|
||||||
|
|
||||||
|
// 2.Utilizando bucles:
|
||||||
|
// - Imprime los números del 1 al 10.(separados por comas)
|
||||||
|
// - Imprime los números de 60 al 70.(separados por comas)
|
||||||
|
// - Imprime los números del 20 al 1.(separados por comas)
|
||||||
|
// - Imprime los números del 1 al 1000.(separados por comas)
|
||||||
|
// - Imprime la tabla del 5.(con este formato 5 x 1 = 5)
|
||||||
|
// - Imprimir los números pares que hay dentro de los 100 primeros números enteros.
|
||||||
|
// - Escribe un script PHP que muestre los números del 1 al 10 en una tabla de una fila y 10 columnas.
|
||||||
|
foreach (range(1, 10) as $num) {
|
||||||
|
echo "$num ,";
|
||||||
|
};
|
||||||
|
echo '<br>';
|
||||||
|
foreach (range(60, 70) as $num) {
|
||||||
|
echo "$num ,";
|
||||||
|
};
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 20; $i >= 1; $i--) {
|
||||||
|
echo $i . ", ";
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 1; $i <= 1000; $i++) {
|
||||||
|
echo $i . ", ";
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 1; $i <= 10; $i++) {
|
||||||
|
echo '<p> 5 X ' . $i . ' = ' . (5 * $i) . '</p>';
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
for ($i = 0; $i <= 100; $i = $i + 2) {
|
||||||
|
echo $i . ", ";
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
echo "<table border='2'><tr>";
|
||||||
|
for ($i = 1; $i <= 10; $i++) {
|
||||||
|
echo "<td>$i</td>";
|
||||||
|
}
|
||||||
|
echo "</tr></table>";
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<!-- 3. -Crea una lista de selección para pedir el dia de nacimiento: 1 al 31. Usa un foreach.
|
||||||
|
-A su otro lado select para pedir el mes de nacimiento: 1 al 12. Usa un for.
|
||||||
|
-Y a continuación otro select para pedir el año de nacimiento: 1900 al año actual. Usa un while. -->
|
||||||
|
<label for="diaNac">Fecha de Nacieminto: </label>
|
||||||
|
<select name="diaNac" id="diaNac">
|
||||||
|
<?php
|
||||||
|
$i = 1;
|
||||||
|
while ($i <= 31) {
|
||||||
|
echo "<option value=\"$i\"> $i </option>";
|
||||||
|
$i++;
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select name="mesNac" id="mesNac">
|
||||||
|
<?php
|
||||||
|
for ($i=1; $i <= 12; $i++) {
|
||||||
|
echo "<option value=\"$i\"> $i </option>";
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select name="anoNac" id="anoNac">
|
||||||
|
<?php
|
||||||
|
$i = 1900;
|
||||||
|
while ($i <= 2024) {
|
||||||
|
echo "<option value=\"$i\"> $i </option>";
|
||||||
|
$i++;
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
244
Practicas/Practicas_PHP/ejercicios/Ejercicio3_04.php
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=, initial-scale=1.0">
|
||||||
|
<title>Document</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<?php
|
||||||
|
// 1. Comprueba las siguientes condiciones, e indica si se entra o no en el condicional, debemos ejecutar la condición:
|
||||||
|
// if (True && True) TRUE
|
||||||
|
// if (False && True) FALSE
|
||||||
|
// if (1 == 1 && 2 == 1) FALSE
|
||||||
|
// if ("test" == "test") TRUE
|
||||||
|
// if (1 == 1 || 2 != 1) TRUE
|
||||||
|
// if (True && 1 == 1) TRUE
|
||||||
|
// if (False && 0 != 0) FALSE
|
||||||
|
// if (True || 1 == 1) TRUE
|
||||||
|
// if ("test" == "testing") FALSE
|
||||||
|
// if (1 != 0 && 2 == 1) FALSE
|
||||||
|
// if ("test" != "testing") TRUE
|
||||||
|
// if ("test" == 1) FALSE
|
||||||
|
// if (!(True && False)) TRUE
|
||||||
|
// if (!(1 == 1 && 0 != 1)) FALSE
|
||||||
|
// if (!(10 == 1 || 1000 == 1000)) FALSE
|
||||||
|
// if (!(1 != 10 || 3 == 4)) FALSE
|
||||||
|
// if (!("testing" == "testing" && "Zed" == "Cool Guy")) TRUE
|
||||||
|
// if (1 == 1 && (!("testing" == 1 || 1 == 0))) TRUE
|
||||||
|
// if ("chunky" == "bacon" && (!(3 == 4 || 3 == 3))) FALSE
|
||||||
|
// if (3 == 3 && (!("testing" == "testing" || "PHP" == "Fun"))) FALSE
|
||||||
|
|
||||||
|
if ((true && true)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((false && true)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((1 == 1 && 2 == 1)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if (("test" == "test")) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((1 == 1 || 2 != 1)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((true && 1 == 1)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((false && 0 != 0)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((true || 1 == 1)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if (("test" == "testing")) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((1 != 0 && 2 == 1)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if (("test" != "testing")) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if (("test" == 1)) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((!(true && false))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((!(1 == 1 && 0 != 1))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((!(10 == 1 || 1000 == 1000))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((!(1 != 10 || 3 == 4))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((!("testing" == "testing" && "Zed" == "Cool Guy"))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((1 == 1 && (!("testing" == 1 || 1 == 0)))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if (("chunky" == "bacon" && (!(3 == 4 || 3 == 3)))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
if ((3 == 3 && (!("testing" == "testing" || "PHP" == "Fun")))) {
|
||||||
|
echo "True";
|
||||||
|
} else {
|
||||||
|
echo "False";
|
||||||
|
}
|
||||||
|
echo "<br>";
|
||||||
|
|
||||||
|
|
||||||
|
// 2. Control de acceso por edad:(Obten el año actual del sistema en lugar de escribirlo a mano en una variable con date('Y'))
|
||||||
|
// (Obten el año de nacimiento con un random entre 1900 y 2023)
|
||||||
|
// -Pide el año de nacimiento.
|
||||||
|
// -Calcula la edad.
|
||||||
|
// -Si es mayor de edad, dile que puede pasar dentro.
|
||||||
|
// -Si es menor, dile que no puede pasar.
|
||||||
|
// -Si tiene más de 65 años, dile que es demasiado mayor para entrar.
|
||||||
|
|
||||||
|
$anoNac = rand(1900, 2023);
|
||||||
|
$edad = date('Y') - $anoNac;
|
||||||
|
echo "Año de nacimiento: $anoNac, tiene $edad años <br>";
|
||||||
|
if ($edad >= 18) {
|
||||||
|
if ($edad >= 65) {
|
||||||
|
echo 'Demasiado mayor para pasar!!!!!';
|
||||||
|
} else {
|
||||||
|
echo 'Puedes pasar!!!!!';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echo 'No puedes pasar!!!!!';
|
||||||
|
}
|
||||||
|
echo '<br>';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//3. La función date() con el parametro 'D' nos devuelve las tres primeras letras del día de la semana en inglés: Mon, Tue, Wed, Thu, Fri, Sat, Sun.
|
||||||
|
//Ej.echo date('D'); // Salida Mon
|
||||||
|
//Empleando switch debemos hacer que en la página salga un mensaje como este con el día en español "El día de la semana es: XXXX".
|
||||||
|
switch (date('D')) {
|
||||||
|
case 'Mon':
|
||||||
|
$diaEsp = 'Lunes';
|
||||||
|
break;
|
||||||
|
case 'Tue':
|
||||||
|
$diaEsp = 'Martes';
|
||||||
|
break;
|
||||||
|
case 'Wed':
|
||||||
|
$diaEsp = 'Miercoles';
|
||||||
|
break;
|
||||||
|
case 'Thu':
|
||||||
|
$diaEsp = 'Jueves';
|
||||||
|
break;
|
||||||
|
case 'Fri':
|
||||||
|
$diaEsp = 'Viernes';
|
||||||
|
break;
|
||||||
|
case 'Sat':
|
||||||
|
$diaEsp = 'Sabado';
|
||||||
|
break;
|
||||||
|
case 'Sun':
|
||||||
|
$diaEsp = 'Domingo';
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
echo "Día de la semana $diaEsp";
|
||||||
|
|
||||||
|
echo '<br>';
|
||||||
|
// 4.Crea un simulador de tirada de dados dobles:
|
||||||
|
// - Da la puntuación de la tirada.
|
||||||
|
// - Debe indicarnos si la tirada es par o impar.
|
||||||
|
// - Si sacamos una tirada doble debe indicarlo.
|
||||||
|
$dado1 = rand(1, 6);
|
||||||
|
$dado2 = rand(1, 6);
|
||||||
|
$resTirada = $dado1 + $dado2;
|
||||||
|
echo "DADOS!!!! (dobles) <br> La tirada es $resTirada <br>";
|
||||||
|
if ($dado1 === $dado2) {
|
||||||
|
echo "Has hecho un doble $dado1 <br>";
|
||||||
|
}
|
||||||
|
if ($resTirada % 2 === 0) {
|
||||||
|
echo "La tirada es par <br>";
|
||||||
|
}
|
||||||
|
|
||||||
|
//Ahora lo pasamos a tres dados indica cuando se saca un doble y un trio
|
||||||
|
$dado1 = rand(1, 6);
|
||||||
|
$dado2 = rand(1, 6);
|
||||||
|
$dado3 = rand(1, 6);
|
||||||
|
$resTirada = $dado1 + $dado2 + $dado3;
|
||||||
|
echo "DADOS!!!! (triples) <br> La tirada es $resTirada <br>";
|
||||||
|
if ($dado1 === $dado2 && $dado1 === $dado3) {
|
||||||
|
echo "Has hecho un triple $dado1 <br>";
|
||||||
|
}
|
||||||
|
if ($resTirada % 2 === 0) {
|
||||||
|
echo "La tirada es par <br>";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
68
Practicas/Practicas_PHP/ejercicios/Ejercicio4_04.php
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Document</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Establecer la zona horaria a tu zona local
|
||||||
|
date_default_timezone_set('Europe/Madrid');
|
||||||
|
|
||||||
|
$fechaNacimiento = new DateTime('1977-10-23');
|
||||||
|
$fechaActual = new DateTime();
|
||||||
|
|
||||||
|
|
||||||
|
// 1- Crea un script que partiendo de tu fecha de nacimiento calcule tu edad con años, meses y días.
|
||||||
|
$diferencia = $fechaActual->diff($fechaNacimiento);
|
||||||
|
echo "Tienes $diferencia->y años, $diferencia->m meses y $diferencia->d dias. <br>";
|
||||||
|
|
||||||
|
// 2- Crea un script que calcule la fecha de vencimiento de una factura a 30 días desde hoy.
|
||||||
|
$fechaVencimiento = clone $fechaActual;
|
||||||
|
$fechaVencimiento->modify('+30 days');
|
||||||
|
$fechaVencimiento = new DateTime();
|
||||||
|
echo "La fecha de vencimiento es: {$fechaVencimiento->format('d-m-Y')} <br>";
|
||||||
|
|
||||||
|
// 3- Crea un script que calcule los días que faltan para tu cumpleaños partiendo de la fecha de nacimiento.
|
||||||
|
$proximoCumple = new DateTime($fechaActual->format('Y') . '-' . $fechaNacimiento->format('m-d'));
|
||||||
|
if ($proximoCumple < $fechaActual) {
|
||||||
|
$proximoCumple->modify('+1 year');
|
||||||
|
}
|
||||||
|
$diferencia = $fechaActual->diff($proximoCumple);
|
||||||
|
echo "Quedan $diferencia->days dias para tu cumpleaños <br>";
|
||||||
|
|
||||||
|
|
||||||
|
// Crea una función para saber si una fecha es fin de semana.
|
||||||
|
|
||||||
|
if (esfinde($fechaNacimiento)) {
|
||||||
|
echo "El dia {$fechaNacimiento->format('d-m-Y')} es fin de semana";
|
||||||
|
} else {
|
||||||
|
echo "El dia {$fechaNacimiento->format('d-m-Y')} no es fin de semana";
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
function esFinde($fecha)
|
||||||
|
{
|
||||||
|
$dia = $fecha->format('w');
|
||||||
|
switch ($dia) {
|
||||||
|
case 6:
|
||||||
|
return true;
|
||||||
|
break;
|
||||||
|
case 0:
|
||||||
|
return true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
43
Practicas/Practicas_PHP/ejercicios/Ejercicio5V2_04.php
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Ejercicio6_04</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<form method="post" enctype="multipart/form-data">
|
||||||
|
<label for="nombre">Nombre: </label><input type="text" name="nombre" id="nombre" required> <br><br>
|
||||||
|
<label for="email">E-Mail: </label><input type="text" name="email" id="email" required> <br><br>
|
||||||
|
<label for="nif">NIF: </label><input type="file" name="nif" id="nif" accept=".jpg,.pdf" required> <br> <br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["nif"])) {
|
||||||
|
|
||||||
|
$directorioDestino = 'uploads/';
|
||||||
|
|
||||||
|
$email = $_POST['email'];
|
||||||
|
$nombre_archivo = basename($_FILES["nif"]['name']);
|
||||||
|
$tipoArchivo = strtolower(pathinfo($nombre_archivo, PATHINFO_EXTENSION));
|
||||||
|
|
||||||
|
$tamanoArchivo = $_FILES["nif"]["size"];
|
||||||
|
$ext_permitidas = array("jpg", "pdf");
|
||||||
|
$tamanoMaximo = 5 * 1024 * 1024;
|
||||||
|
|
||||||
|
if ($tamanoArchivo <= $tamanoMaximo && in_array($tipoArchivo, $ext_permitidas)) {
|
||||||
|
$nombreUnico = time() . "_" . mt_rand(100, 999) . "_" . $email . "_" . $nombre_archivo;
|
||||||
|
$rutaArchivoDestino = $directorioDestino . $nombreUnico;
|
||||||
|
move_uploaded_file($_FILES["nif"]["tmp_name"], $rutaArchivoDestino);
|
||||||
|
} else {
|
||||||
|
echo 'No se ha podido subir el fichero';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
162
Practicas/Practicas_PHP/ejercicios/Ejercicio5_04.php
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Ejercicio 5 PHP</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<!-- 1.Realiza un formulario con los siguientes datos: nombre, telefono, email y mensaje.
|
||||||
|
Cuando se pulse en enviar debe mostrar la siguiente plantilla. -->
|
||||||
|
|
||||||
|
<h2>Formulario de contacto</h2>
|
||||||
|
<form action="" method="post">
|
||||||
|
<label for="nombre">Nombre:</label>
|
||||||
|
<input type="text" id="nombre" name="nombre">
|
||||||
|
<br>
|
||||||
|
<label for="telefono">Teléfono:</label>
|
||||||
|
<input type="tel" id="telefono" name="telefono">
|
||||||
|
<br>
|
||||||
|
<label for="email">Email:</label>
|
||||||
|
<input type="email" id="email" name="email">
|
||||||
|
<br>
|
||||||
|
<label for="mensaje">Mensaje:</label>
|
||||||
|
<br>
|
||||||
|
<textarea id="mensaje" name="mensaje" rows="5" cols="30"></textarea>
|
||||||
|
<br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// Verificamos si el formulario fue enviado
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
if (isset($_POST["nombre"]) && isset($_POST["email"]) && isset($_POST["telefono"]) && isset($_POST["mensaje"])) {
|
||||||
|
echo "Hola {$_POST["nombre"]}! <br>Te voy a enviar span a {$_POST["email"]} y te llamare de madrugada al {$_POST["telefono"]} <br>";
|
||||||
|
echo "Para decirte: <br>";
|
||||||
|
echo $_POST["mensaje"];
|
||||||
|
echo '<br>';
|
||||||
|
echo "Enviado desde un Iphone";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- 2. ¿Quién saca al perro?
|
||||||
|
Escribe en un textarea una lista de nombres.
|
||||||
|
Cuando pulses un botón debes mostrar un nombre aleatorio. (Será el encargado de sacar al perro)
|
||||||
|
Muestra la respuesta con la siguiente plantilla: nombre sacará el perro a pasear. -->
|
||||||
|
|
||||||
|
<form action="" method="post">
|
||||||
|
<label for="listaPerro">Lista de nombres:</label>
|
||||||
|
<br>
|
||||||
|
<textarea id="listaPerro" name="listaPerro" rows="5" cols="30"></textarea>
|
||||||
|
<br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
|
||||||
|
if (isset($_POST["listaPerro"])) {
|
||||||
|
$nombres = $_POST['listaPerro'];
|
||||||
|
$listaNombres = explode("\n", $nombres);
|
||||||
|
$indiceAleatorio = rand(0, count($listaNombres) - 1);
|
||||||
|
$nombreElegido = $listaNombres[$indiceAleatorio];
|
||||||
|
echo $nombreElegido;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
<!-- 3.Adivinanza: -->
|
||||||
|
<form action="" method="post">
|
||||||
|
<label for="respuesta">Adivinanza: <br>
|
||||||
|
“Esta cosa se devora a todas las cosas; <br>
|
||||||
|
Pájaros, bestias, árboles, flores;<br>
|
||||||
|
Carcome el hierro, muerde el acero;<br>
|
||||||
|
Muele duras piedras y las reduce a harina;<br>
|
||||||
|
Mata al rey, arruina la ciudad,<br>
|
||||||
|
Y derriba a la montaña.” <br></label>
|
||||||
|
<input type="text" name="respuesta" id="respuesta">
|
||||||
|
<br>
|
||||||
|
<input type="submit" value="Comprobar respuesta">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
if (isset($_POST["respuesta"])) {
|
||||||
|
$resp = $_POST["respuesta"];
|
||||||
|
if ($resp === "Tiempo") {
|
||||||
|
echo "Enhorabuena!!! Acertaste";
|
||||||
|
} else {
|
||||||
|
echo "Lo siento, la respuesta no es correcta";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
<!-- 4.Calculadora de IVA
|
||||||
|
Debemos crear una calculadora de IVA, el usuario introduce el precio en un input y le damos el precio con IVA. -->
|
||||||
|
<form action="" method="post">
|
||||||
|
<label for="precio">Introduce el precio:</label>
|
||||||
|
<input type="text" name="precio" id="precio">
|
||||||
|
<input type="submit" value="Calcula el precio con iva">
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
if (isset($_POST["precio"])) {
|
||||||
|
$pvpSin = round(floatval($_POST["precio"]),2);
|
||||||
|
$pvpCon = $pvpSin * 1.21;
|
||||||
|
echo "El precio con IVA es $pvpCon";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<!-- 5.Listado de películas
|
||||||
|
Crea 5 inputs y un botón de submit.
|
||||||
|
Rellena cada campo de los inputs con el nombre de una película.
|
||||||
|
Cuando se pulse debe guardar el contenido.
|
||||||
|
Imprime el resultado en una tabla en cada fila la posición de la pelicula y el nombre en distintas celdas -->
|
||||||
|
|
||||||
|
<form action="" method="post">
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
|
<label for="nombrePelicula[]">Introduce nombres de pelicula</label> <br>
|
||||||
|
<input type="text" name="nombrePelicula[]" id="nombre1"><br>
|
||||||
|
<input type="text" name="nombrePelicula[]" id="nombre2"><br>
|
||||||
|
<input type="text" name="nombrePelicula[]" id="nombre3"><br>
|
||||||
|
<input type="text" name="nombrePelicula[]" id="nombre4"><br>
|
||||||
|
<input type="text" name="nombrePelicula[]" id="nombre5"><br>
|
||||||
|
<input type="submit" value="Enviar"><br>
|
||||||
|
</form>
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
if (isset($_POST["nombrePelicula"])) {
|
||||||
|
$peliculas = $_POST["nombrePelicula"];
|
||||||
|
echo "<table border='2'>";
|
||||||
|
echo "<tr><td>Posicion</td><td>Nombre pelicula</td></tr>";
|
||||||
|
foreach ($peliculas as $index => $pelicula) {
|
||||||
|
$index=$index+1;
|
||||||
|
echo "<tr>";
|
||||||
|
echo "<td>$index</td>";
|
||||||
|
echo "<td>$pelicula</td>";
|
||||||
|
echo "</tr>";
|
||||||
|
}
|
||||||
|
echo "</table>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
49
Practicas/Practicas_PHP/ejercicios/Ejercicio6V2_04.php
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Ejercicio6v2_04</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$nombre_archivo = "formularios/registro.txt";
|
||||||
|
$contenido = file_get_contents($nombre_archivo);
|
||||||
|
|
||||||
|
$lineas = array();
|
||||||
|
$archivo = fopen($nombre_archivo, 'r');
|
||||||
|
|
||||||
|
while (($linea = fgets($archivo)) !== false) {
|
||||||
|
$lineas[] = $linea;
|
||||||
|
}
|
||||||
|
|
||||||
|
fclose($archivo);
|
||||||
|
|
||||||
|
echo '<table border="2">
|
||||||
|
<tr>
|
||||||
|
<th># Index</th>
|
||||||
|
<th>Nombre</th>
|
||||||
|
<th>Email</th>
|
||||||
|
<th>Ruta archivo</th>
|
||||||
|
</tr>
|
||||||
|
<tbody>';
|
||||||
|
foreach ($lineas as $index => $linea) {
|
||||||
|
$contenido_linea = explode("/_/", $linea);
|
||||||
|
echo '<tr>';
|
||||||
|
echo '<td>' . $index + 1 . '</td>';
|
||||||
|
foreach ($contenido_linea as $contenido) {
|
||||||
|
echo '<td>' . $contenido . '</td>';
|
||||||
|
}
|
||||||
|
echo '</tr>';
|
||||||
|
}
|
||||||
|
echo '</tbody>
|
||||||
|
</table>';
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
51
Practicas/Practicas_PHP/ejercicios/Ejercicio6_04.php
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Ejercicio6_04</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<form method="post" enctype="multipart/form-data">
|
||||||
|
<label for="nombre">Nombre: </label><input type="text" name="nombre" id="nombre" required> <br><br>
|
||||||
|
<label for="email">E-Mail: </label><input type="text" name="email" id="email" required> <br><br>
|
||||||
|
<label for="nif">NIF: </label><input type="file" name="nif" id="nif" accept=".jpg,.pdf" required> <br> <br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<a href="./Ejercicio6V2_04.php"> Ir a la vista de tabla</a>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["nif"])) {
|
||||||
|
|
||||||
|
$directorioDestino = 'uploads/';
|
||||||
|
|
||||||
|
$nombre = $_POST['nombre'];
|
||||||
|
$email = $_POST['email'];
|
||||||
|
$nombre_archivo = basename($_FILES["nif"]['name']);
|
||||||
|
$tipoArchivo = strtolower(pathinfo($nombre_archivo, PATHINFO_EXTENSION));
|
||||||
|
|
||||||
|
$tamanoArchivo = $_FILES["nif"]["size"];
|
||||||
|
$ext_permitidas = array("jpg", "pdf");
|
||||||
|
$tamanoMaximo = 5 * 1024 * 1024;
|
||||||
|
|
||||||
|
if ($tamanoArchivo <= $tamanoMaximo && in_array($tipoArchivo, $ext_permitidas)) {
|
||||||
|
$nombreUnico = time() . "_" . mt_rand(100, 999) . "_" . $email . "_" . $nombre_archivo;
|
||||||
|
$rutaArchivoDestino = $directorioDestino . $nombreUnico;
|
||||||
|
move_uploaded_file($_FILES["nif"]["tmp_name"], $rutaArchivoDestino);
|
||||||
|
|
||||||
|
$archivo="formularios/registro.txt";
|
||||||
|
$contenido=$nombre."/_/".$email."/_/".$rutaArchivoDestino."\r\n";
|
||||||
|
file_put_contents($archivo, $contenido,FILE_APPEND | LOCK_EX);
|
||||||
|
|
||||||
|
} else {
|
||||||
|
echo 'No se ha podido subir el fichero';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Formulario de Registro</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>Formulario de Registro</h2>
|
||||||
|
<form action="" method="post">
|
||||||
|
<label for="nombre">Nombre:</label>
|
||||||
|
<input type="text" id="nombre" name="nombre" required><br><br>
|
||||||
|
<label for="email">Correo Electrónico:</label>
|
||||||
|
<input type="email" id="email" name="email" required><br><br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
// Obtener los datos del formulario
|
||||||
|
$nombre = $_POST["nombre"];
|
||||||
|
$email = $_POST["email"];
|
||||||
|
|
||||||
|
// Abrir el archivo para escritura (modo append)
|
||||||
|
$archivo = fopen("usuarios.txt", "a");
|
||||||
|
|
||||||
|
// Escribir los datos en el archivo
|
||||||
|
fwrite($archivo,"$nombre - $email" . PHP_EOL);
|
||||||
|
|
||||||
|
// Cerrar el archivo
|
||||||
|
fclose($archivo);
|
||||||
|
|
||||||
|
echo "¡Datos guardados correctamente!";
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
<p></p>
|
||||||
|
<h2>Pulsa el enlace para ver la tabla de usuarios</h2>
|
||||||
|
<a href="leer_usuarios.php">Tabla de usuarios</a>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
33
Practicas/Practicas_PHP/ejercicios/Ejercicio7_04.php
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Ejercicio7_04</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<form method="post" enctype="multipart/form-data">
|
||||||
|
<label for="nombre">Nombre: </label><input type="text" name="nombre" id="nombre" required> <br><br>
|
||||||
|
<label for="email">E-Mail: </label><input type="text" name="email" id="email" required> <br><br>
|
||||||
|
<input type="submit" value="Enviar">
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<a href="./Ejercicio7_04_Tabla.php">Tabla de usuarios introducidos</a>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST") {
|
||||||
|
$nombre = $_POST['nombre'];
|
||||||
|
$email = $_POST['email'];
|
||||||
|
|
||||||
|
$nombre_archivo = "formularios/usuarios.txt";
|
||||||
|
$archivo = fopen($nombre_archivo, 'a');
|
||||||
|
fwrite($archivo, $nombre . " - " . $email . PHP_EOL);
|
||||||
|
fclose($archivo);
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
48
Practicas/Practicas_PHP/ejercicios/Ejercicio7_04_Tabla.php
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Ejercicio7_04_Tabla</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$nombre_archivo = "formularios/usuarios.txt";
|
||||||
|
$contenido = file_get_contents($nombre_archivo);
|
||||||
|
|
||||||
|
$lineas = array();
|
||||||
|
$archivo = fopen($nombre_archivo, 'r');
|
||||||
|
|
||||||
|
while (($linea = fgets($archivo)) !== false) {
|
||||||
|
$lineas[] = $linea;
|
||||||
|
}
|
||||||
|
|
||||||
|
fclose($archivo);
|
||||||
|
|
||||||
|
echo '<table border="2">
|
||||||
|
<tr>
|
||||||
|
<th># Index</th>
|
||||||
|
<th>Nombre</th>
|
||||||
|
<th>Email</th>
|
||||||
|
</tr>
|
||||||
|
<tbody>';
|
||||||
|
foreach ($lineas as $index => $linea) {
|
||||||
|
$contenido_linea = explode(" - ", $linea);
|
||||||
|
echo '<tr>';
|
||||||
|
echo '<td>' . $index + 1 . '</td>';
|
||||||
|
foreach ($contenido_linea as $contenido) {
|
||||||
|
echo '<td>' . $contenido . '</td>';
|
||||||
|
}
|
||||||
|
echo '</tr>';
|
||||||
|
}
|
||||||
|
echo '</tbody>
|
||||||
|
</table>';
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 3.3 MiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 255 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 64 KiB |
158
Practicas/Practicas_PHP/ejercicios/Plantilla Examen/busqueda.php
Executable file
@@ -0,0 +1,158 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<?php
|
||||||
|
echo $_COOKIE['tema'] === 'claro' ? '<link rel="stylesheet" type="text/css" href="estilos_claro.css" />'
|
||||||
|
: '<link rel="stylesheet" type="text/css" href="estilos.css" />' ?>
|
||||||
|
<title>Busqueda y eliminacion de registros</title>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
session_start();
|
||||||
|
$nombre_usuario = $_SESSION['nombre'];
|
||||||
|
$tipo_usuario = $_SESSION['tipo'];
|
||||||
|
echo "<div>
|
||||||
|
<h2>Bienvenido $nombre_usuario </h2>
|
||||||
|
<a href=\"logout.php\">Cerrar session</a>
|
||||||
|
</div>"
|
||||||
|
?>
|
||||||
|
|
||||||
|
<form method="post">
|
||||||
|
<p>*Término a buscar: </p>
|
||||||
|
<p><input type="text" name="termBusqueda" id="termBusqueda" size="30" placeholder="Introduzca la palabra de Busqueda" required></p>
|
||||||
|
<input type="submit" name="buscar" value="Buscar">
|
||||||
|
</form>
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
include_once('caracteres.php');
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['buscar'])) {
|
||||||
|
$termBusqueda = isset($_POST['termBusqueda']) ? $_POST['termBusqueda'] : '';
|
||||||
|
$termBusqueda !== "" ? busqueda($termBusqueda) : null;
|
||||||
|
unset($_POST);
|
||||||
|
}
|
||||||
|
|
||||||
|
function busqueda($termBusqueda)
|
||||||
|
{
|
||||||
|
$termBusqueda = eliminar_tildes(strtolower($termBusqueda));
|
||||||
|
$nombre_archivo = "listado_reservas.txt";
|
||||||
|
$registros = [];
|
||||||
|
$archivo = fopen($nombre_archivo, 'r');
|
||||||
|
|
||||||
|
while (($linea = fgets($archivo)) !== false) {
|
||||||
|
if (strpos(eliminar_tildes(strtolower($linea)), $termBusqueda) !== false) {
|
||||||
|
$registros[] = $linea;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fclose($archivo);
|
||||||
|
|
||||||
|
if (count($registros) > 0) {
|
||||||
|
echo "<table>
|
||||||
|
<tbody>
|
||||||
|
<thead>
|
||||||
|
<th>Id Reserva</th>
|
||||||
|
<th>Nombre</th>
|
||||||
|
<th>Email</th>
|
||||||
|
<th>Nº Telefono</th>
|
||||||
|
<th>Fecha de entrada</th>
|
||||||
|
<th>Fecha de salida</th>
|
||||||
|
<th>Fecha de registro</th>
|
||||||
|
<th>Nº de noches</th>
|
||||||
|
<th>Acciones</th>
|
||||||
|
</thead>";
|
||||||
|
foreach ($registros as $registro) {
|
||||||
|
$campos = explode("/_/", $registro);
|
||||||
|
echo "<tr>";
|
||||||
|
foreach ($campos as $campo) {
|
||||||
|
echo "<td> $campo </td>";
|
||||||
|
}
|
||||||
|
echo "<td>" . genButtonDel($campos[0]) . "</td>";
|
||||||
|
echo "</tr>";
|
||||||
|
}
|
||||||
|
echo "</tbody>";
|
||||||
|
echo "</table>";
|
||||||
|
} else {
|
||||||
|
echo "<div><h4> No se han encontrado registros con los terminos indicados </h4></div>";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function genButtonDel($idReserva)
|
||||||
|
{
|
||||||
|
return "<form method=\"POST\" style=\"border: none; padding:0.2rem; min-width: auto; margin:0\">
|
||||||
|
<input type=\"hidden\" name=\"idReserva\" value=\"$idReserva\" style=\"border: none; padding:0; min-width: auto; margin:0\">
|
||||||
|
<input type=\"submit\" name=\"borrar\" value=\"Eliminar\" style=\"cursor: pointer; padding:0.2rem 0.4rem; min-width: auto; margin:0\">
|
||||||
|
</form>";
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
|
<form method="post">
|
||||||
|
<p>*ID de reserva para borrar: </p>
|
||||||
|
<input type="text" name="idReserva" value="" id="idReserva" size="15" minlength="15" maxlength="15" placeholder="Id de reserva" />
|
||||||
|
<input type="submit" name="borrar" value="Borrar reserva de alquiler">
|
||||||
|
</form>
|
||||||
|
<br>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['borrar'])) {
|
||||||
|
$idReserva = isset($_POST['idReserva']) ? $_POST['idReserva'] : '';
|
||||||
|
if ($idReserva !== "") {
|
||||||
|
echo "<div>";
|
||||||
|
echo "<h4>Actuaciones sobre el registro: $idReserva</h4> <br>";
|
||||||
|
echo eliminaDeLista($idReserva) ?
|
||||||
|
"<p>Se ha encontrado el registro en el archivo y se ha eliminado</p>" :
|
||||||
|
"<p>No se encontro el registro especificado en el archivo</p>";
|
||||||
|
echo eliminaRegistro($idReserva) ?
|
||||||
|
"<p>Se ha eliminado correctamente el registro de reserva</p>" :
|
||||||
|
"No se ha encontrado el registro de reserva especificado</p>";
|
||||||
|
echo eliminaUpload($idReserva) ?
|
||||||
|
"<p>Se ha eliminado el documento almacenado con el registro</p>" :
|
||||||
|
"<p>No se ha encontrado documentos asociados al registro</p>";
|
||||||
|
echo "</div>";
|
||||||
|
}
|
||||||
|
unset($_POST);
|
||||||
|
}
|
||||||
|
|
||||||
|
function eliminaDeLista($idReserva)
|
||||||
|
{
|
||||||
|
$nombre_archivo = "listado_reservas.txt";
|
||||||
|
$flagEncontrado = false;
|
||||||
|
$registros = [];
|
||||||
|
$archivo = fopen($nombre_archivo, 'r');
|
||||||
|
|
||||||
|
while (($linea = fgets($archivo)) !== false) {
|
||||||
|
if (strpos($linea, $idReserva) === false) {
|
||||||
|
$registros[] = $linea;
|
||||||
|
} else {
|
||||||
|
$flagEncontrado = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fclose($archivo);
|
||||||
|
return ($flagEncontrado && file_put_contents($nombre_archivo, $registros));
|
||||||
|
}
|
||||||
|
|
||||||
|
function eliminaRegistro($idReserva)
|
||||||
|
{
|
||||||
|
$dir_reservas = "reservas/";
|
||||||
|
$nombre_archivo = "$idReserva.txt";
|
||||||
|
return file_exists($dir_reservas . $nombre_archivo) ?
|
||||||
|
unlink($dir_reservas . $nombre_archivo) :
|
||||||
|
false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function eliminaUpload($idReserva)
|
||||||
|
{
|
||||||
|
$dir_uploads = "dni_clientes/";
|
||||||
|
$file = glob($dir_uploads . "*" . $idReserva . "*");
|
||||||
|
return (count($file) > 0) ? unlink($file[0]) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
?>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||