[PHP] Convertir caracteres UTF-8 con PHP

Funciones PHP para convertir caracteres UTF-8 y que se vean bien los acentos y otras letras del alfabeto latino. Función decode UTF8 PHP.

En ocasiones los textos de la página web pueden contener caracteres raros en lugar de acentos u otras letras propias del idioma español, como la ñ o las letras con diéresis y de otros idiomas latinos. Esto suele ocurrir en casos en que la base de datos trabaje en un juego de caracteres distinto que la página, o que los datos estén mal cargados en la misma. Generalmente estos errores surgen por un tratamiento inadecuado del juego de caracteres UTF-8, que no están procesados como UTF-8, sino como si fueran ISO-8859-1. Con PHP podemos decodificar esos caracteres para que a la hora de mostrar los textos en la página aparezcan correctamente. Para ello existen una funciones que vamos a comentar en este artículo de DesarrolloWeb.com.

Cuando vemos incorrectamente un texto nos pueden aparecer textos como estos:

Solución útil y apañada a UTF-8

Este texto tiene caracteres codificados en UTF8, que debemos decodificar para que aparezcan correctamente los acentos y demás símbolos del alfabeto latino.

Decodificar una cadena UTF-8 con PHP – decode utf8 php

Existe una función de PHP que realiza el trabajo de conversión de los caracteres UTF8 a sus correspondientes códigos reales.

La función se llama utf8_decode() y lo que hace es convertir una cadena que realmente utiliza ISO-8859-1 pero que tiene caracteres codificados a con UTF-8. La conversión genera el string en ISO-8859-1 pero con un sólo byte para todos los caracteres, con lo que se verán correctamente.

Se utiliza así:

utf8_decode(“Solución útil y apañada a UTF-8”);

Devolverá una cadena el texto correctamente escrito:

Solución útil y apañada a UTF-8

Codificar una cadena al juego de caracteres UTF-8 – encode utf8 php

Existe una función para hacer justo el paso contrario, que vamos a ver también en desarrollo web .com. Es decir, partiendo de una cadena en el juego de caracteres ISO-8859-1, obtener la correspondiente traducción a UTF-8.

Esto lo podemos necesitar, por ejemplo, si nuestra base de datos está definida con UTF-8 y tenemos entrada de datos ISO-8859-1.

El uso es bien simple:

echo utf8_encode(“Mañanas de programación PHP”);

Y devolverá el correspondiente string convertido a UTF-8, que si lo mostramos en una página que utiliza el juego de caracteres ISO-8859-1, se vería de esta manera:

Mañanas de programación PHP

Impactos: 0

How can I create a child theme in Prestashop

image.png

First of all, you need to have an installed theme on your store(root/themes folder) that will be used as a parent for your child theme. Create a new folder in /themes folder( For example: childtheme) copy below files from parent theme folder to child theme folder

 ├── config  │   └── theme.yml  └── preview.png 

open theme.yml file of child theme and specify which theme should be used as a parent.

parent: classic name: childtheme display_name: My first child Theme version: 1.0.0 assets:   use_parent_assets: true 

Now go to back office where you can see a new child theme will appear and you are all set.

Impactos: 0

Módulo para borrar cache de forma automática.

image.png
Hoy te mostraré cómo borrar el caché mediante programación en PrestaShop. Por ejemplo, puede realizar una tarea CRON que ejecutará este pequeño script PHP una o más veces al día, según sus necesidades.
1. Create PHP file in your store root (main) directory and name it as you wish – in this example it’ll be cache_clear.php
2. Open this file and paste

include('./config/config.inc.php');

$token = Tools::getValue('token');

if($token == “vBnmmP3218”) {
    Tools::clearSmartyCache();
    Tools::clearXMLCache();
    Media::clearCache();
    Tools::generateIndex();
    echo “Cache clear ended successfully.”;
} else {
    echo “Wrong security token – cache clear failed.”;
}
3. Change the string vBnmmP3218 to your random one (stronger is more secure).
4. Save the file.
5. Add script URL to your CRON task manager or execute it directly via your browser in format: http://{your_store_url}/cache_clear.php?token=vBnmmP3218

For example: http://example.com/cache_clear.php?token=vBnmmP3218

Impactos: 0

¿Cómo evitar que un cron job me envíe un email cada vez que se ejecuta?

¿Cómo evitar que un cron job me envíe un email cada vez que se ejecuta?


1. Redirigir la salida

0   */2 *   *   *   /bin/sh /ruta/mi-script.sh >/dev/null 2>&1 

Esto lo que hace es redirigir la salida estándar y la salida de error al clásico colector de basura de unix /dev/null. Podrías eventualmente dejar la salida de error para que pase por el mail y desactivar solo la estándar:

0   */2 *   *   *   /bin/sh /ruta/mi-script.sh >/dev/null 

2. Quitar el MAILTO

Si tienes acceso a editar el archivo /etc/crontab puedes editar la variable MAILTO dejándola en blanco MAILTO=""

3. Configurar el demonio del cron para que la salida vaya a un log

Si puedes editar /etc/sysconfig/crond, podrías agregar el parámetro -s para redirigir la salida al log del sistema y -m off para deshabilitar el envío de mails

Ten en cuenta que las opciones 2 y 3 requieren reiniciar el demonio del cron.

Referencia: https://www.putorius.net/2015/03/stop-cron-daemon-from-sending-email-for.html

Impactos: 0

Habilite VNC en implementaciones de VMware

image.png

This article outlines the steps needed to enable VNC on VMware, so that the VNC console can be used within the Platform9 UI.
Step 1 – Changes Needed on the ESXi Hosts Housing the Virtual Machines

SSH to the ESXi host (not vCenter). We need to open the VNC ports on the ESXi firewall. These steps need to be performed on all the ESX hosts that are part of the clusters authorized with Platform9 controller. An automated script for doing same is coming soon.

chmod 644 /etc/vmware/firewall/service.xml
chmod +t /etc/vmware/firewall/service.xml
vi /etc/vmware/firewall/service.xml

Create a new service block before the end of ConfigRoot tag.

<service id=”new unique id within this file”>
<id>VNC</id>
<rule id=”0000″>
<direction>inbound</direction>
<protocol>tcp</protocol>
<porttype>dst</porttype>
<port>
<begin>5900</begin>
<end>6199</end>
</port>
</rule>
</service>

Step 2 – Add Firewall Rules to the ESXi Firewall and Verify that Ports Have Been Opened

On the ESXi host, execute the following commands

esxcli network firewall refresh
esxcli network firewall ruleset set –ruleset-id VNC –enabled true

Verify that the firewall rules were applied and the ports are open by executing the following commands

esxcli network firewall ruleset list
# You should see a rule labelled VNC in the output
esxcli network firewall ruleset rule list
# You should see the details of VNC rule i.e. port range, protocol, direction, etc.

Step 3 – Enable VNC for Existing Virtual Machines (Optional)

To enable VNC console for existing VMs, power off the VM and use one of the following:

Using vSphere Web Client
Click on “edit settings”-> Select the “VM Options” tab->Expand the “Advanced” section-> click on “Edit configuration” and add the settings mentioned at the end of this step
Directly on ESXi Host
Edit the *.vmx file of the corresponding VM and the lines mentioned here.

RemoteDisplay.vnc.enabled = “TRUE”
RemoteDisplay.vnc.port = “<port>” # Port between 5900 and 6199

IMPORTANT NOTES –
1. The key point in the step 3 is to make sure that the port number that you are adding does not collide with any other VM. One way to verify that is to SSH into the ESXi host and run grep on all the *.vmx files and choose a port that is not present in the output

grep “vnc.port” */*/*/*/*.vmx

2. For VNC console to work, the appliance, the ESX host, and the browser where the VNC is being accessed need to have IP connectivity to each other.

Fuente:
https://docs.platform9.com/support/enable-vnc-on-vmware-deployments/

#vmware, #Linux

 

Impactos: 0

Instalar docker en Ubuntu 20.x

image.png

Primero, actualice su lista de paquetes existente:

sudo apt update

A continuación, instale algunos paquetes de requisitos previos que permitan a apt usar paquetes a través de HTTPS:

sudo apt install apt-transport-https ca-certificates curl software-properties-common

Luego, añada la clave de GPG para el repositorio oficial de Docker en su sistema:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add –

Agregue el repositorio de Docker a las fuentes de APT:

sudo add-apt-repository “deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable”

A continuación, actualice el paquete de base de datos con los paquetes de Docker del repositorio recién agregado:

sudo apt update
Asegúrese de estar a punto de realizar la instalación desde el repositorio de Docker en lugar del repositorio predeterminado de Ubuntu:
apt-cache policy docker-ce

Si bien el número de versión de Docker puede ser distinto, verá un resultado como el siguiente:

Output of apt-cache policy docker-ce
docker-ce:
Installed: (none)
Candidate: 5:19.03.9~3-0~ubuntu-focal
Version table:
5:19.03.9~3-0~ubuntu-focal 500
500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages

Observe que docker-ce no está instalado, pero la opción más viable para la instalación es del repositorio de Docker para Ubuntu 20.04 (focal).

Por último, instale Docker:

sudo apt install docker-ce

Con esto, Docker quedará instalado, el demonio se iniciará y el proceso se habilitará para ejecutarse en el inicio. Compruebe que funcione:

sudo systemctl status docker

El resultado debe ser similar al siguiente, y mostrar que el servicio está activo y en ejecución:

Output
● docker.service – Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2020-05-19 17:00:41 UTC; 17s ago
TriggeredBy: ● docker.socket
Docs: https://docs.docker.com
Main PID: 24321 (dockerd)
Tasks: 8
Memory: 46.4M
CGroup: /system.slice/docker.service
└─24321 /usr/bin/dockerd -H fd:// –containerd=/run/containerd/containerd.sock

#docker #linux #Ubuntu

Impactos: 0

Omitir la verificación de memoria en un VMware ESXi 5

image.png
Omitir la verificación de memoria en un VMware ESXi 5
 
Pasos a seguir:

Boot the system from USB Stick with ESXi installer on it.
Once the installer welcome screen shows up, press ALT+F1
Login as “root”, no password.
cd /usr/lib/vmware/weasel/util
Delete upgrade_precheck .pyc (compiled version)
Move precheck.py to precheck.py.old
cp upgrade_precheck.py.old upgrade_precheck.py
chmod 666 upgrade_precheck.py
vi upgrade_precheck.py
Type “/MEM_MIN” and press ENTER
Press “i” for insert
Edit the line to read “MEM_MIN_SIZE= (1*1024–32)”
Press ESC and then type “:w” and ENTER
Press ESC and then type “:q!” and ENTER
ps -c | grep weasel
Note the process id for “python”
kill –9 /<process_id/>
This put me back at the main screen, but you can jump back pressing ALT+F2 if necessary
Continue the install process

 Referencia:
image.png

Impactos: 0

Montar y desmontar unidades USB

image.png
Utilidad para montar y desmontar unidades USB

Para montar unidad USB

C:\Windows\System32\mountvol.exe E:\ \\?\Volume{c5f4a6e7-86be-11e6-a604-806e6f6e6963}\

Para desmontar unidad USB

C:\Windows\System32\mountvol.exe E:\ /p

Para desconectar puerto USB

C:\Windows\System32\rundll32.exe shell32.dll,Control_RunDLL hotplug.dll


Impactos: 0

Copias de seguridad de MariaDB automatizadas

 

image.png

Primero instalar el cliente de mariadb

 

apt-get install -y mariadb-client

Crear el siguiente script y hacerlo ejecutable

#!/bin/bash
pcds=/var/opt/mariadb
cds=$pcds/copia_de_seguridad_$(date +%Y%m%dT%H.%M.%S).sql
mysqldump –all-databases –lock-tables > $cds
if [ $? -eq 0 ]
then
gzip $cds
limite=$(date +%Y%m%dT%H.%M.%S -d “-7 days”)
for i in $pcds/*.sql.gz
do
if [[ ${i:36:17} < $limite ]] && [[ -e $i ]]
then
rm $i
fi
done
else
if [[ -e $cds ]]
then
rm $cds
fi
source /root/.telegram_keysURL=https://api.telegram.org/bot$TOKEN/sendMessage
message=”No se ha podido hacer la copia de seguridad”
curl -s -X POST $URL -d chat_id=$CHANNEL -d text=”$message” >/dev/null 2>&1
fi

y en el crontab crear las siguientes líneas:

30 23 * * * /mnt/mydatabasebackupscript.sh
0 4 * * * find /var/log/ -name *.gz -mtime +7 -exec rm {} \;
0 4 * * * find /mnt/copia/ -name *.gz -mtime +7 -exec rm {} \;

 

Impactos: 0