Hola a todos de nuevo.
En un artículo muy reciente (ir al articulo) hemos visto una solución para validar el tipo de archivo y su peso en Dropzone.js, a partir de la configuración inicial.
A quedado patente la dificultad de acceder al objeto file.width y file.heigth en esta librería y os propongo una solución para validar el ancho y alto de una imagen.
A partir de la configuración inicial, igual que en el otro ejemplo, realizaremos unas pequeñas modificaciones para conseguir esta validación.
Vamos:
/* Esta es la configuration inicial:
accept: function(file, done) {
return done();
},
init: function() {
return noop;
}, */
// Y esta es la nueva configuración:
accept: function(file, done) {
sábado, 16 de mayo de 2020
sábado, 9 de mayo de 2020
JS DOS METODOS PARA VALIDAR EXTENSION DE ARCHIVO
PARTIMOS DE UNA ARRAY EN EL QUE INCLUIMOS LAS EXTENSIONES PERMITIDAS.
Primero recupero la extensión del archivo:
var archivo = $("#uploadImage").val(); // o file.name
//RECUPERO LA EXTENSION DEL ARCHIVO
var ext = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
Método 1º por medio de un for recorremos el array:
ext_ok = new Array(".gif", ".jpg", ".png", ".jpeg", ".mkv", ".mp4", ".avi", ".webm");
//COMPRUEBO SI LA EXTENSION ESTA PERMITIDA
permitida = "";
for (var i = 0; i < ext_ok.length; i++) {
if (ext_ok[i] == ext) { permitida = "yes";
break;
}else {permitida = "no";}
} // FIN for
Primero recupero la extensión del archivo:
var archivo = $("#uploadImage").val(); // o file.name
//RECUPERO LA EXTENSION DEL ARCHIVO
var ext = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
Método 1º por medio de un for recorremos el array:
ext_ok = new Array(".gif", ".jpg", ".png", ".jpeg", ".mkv", ".mp4", ".avi", ".webm");
//COMPRUEBO SI LA EXTENSION ESTA PERMITIDA
permitida = "";
for (var i = 0; i < ext_ok.length; i++) {
if (ext_ok[i] == ext) { permitida = "yes";
break;
}else {permitida = "no";}
} // FIN for
PHP REDUCIR IMAGEN
Mediante este simple script logro la reducción de la imagen.
Lo puedo aplicar comprobando la altura o el ancho de la imagen, nos serviría en los dos casos.
$ancho y $alto son los valores reales de la imagen.
$ext la extensión de la misma.
Nos servira si la imagen es jpg, png, jpeg.
Los valores de la imagen los obtengo de la siguiente manera:
global $ancho;
global $alto;
list($ancho, $alto, $tipo, $atributos) = getimagesize("temp/img.".$_SESSION['imgext']);
global $anchomax;
$anchomax = 900;
global $altomax;
$altomax = 900;
Lo puedo aplicar comprobando la altura o el ancho de la imagen, nos serviría en los dos casos.
$ancho y $alto son los valores reales de la imagen.
$ext la extensión de la misma.
Nos servira si la imagen es jpg, png, jpeg.
Los valores de la imagen los obtengo de la siguiente manera:
global $ancho;
global $alto;
list($ancho, $alto, $tipo, $atributos) = getimagesize("temp/img.".$_SESSION['imgext']);
global $anchomax;
$anchomax = 900;
global $altomax;
$altomax = 900;
DROPZONE JS VALIDACIONES EXTRA
En este artículo os comentaré como he ampliado las validaciones de dropzone js de una forma sencilla:
En este otro artículo (ir al artículo) os explico como validar el ancho y alto de una imágen, por medio de los objetos file.width y file.heigth.
Partiendo de la configuración inicial en:
This is an original option:
accept: function(file, done) {
return done();
},
init: function() {
return noop;
},
He integrado alguna validación muy fácil de modificar y que nos retorna los errores en pantalla sin problema:
accept: function(file, done) {
ext_img = new Array(".jpg", ".png", "jpeg");
var namei = file.name;
var exti = (namei.substring(namei.lastIndexOf("."))).toLowerCase();
En este otro artículo (ir al artículo) os explico como validar el ancho y alto de una imágen, por medio de los objetos file.width y file.heigth.
Partiendo de la configuración inicial en:
This is an original option:
accept: function(file, done) {
return done();
},
init: function() {
return noop;
},
He integrado alguna validación muy fácil de modificar y que nos retorna los errores en pantalla sin problema:
accept: function(file, done) {
ext_img = new Array(".jpg", ".png", "jpeg");
var namei = file.name;
var exti = (namei.substring(namei.lastIndexOf("."))).toLowerCase();
Etiquetas:
Dropzone js,
JAVA SCRIPT,
Js,
Web
DROPZONE JS CONFIGURACION BASICA
Hola a todos en este post voy a compartir con vosotros las configuaciones básicas de dropzone js y los comentarios sobre ellas.
En otro atriculo os comentaré como he integrado algunas balidaciones extra según el tipo de archivo y su peso.
/* url: defines the target for the upload form, and is the only required parameter.
That said, if you’re attaching it to a form element then it’ll simply use the form’s action attribute, in which case you don’t even need to specify that. */
url: null,
// method: sets the HTTP method and again, it’ll simply default to POST
method: "post",
withCredentials: false,
En otro atriculo os comentaré como he integrado algunas balidaciones extra según el tipo de archivo y su peso.
/* url: defines the target for the upload form, and is the only required parameter.
That said, if you’re attaching it to a form element then it’ll simply use the form’s action attribute, in which case you don’t even need to specify that. */
url: null,
// method: sets the HTTP method and again, it’ll simply default to POST
method: "post",
withCredentials: false,
Etiquetas:
Dropzone js,
JAVA SCRIPT,
Js,
Web
lunes, 20 de abril de 2020
Php Mysql borrar tablas en cascada
Veremos en este post, como poder borrar las tablas de un usuario mediante una función de php.
Si pasamos el script tras comprobar que el query que borra el usuario se cumple, no tendrémos problemas en caso de que este no se haya borrado en la tabla de usuarios.
Vemos también como se pasan unos parámetros a los log y los datos se ecriben en cascada, según las tablas que ha detectado.
Espero que os seá muy útil.
/************* BORRAMOS TODAS LAS TABLAS DE USUARIO ***************/
/* Se busca las tablas en la base de datos */
/* REFERENCIA DEL USUARIO O $_SESSION['iniref'] = $_POST['ref'] */
/* $nom PARA LA CLAVE USUARIO ACOMPAÑANDA DE _ O NO */
global $db;
global $db_name;
global $nom;
$nom = strtolower($_POST['ref']);
$nom = "clb_".$_POST['ref']."%"; // SOLO COINCIDEN AL PRINCIPIO
$nom = "LIKE '$nom'";
//$consulta = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME $nom ";
$consulta = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db_name' AND TABLE_NAME $nom ";
$respuesta = mysqli_query($db, $consulta);
//$count = mysqli_num_rows($respuesta);
//print("* NUMERO TABLAS: ".$count."<br>");
//print("* CLAVE TABLA USUARIO: ".$nom."<br>");
Si pasamos el script tras comprobar que el query que borra el usuario se cumple, no tendrémos problemas en caso de que este no se haya borrado en la tabla de usuarios.
Vemos también como se pasan unos parámetros a los log y los datos se ecriben en cascada, según las tablas que ha detectado.
Espero que os seá muy útil.
/************* BORRAMOS TODAS LAS TABLAS DE USUARIO ***************/
/* Se busca las tablas en la base de datos */
/* REFERENCIA DEL USUARIO O $_SESSION['iniref'] = $_POST['ref'] */
/* $nom PARA LA CLAVE USUARIO ACOMPAÑANDA DE _ O NO */
global $db;
global $db_name;
global $nom;
$nom = strtolower($_POST['ref']);
$nom = "clb_".$_POST['ref']."%"; // SOLO COINCIDEN AL PRINCIPIO
$nom = "LIKE '$nom'";
//$consulta = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME $nom ";
$consulta = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db_name' AND TABLE_NAME $nom ";
$respuesta = mysqli_query($db, $consulta);
//$count = mysqli_num_rows($respuesta);
//print("* NUMERO TABLAS: ".$count."<br>");
//print("* CLAVE TABLA USUARIO: ".$nom."<br>");
Etiquetas:
PHP8.1,
PHPMYADMIN,
Programas Php,
XHTML / HTML
Php conocer navegador web del usuario
Hoy os dejo una forma sencilla de poder detectar el navegador web del usuario y poder presentar distintos parametros en base a ese dato.
Espero que os ayude.
// DETERMINO EL NAVEGADOR WEB Y PASO EL MENU ADECUADO
global $user_agent;
$user_agent = $_SERVER['HTTP_USER_AGENT'];
//getBrowser($user_agent);
$_SESSION['menu'] = getBrowser($user_agent);
function getBrowser($user_agent){
if(strpos($user_agent, 'MSIE') !== FALSE){
//return 'Internet explorer';
return "Inclu_MInd_b";
}elseif(strpos($user_agent, 'Edge') !== FALSE){ //Microsoft Edge
//return 'Microsoft Edge';
return "Inclu_MInd_b";
Espero que os ayude.
// DETERMINO EL NAVEGADOR WEB Y PASO EL MENU ADECUADO
global $user_agent;
$user_agent = $_SERVER['HTTP_USER_AGENT'];
//getBrowser($user_agent);
$_SESSION['menu'] = getBrowser($user_agent);
function getBrowser($user_agent){
if(strpos($user_agent, 'MSIE') !== FALSE){
//return 'Internet explorer';
return "Inclu_MInd_b";
}elseif(strpos($user_agent, 'Edge') !== FALSE){ //Microsoft Edge
//return 'Microsoft Edge';
return "Inclu_MInd_b";
Etiquetas:
PHP8.1,
Programas Php,
XHTML / HTML
martes, 10 de marzo de 2020
Descarga Plantillas Excel y Word Gratis
Aquí os dejo algunas plantillas de Excel que os serán muy útiles, van desde el seguimiento del ejercicio diario que realizáis, pasando por contabilidad doméstica, hasta facturación de actividad y cálculo financiero o balances de la actividad.
Recordad que en Google Drive las plantillas de Excel en ocasiones no se visualizan correctamente, pero están ok.
Espero que os sean muy útiles.
Dudas y sugerencias: JuanBarrosPazos@hotmail.es
PLANTILLAS PROPIAS:
- Plantillas Alquileres Inmobiliarios.
- Ejemplo de lista condicional y filtros avanzados en varias columnas
- Plantilla_Ejercicio_Anual.xls
- Plantilla_Ejercicio_Inter_Anual.xlsx
- Plantilla_Gastos_Domesticos_Anual.xls
Recordad que en Google Drive las plantillas de Excel en ocasiones no se visualizan correctamente, pero están ok.
Espero que os sean muy útiles.
Dudas y sugerencias: JuanBarrosPazos@hotmail.es
PLANTILLAS PROPIAS:
- Plantillas Alquileres Inmobiliarios.
- Ejemplo de lista condicional y filtros avanzados en varias columnas
- Plantilla_Ejercicio_Anual.xls
- Plantilla_Ejercicio_Inter_Anual.xlsx
- Plantilla_Gastos_Domesticos_Anual.xls
Etiquetas:
DESCARGAS,
EXCEL,
PLANTILLA CONTABLE,
PLANTILLA FISCAL,
PLANTILLAS EXCEL,
PLANTILLAS WORD
viernes, 31 de enero de 2020
Php sumar tiempos totales
La locura del registro del horario.
Unas lineas de código para poder sumar todos los tiempos totales:
/* TOTALES HORAS MINUTOS Y SEGUNDOS DE LA CONSULTA*/
$sh = "SELECT * FROM $vname WHERE `din` LIKE '$fil' AND `ttot` <> 'xxx' ORDER BY $orden ";
/* CALCULAMOS LAS HORAS TOTALES Y LAS PASAMOS A SEGUNDOS. */
if(!$sh){print(mysqli_error($db).".</br>");
}
else{
$qh = mysqli_query($db, $sh);
$qhr = mysqli_num_rows($qh);
$sumah = 0;
for($i=0; $i<$qhr; $i++){
$verh = mysqli_fetch_array($qh);
$verh = substr($verh['ttot'],0,2).",";
$verh = str_replace(":","",$verh);
global $sumah;
$sumah = $sumah + $verh;
}
}
$hortosec = $sumah * 3600;
//print ("</br>".$sumah);
//print ("</br>".$hortosec);
Unas lineas de código para poder sumar todos los tiempos totales:
/* TOTALES HORAS MINUTOS Y SEGUNDOS DE LA CONSULTA*/
$sh = "SELECT * FROM $vname WHERE `din` LIKE '$fil' AND `ttot` <> 'xxx' ORDER BY $orden ";
/* CALCULAMOS LAS HORAS TOTALES Y LAS PASAMOS A SEGUNDOS. */
if(!$sh){print(mysqli_error($db).".</br>");
}
else{
$qh = mysqli_query($db, $sh);
$qhr = mysqli_num_rows($qh);
$sumah = 0;
for($i=0; $i<$qhr; $i++){
$verh = mysqli_fetch_array($qh);
$verh = substr($verh['ttot'],0,2).",";
$verh = str_replace(":","",$verh);
global $sumah;
$sumah = $sumah + $verh;
}
}
$hortosec = $sumah * 3600;
//print ("</br>".$sumah);
//print ("</br>".$hortosec);
Php Calcular la diferencia entre la entrada y la salida
Con este sencillo script podremos calculas la diferencia entre dos fechas distintas.
$fecha1 = new DateTime($in);//fecha inicial
$fecha2 = new DateTime($out);//fecha de cierre
global $difer;
$difer = $fecha1->diff($fecha2);
//print ($difer);
global $ttot;
$ttot = $difer->format('%H:%i:%s');
$fecha1 = new DateTime($in);//fecha inicial
$fecha2 = new DateTime($out);//fecha de cierre
global $difer;
$difer = $fecha1->diff($fecha2);
//print ($difer);
global $ttot;
$ttot = $difer->format('%H:%i:%s');
Php foreach array tridimensional asociativo
En este ejemplo podemos ver como anidando varios foreach podremos recorrer un array asociativo tridimensional, de forma sencilla.
<?php
$niveles
=
array
(
'Primaria'
=>
array
(
'1º'
,
'2º'
,
'3º'
,
'4º'
,
'5º'
,
'6º'
),
'Secundaria'
=>
array
(
'Primer Ciclo'
=>
array
(
'1º Eso'
,
'2º Eso'
),
'Segundo Ciclo'
=>
array
(
'3º Eso'
,
'4º Eso'
)),
'Fp'
=>
array
(
'Grado Medio'
=>
array
(
'Artes gráficas'
=>
array
(
'Impresión'
,
'Post impresión y acabados gráficos'
),
'Comercio y Marqueting'
=>
array
(
'Actividades comerciales'
),
'Imagen y sonido'
=>
array
(
'Vídeo Disc-Jockey y Sonido'
),
'Informática y Comunicaciones'
=>
array
(
'Sistemas Microinformáticos y Redes'
)),
'Grado Superior'
=>
array
(
'Edificación Obra Civil'
=>
array
(
'Diseño y Amueblamiento'
),
'Electricidad Electrónica'
=>
array
(
'Eficiencia Energética y Energ. Solar Térmica'
),
'Hostelería Turismo'
=>
array
(
'Dirección de Servicios de Restauración'
),
'Informatica y Comunicaciones'
=>
array
(
'Desarrollo de Aplicaciones Multiplataforma'
,
'Desarrollo de Aplicaciones Web'
)))
);
foreach
(
$niveles
as
$nivel
=>
$nombre
){
Php foreach while en array bidimensional asociativo
Aqui podemos ver dos ejemplos de como recorrer un array bidimensional asociativo.
1. Foreach anidado.
2. Select co un while.
/////////////
1.
/* INICIO CIUDADES BARRIOS CON FOREACH */
$barrios
=
array
(
"Palma"
=>
array
(
"Barrio PM01 | CP: PM01"
,
"Barrio PM02 | CP: PM02"
,
"Barrio PM03 | CP: PM03"
,
"Barrio PM04 | CP: PM04"
,
"Barrio PM05 | CP: PM05"
,
"Barrio PM06 | CP: PM06"
),
Php tablas de multiplicar dividir sumar y restar
Con estas sencillas funciones podemos crear las tablas de sumar, restar, multiplicar y dividir.
<?php
multiplicar();
dividir();
sumar();
restar();
function
multiplicar(){
$ini
= 1;
$fin
= 12;
echo
'<div style=
"float:left;margin: 4px;padding: 4px;border:1px solid #000"
>
<div>TABLA DE MULTIPLICAR DESDE
'.$ini.'
HASTA
'.$fin.'
</div>';
for
(
$cuenta
=
$ini
;
$cuenta
<=
$fin
;
$cuenta
++){
echo
'<div style="float:left;margin: 4px;padding: 4px;border:1px solid #000">POR '
.
$cuenta
.
'<br/>'
;
for
(
$i
=1;
$i
<=10;
$i
++){
if
(
$i
<10){
$i
=
'0'
.
$i
;}
else
{}
global
$tot
;
$tot
=
$i
*
$cuenta
;
if
((
$tot
>=10)&&(
$tot
<100)&&(
$cuenta
>=10)){
$tot
=
' '
.
$tot
;}
if
((
$tot
<10)&&(
$cuenta
<=10)){
$tot
=
' '
.
$tot
;}
else
{}
Php funcion calcular numero primo
Hola a todos, con esta función podremos calcular de forma sencilla si un número es primo.
Sólo hemos de sustituir el valor de la variable valor por el número que deseamos saber si es primo o no.
Sólo hemos de sustituir el valor de la variable valor por el número que deseamos saber si es primo o no.
<?php
juan();
function
juan()
{
// valoe del número a calcular.
$valor
= 9967;
$primo
= 0;
/* SI NO ES NUMERICO */
if
(!
is_numeric
(
$valor
)){
echo
"* EL CARACTER: \"<b>"
.
$valor
.
"\" <i>NO ES UN VALOR NUMÉRICO ADMITIDO</i>.</b><br/>"
;
}
/* SI ES NUMERICO DECIMAL */
elseif
(!
is_int
(
$valor
)){
echo
"* EL NÚMERO: \"<b>"
.
$valor
.
"\" <i>ES UN DECIMAL NO ADMITIDO</i>.</b><br/>"
;
}
/* SI ES UN NEGATIVO NO ES ADMITIDO */
elseif
(
$valor
< 0){
echo
"* EL CARACTER: \"<b>"
.
$valor
.
"\" <i>ES UN NÚMERO NEGATIVO NO ADMITIDO</i>.</b><br/>"
;
Suscribirse a:
Entradas (Atom)