viernes, 16 de marzo de 2018

Cómo usar FTP desde la linea de comandos

How do I use FTP from a command line?

Updated: 05/05/2017 by Computer Hope
Note: FTP is not an encrypted transmission, which means any data sent over it, including your username and password, could be read by anyone who may intercept your transmission. If you're wanting a more secure transmission, we suggest using SFTP.

Connect using FTP

To connect to another computer using FTP at the MS-DOS prompt, command line, or Linux shell type FTP and press Enter. Once in FTP, use the open command to connect to the FTP server, as shown in the example below.
open ftp.example.com
In the above example, you'd substitute example.com for the domain name or IP address of where you are connecting. An example would be open 192.168.1.12.
Note: By default, the open command uses the TCP port 21 to make the FTP connection. If a different TCP port is needed for connecting to the domain name or IP address you are using, enter the port number after the domain name or IP address in the open command.
Once connected, a username and password prompt will appear. Once these credentials have been entered, the server allows you to browse, send, or receive files, depending on your rights. Some servers may also allow anonymous logins using guest or an e-mail address.

Send and receive a file in FTP

To get files from the server onto your computer, use the get command as shown in the example below. In this example, you would get the file myfile.htm.
get myfile.htm
Tip: If you want to get more than one file, use mget and wildcards. For example, if you wanted to get all files that end with .htm, you could type mget *.htm. Finally, if you do not want to be prompted as each file is being sent, make sure to type prompt to disable prompting.
To send a file from your computer to the computer you are connected to, assuming you have the rights, use the send command as shown in the example below. In this example, we are sending the myfile.htm to the current directory.
send myfile.htm
It is important to realize that the files being sent must be in your local working directory, which is the directory you were in when you typed the FTP command. If you want to change to the directory that contains your files, use the lcd command. For example, in Windows, you'd type lcd c:\windows to set the local directory to the Windows directory.

FTP Commands

Depending upon the version of FTP and the operating system being used, each of the below commands may or may not work. Typing -help or a ? will list the commands available to you. Below is a general description of FTP commands available in the Windows command line FTP command.


CommandInformation
!This command toggles back and forth between the operating system and ftp. Once back in the operating system, typing exit takes you back to the FTP command line.
?Access the Help screen.
appendAppend text to a local file.
asciiSwitch to ASCII transfer mode
bellTurns bell mode on or off.
binarySwitches to binary transfer mode.
byeExits from FTP.
cdChanges directory.
closeExits from FTP.
deleteDeletes a file.
debugSets debugging on or off.
dirLists files if connected.

dir - C = Will list the files in wide format.
dir -1 = Lists the files in bare format in alphabetic order
dir -r = Lists directory in reverse alphabetic order.
dir -R = Lists all files in current directory and sub directories.
dir -S = Lists files in bare format in alphabetic order.
disconnectExits from FTP.
getGrabs file from the computer to which you are connected.
globSets globbing on or off. When turned off the file name in the put and get commands is taken literally and wildcards are not used.
hashSets hash mark printing on or off. When turned on for each 1024 bytes of data received a hash-mark (#) is displayed.
helpAccess the Help screen and displays information about command if command typed after help.
lcdDisplays local directory if typed alone or if path typed after lcd will change local directory.
literalSends a literal command to the connected computer with an expected one line response.
lsLists files of the remotely connected computer.
mdeleteMultiple delete.
mdirLists contents of multiple remote directories.
mgetGet multiple files.
mkdirMake directory.
mlsLists contents of multiple remote directories.
mputSent multiple files
openOpens address.
promptEnables or disables the prompt.
putSend one file
pwdPrint working directory
quitExits from FTP.
quoteSame as the literal command.
recvReceive file.
remotehelpGet help from remote server.
renameRenames a file.
rmdirRemoves a directory on the remote computer.
sendSend single file.
statusShows status of currently enabled and disabled options
traceToggles packet tracing.
TypeSet file transfer type.
userSend new user information.
verboseSets verbose on or off.
Fuente: https://www.computerhope.com/issues/ch001246.htm

miércoles, 14 de febrero de 2018

Propiedad Body vacía leyendo correos o emails con delphi e Indy

El motivo es porque el correo está codificado con encapsulación MIME-encoded text. Debebemos de leer el contenido que viene en varias partes y formar una cadena única

Ejemplo delphi:
---------------------------
nota: requiere el use TIdText;

for x := 0 to TheMsg.MessageParts.Count - 1 do begin 
      if TheMsg.MessageParts.Items[x] is TIdText then 
             BodyMsg := BodyMsg+ TIdText(TheMsg.MessageParts.Items[x]).Body.Text; 
end; 




TIdText

Encapsulates a MIME-encoded text message part. TIdText = class(TIdMessagePart) Class Hierarchy
TCollectionltem TIdMessagePart TIdText [CI
Unit
IdMessage [CI TIdText Members Properties
Body
Textual content of the message part. Methods
^Assign Create
Copy the property values of an object instance. Constructor for the collection item.
^ Destroy Frees the object instance.
Legend
^virtual

Description

TIdText is a TIdMessagePart [C] descendant that encapsulates a MIME textual message part. TldAttachment [C] and TIdText are Created with Doc-O-Matic 2 donated to Project JEDI. Commercial license available from the Doc-O-Matic site.
used as collection items in a TldMessageParts [C] collection.
TldText provides the Body [C] property to represent the textual content of the message part. See Also
TldMessagePart[C], Technical Support [CI
Textual content of the message part. property Body: TStrings; Description
Body is a TStrings property that represents the textual content of the MIME message part. Body will be populated with the values from a valid TStrings instance supplied in the Create [C] constructor. Body may also be updated using inherited properties and methods from TStrings, like Text and Add.
See Also
TldText.Create [C]
fuente: https://www.delphipower.xyz/indy9/tidtext.html

martes, 6 de febrero de 2018

Top 10 MySQL Mistakes Made By PHP Developers

Learn more on MySQL with our screencast MySQL on the Command Line.
A database is a fundamental component for most web applications. If you’re using PHP, you’re probably using MySQL–an integral part of the LAMP stack.
PHP is relatively easy and most new developers can write functional code within a few hours. However, building a solid, dependable database takes time and expertise. Here are ten of the worst MySQL mistakes I’ve made (some apply to any language/database)…

1. Using MyISAM rather than InnoDB

MySQL has a number of database engines, but you’re most likely to encounter MyISAM and InnoDB.

MyISAM is used by default. However, unless you’re creating a very simple or experimental database, it’s almost certainly the wrong choice! MyISAM doesn’t support foreign key constraints or transactions, which are essential for data integrity. In addition, the whole table is locked whenever a record is inserted or updated; this causes a detrimental effect on performance as usage grows.
The solution is simple: use InnoDB.

2. Using PHP’s mysql functions

PHP has provided MySQL library functions since day one (or near as makes no difference). Many applications rely on mysql_connect, mysql_query, mysql_fetch_assoc, etc. but the PHP manual states:
If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.
mysqli, or the MySQL improved extension, has several advantages:
  • an (optional) object-oriented interface
  • prepared statements (which help prevent SQL-injection attacks and increase performance)
  • multiple statements and transaction support
Alternatively, you should consider PDO if you want to support multiple databases.

3. Not sanitizing user input

This should probably be #1: never trust user input. Validate every string using server-side PHP — don’t rely on JavaScript. The simplest SQL injection attacks depend on code such as:

$username = $_POST["name"];
$password = $_POST["password"];
$sql = "SELECT userid FROM usertable WHERE username='$username' AND password='$password';";
// run query...
This can be cracked by entering “admin'; --” in the username field. The SQL string will equate to:

SELECT userid FROM usertable WHERE username='admin';
The devious cracker can log in as “admin”; they need not know the password because it’s commented out of the SQL.

4. Not using UTF-8

Those of us in the US, UK, and Australia rarely consider languages other than English. We happily complete our masterpiece only to find it cannot be used elsewhere.
UTF-8 solves many internationalization issues. Although it won’t be properly supported in PHP until version 6.0, there’s little to prevent you setting MySQL character sets to UTF-8.

5. Favoring PHP over SQL

When you’re new to MySQL, it’s tempting to solve problems in the language you know. That can lead to unnecessary and slower code. For example, rather than using MySQL’s native AVG() function, you use a PHP loop to calculate an average by summing all values in a record-set.
Watch out also for SQL queries within PHP loops. Normally, it’s more effective to run a query then loop through the results.
In general, utilize the strengths of your database when analyzing data. A little SQL knowledge goes a long way.

6. Not optimizing your queries

99% of PHP performance problems will be caused by the database, and a single bad SQL query can play havoc with your web application. MySQL’s EXPLAIN statement, the Query Profiler, and many other tools can help you find that rogue SELECT.

7. Using the wrong data types

MySQL offers a range of numeric, string, and time data types. If you’re storing a date, use a DATE or DATETIME field. Using an INTEGER or STRING can make SQL queries more complicated, if not impossible.
It’s often tempting to invent your own data formats; for example, storing serialized PHP objects in string. Database management may be easier, but MySQL will become a dumb data store and it may lead to problems later.

8. Using * in SELECT queries

Never use * to return all columns in a table–it’s lazy. You should only extract the data you need. Even if you require every field, your tables will inevitably change.

9. Under- or over-indexing

As a general rule of thumb, indexes should be applied to any column named in the WHERE clause of a SELECT query.
For example, assume we have a usertable with a numeric ID (the primary key) and an email address. During log on, MySQL must locate the correct ID by searching for an email. With an index, MySQL can use a fast search algorithm to locate the email almost instantly. Without an index, MySQL must check every record in sequence until the address is found.
It’s tempting to add indexes to every column, however, they are regenerated during every table INSERT or UPDATE. That can hit performance; only add indexes when necessary.

10. Forgetting to back up

It may be rare, but databases fail. Hard disks can stop. Servers can explode. Web hosts can go bankrupt. Losing your MySQL data is catastrophic, so ensure you have automated backups or replication in place.

11. Bonus mistake: not considering other databases!

MySQL may be the most widely used database for PHP developers, but it’s not the only option. PostgreSQL and Firebird are its closest competitors; both are open source and not controlled by a corporation. Microsoft provide SQL Server Express and Oracle supply 10g Express; both are free versions of the bigger enterprise editions. Even SQLite may be a viable alternative for smaller or embedded applications.
Have I missed your worst MySQL mistakes?
Learn more on MySQL with our screencast MySQL on the Command Line.
Fuente: https://www.sitepoint.com/mysql-mistakes-php-developers/

miércoles, 3 de enero de 2018

pop vs imap diferencias ventajas e inconvenientes

IMAP y POP3: Diferencias, ventajas y desventajas

POP: Post Office Protocol (Protocolo de oficina de correos) es un protocolo de comunicación que se utiliza para obtener desde un programa de escritorio (Thunderbird, Outlook, Windows Mail, etc.) los mensajes de correo electrónico almacenados en un servidor remoto
IMAP: Internet Message Access Protocol (Protocolo de acceso a mensajes de internet), esto es, igualmente, un protocolo de comunicación que se utiliza para acceder a los mensajes electrónicos alojadas en un servidor remoto.
El protocolo IMAP, de forma predeterminada, permite al usuario conservar todos los mensajes en el servidor. Constantemente se sincroniza el programa de correo electrónico con el servidor, mostrando los mensajes que están presentes en la carpeta en cuestión. Todas las accionesrealizadas en los mensajes (leer, mover, eliminar…) se realizan directamente en el servidor.
El protocolo POP, por defecto, está configurado para descargar todos los mensajes del servidor de correo electrónico al ordenador desde el que se conecta. Esto significa que todas las acciones realizadas en los mensajes (leer, mover, borrar…) se realizarán en el propio ordenador. Al descargarse, por defecto, se eliminan los mensajes del servidor y, por ello, el usuario no podrá volver a ver los mensajes desde cualquier lugar que no sea el equipo en el que los mensajes han sido descargados.
En ambos casos, como ves, se habla de configuración por defecto (o predeterminada), por lo que deja ver que es una configuración que se puede cambiar. Así, con el protocolo IMAP se pueden descargar mensajes y conservarlos únicamente en nuestro PC (al menos con Thunderbird -no sé si otros clientes disponen de esta opción-, si se archiva el mensaje en una carpeta local en vez de archivarlos en una carpeta dependiente de tu cuenta IMAP) y el protocolo POP se puede configurar para que deje una copia de los mensajes en el servidor y que se borren una vez pasado un determinado periodo de tiempo (o que no se borren nunca).

IMAP (Internet Message Access Protocol)

La característica más significativa del protocolo IMAP es que los correos y bandejas no están en tu ordenador sino en el Servidor Cloud. Esto permite tener perfectamente sincronizados todos tus correos cuando normalmente lees los e-mails desde distintos ordenadores o dispositivos, o incluso desde Webmail, ya que en cualquiera de ellos aparecerán todos tus correos, lo que incluiría no sólo los correos de la bandeja de entrada sino también los del resto de bandejas.
La principal desventaja del protocolo IMAP es que es necesario disponer de conexión a Internet todo el tiempo para revisar los mensajes, además de que al quedar almacenados en el servidor, hay que ir revisando de vez en cuando el espacio utilizado por los correos para no sobrepasar el límite de capacidad del buzón en cuestión.
En cualquier caso, esta desventaja queda “corregida” al utilizar algunos programas de correo como Microsoft Outlook, ya que es posible activar la función “Autoarchivar” para evitar que se llene el buzón, ya que de forma automatizada irá borrando o almacenando en carpetas locales los correos más antiguos o caducados.

VENTAJAS

  • Comunicación bidireccional entre el servidor de correo y el cliente de correo electrónico, lo que permite que varios dispositivos trabajen con una misma cuenta viendo los cambios realizados por todos.
  • Los correos están en todo momento en el servidor, por lo que se puede acceder a ellos desde cualquier lugar, teniendo un dispositivo con acceso a internet.
  • En caso de una avería en el ordenador en el que esté configurado el buzón, o si por cualquier razón se elimina la cuenta, siempre es posible recuperar los correos.
  • Al no descargarse los correos directamente en el dispositivo que accede al servidor de correo, no consume espacio local.
  • Es posible gestionar carpetas locales y archivos desde el servidor.
  • Permite la búsqueda de mensajes por medio de palabras clave.

DESVENTAJAS

  • No es posible acceder a los correos sin acceso a internet.
  • En caso de hacer un uso intensivo del servicio de correo, es necesaria una gran cantidad de espacio de almacenamiento en el servidor.
  • Las carpetas que se hayan creado con IMAP no podrán ser leídas usando POP (la única excepción es la carpeta de la Bandeja de entrada).

POP3 (Post Office Protocol)

En el caso del protocolo POP3, el programa cliente de correo (Outlook, ThunderBird, Mail, etc) se conecta con el servidor y descarga todos los correos en el dispositivo en el que configures la cuenta. Esta es su principal ventaja, pues al descargar los correos, es posible leerlos incluso no estando conectado a Internet.
Como información adicional, comentar que POP3 es un protocolo que fue desarrollado cuando las conexiones a Internet eran sin tarifa plana, de modo que el objetivo era descargar el correo y desconectar enseguida y no tener que conectar cada vez que quisieras revisar el email.
Al descargar los mensajes del servidor cada vez que lees el correo, éstos se borran del servidor liberando espacio en el mismo, con lo cual hay menos posibilidades de que se llene el buzón, y no puedas recibir nuevos correos. No obstante, actualmente existe la opción de mantener copia de los mensajes en el servidor para poder sincronizar los mensajes entrantes para poder revisar el correo desde diferentes dispositivos.

VENTAJAS

  • Poder utilizar un cliente de correo para descargarlos en un dispositivo u ordenador, y poder leerlos posteriormente, aún sin tener conexión a internet.
  • No es necesario tener un gran espacio de almacenamiento en el servidor de correo, ya que al descargar los correos se borran del mismo.

DESVENTAJAS

  • Si el dispositivo donde están almacenados los correos descargados tiene una avería, es extraviado, o robado se pierden los correos.
  • Enviar un mensaje desde el cliente puede tardar el doble del tiempo.
  • Dependiendo del mensaje, puede consumir recursos del sistema.

Jesús Moreno - Ingeniero Ténico Informático - consultor Informático

Hola, soy Jesús Moreno Ingeniero Técnico Informático en sistemas por la US y propietario de éste blog. Mi trabajo en los ultimos años se ...