Sunday, 23 December 2018

HOW TO SECURELY STORE BITCOIN WITH SOFTWARE, APPS AND HARDWARE

WHAT IS A BITCOIN WALLET?

A bitcoin wallet represents a software program which stores bitcoin (BTC) $4222.19 -0.31% private keys. Often, wallets come in hardware and software for, the former being known as a hardware wallet. In general, they grant you access to your public Bitcoin address, often with Bitcoin Core and an internet connection, thus facilitating the buying and selling of cryptocurrency.
Obtaining a blockchain wallet is necessary in order to hold any type of crypto assets or digital currency. While there are certain solutions which would only allow you to hold one type of digital currencies, the wide majority of Bitcoin wallets, many harnessing the open-source programming of Bitcoin Core, also allow the user to hold multiple cryptocurrencies at the same time, including Ether (ETH), Bitcoin Cash (BCH), Monero (XMR), Ripple (XRP), Stellar (XLM), and others.

WHAT IS A PRIVATE KEY?

In the context of bitcoin, a private key represents a secret sequence of numbers and letters which allow bitcoins to be spent. Each bitcoin wallet contains at least one, or sometimes more, private key. The keys are saved within the wallet file and are mathematically related to all of the bitcoin addresses which are generated for the wallet.
Put simply, this is your “ticket” which will allow you to spend your bitcoins. As such, it is quintessential that you keep it secure. This is the reason for which all reputable cryptocurrency exchanges put the emphasis on advanced privacy when it comes to storing your digital assets.

DIFFERENT TYPES OF BITCOIN WALLETS

There are many types of wallets: desktop, mobile, paper, web, and hardware. Many have different features allowing a span of financial activity like savings management or retirement planning. A good wallet review will make these features clearer.
Desktop wallets, as the name suggests, are installed on your computer’s desktop. These types of wallets offer full control over the software wallets. They enable the user to generate a bitcoin address for buying and selling bitcoin. Naturally, they also allow the user to store their private key.
A mobile wallet, on the other hand, provides for more convenience, as they aren’t fixed in one place. These usually come in the form of paid applications that you can run on your smartphone. In terms of functionality, however, a mobile wallet would allow you to do the same things as a desktop wallet. These differences can often be fleshed out in an online wallet review. One notable advantage is the fact that a mobile wallet could enable you to receive payments and make direct payments in physical stores which accept digital currency by scanning a QR code.
Among the various types of wallets —a mobile wallet, bitcoin wallet, etc. — is the paper wallet. This is nothing but your public and private key printed together. Technically, a paper wallet is a type of cold wallet because it is entirely offline. You can make a paper wallet out of any substance that you can print information on.
Differentiation can also be made based on the operating system the wallet can be used on. As such, you can have Android wallets (which are Android apps), Apps for iOS on iPhone and iPad, Windows, Mac and Linux, and so forth. Many software solutions are programs with a free download. Naturally, almost all of the hot wallets can be classified as Android wallets as they are usually supported by the operating system and they do have designated Android apps. Some wallets are compatible with mining hardware as well.
paper wallet for bitcoin

HOT WALLETS VS COLD WALLETS

The next differentiation is based on whether or not the wallet is connected to the internet. If they are connected, they are referred to as web wallets or, most commonly, a hot wallet. If it’s not connected and it operates entirely offline, the solution is called a hardware wallet or cold wallet.
Cold wallets are generally considered to be safer, simply because they can’t be tampered with by someone online. They are not connected to the internet and, as such, they are safe from any types of hacking attempts and attacks. This is a type of offline storage.
Hot wallets, on the other hand, are a web-based wallet which is actually on the internet. In other words, in order to access them and to manage your BTC, you will need to have a stable internet connection. They offer a lot more flexibility and many of them have integrated solutions which facilitate the buying and selling of digital currencies. At the same time, though, they are considered to be less secure because they are connected to the internet and, hence, subjected to hack attacks.
Naturally, both solutions have their own benefits and drawbacks. Understanding them is critical when making the right choice finding a wallet provider for storing bitcoin.

ADVANTAGES AND DISADVANTAGES OF A HOT WALLET

As with any wallet provider, hot wallets have their pros and cons. Being well aware of these advantages and disadvantages will enable you to make the right choice based on your particular preferences.
Pros of Using a Hot Wallet:
  • Most of the hot wallets are beginner friendly and easy to use.
  • They provide instant access to your crypto assets at any given moment as long as you have internet connection (Web-based wallet).
  • They usually come with numerous layers of security features and backup options.
  • They are compatible with most every operating system such as Windows, Mac and Linux, and Android, as well as mining hardware.
  • 2-Factor Authentication for improved security.
Cons of Using a Hot Wallet:
  • They offer a lower level of security features compared to cold wallets as they are always connected to the internet.
  • They are run on centralized servers, hence are usually limited in terms of the number of transactions that can be handled, which may cause occasional delays.
It’s worth noting that hot wallets are very user-friendly and, as such, are particularly convenient for beginners looking to safely and securely store your cryptocurrency, or trade a relatively small amount of cryptocurrencies. If you’re looking to store your cryptocurrency in bulk, though, you might be better off with a cold wallet.

Bitcoin Cold Wallet

ADVANTAGES AND DISADVANTAGES OF A COLD WALLET

Cold wallets offer offline storage solutions for those users who prefer to keep their private keys stored offline safely and securely off the internet. In order to gain access to the information stored offline on them, you would need to simply plug them to your computer. As this is their main characteristics, they reveal certain distinct pros and cons.
Pros of using a cold wallet:
  • No one but the owner of the cold wallet has access to the information kept on it.
  • They are not connected to the internet and, hence, provide greater security.
  • They are excellent for long-term investors who would like to securely have their assets stored offline.
Cons of using a cold wallet
  • Cold wallets are a bit more challenging to work with and they offer limited flexibility when it comes to transacting.
  • A lot of them don’t accept all types of tokens
  • They can be a bit expensive
  • Difficult compatibility with mining hardware.

HOW TO CHOOSE A WALLET?

Naturally, if you want to get involved in buying and selling cryptocurrency and you are reasonable enough when it comes to the integrity of your personal finance, you need to pick the best Bitcoin wallet possible — not to mention the most secure wallet for your task.
One of the best things you can do, in case you are unsure about the type of solution you’d want to use, is to read a solid bitcoin wallet review, investigate Bitcoin Core, various apps, etc. It goes without saying that choosing the best bitcoin wallets will require you to determine whether you’d want to be actively trading or to simply store your bitcoin or any other digital currency for a longer period of time.
Here are some of the popular wallets used for storing digital assets.

TREZOR WALLET

Trezor is among the very first hardware wallets and it allows the offline storage of a wide range of different digital assets including Bitcoin, Litecoin, Binance Coin, Dash, Zcash, Ethereum, Ethereum Classic, and over 500 other cryptocurrencies.
Trezor, another popular hardware wallet, is beginner friendly and comes with a monochrome display containing 2 buttons. The secure wallet brand has two models currently on the market. In terms of security, the device offers 2-factor authentication, SSH, encryption via GPG, encrypted cloud-storage, and other features.
Trezor Model T review

KEEPKEY WALLET

Keepkey wallet is another cold wallet which is designated to enable users to store your Bitcoin, Ethereum, Bitcoin Cash, Dogecoin, Dash, Bitcoin Gold, Litecoin, and a wide range of ERC20-based tokens.
It has a rather sleek design and a large display which makes it easy to manage your BTC. Every single transaction needs to be manually approved. This is possible through KeepKey’s confirmation button. One of the main benefits of the device is that if you lose it, you can recover it without worrying about your private keys being compromised.

COOLWALLET S

The CoolWallet S by CoolBit X is a sleek and handsome-looking credit card-like hardware wallet that easily slips write into fiat wallet. It boasts robust security features by pairing via Bluetooth to your Android or iOS device, adding the convenience of smartphone functionality without sacrificing security.
It’s not only the best-looking wallet out there, but also one of the safest and most secure.
CoolWallet S

COPAY WALLET

Copay wallet is a web-based wallet and multisignature wallet. You can get it from the app store, or you from the Google Play store if you are using android wallets. It also works on Windows, Mac and Linux.
The wallet comes with a range of features to give and receive payments such as secure payment verification, 2-factor authentication, and full support for the Bitcoin Payment Protocol. Its code is open-sourced, allowing users to take full control over their finances. A look at a Copay wallet review will reveal a positive outlook from many users and their Bitcoin wallet reviews.

LEDGER NANO

The Ledger Nano is perhaps one of the most popular hardware wallets currently available on the market. Beginner friendly and lauded by Bitcoin wallet reviews and overviews of hardware wallets, the Ledger Nano supports over 40 different cryptocurrencies which include — but are not limited to — Bitcoin, Ethereum, and XRP. The Ledger Nano guarantees that your private key is never going to be exposed, as it remains protected within a secure chip that is locked with a pin code.
It is very easy to use as it only has 2 buttons. All of the actions can be easily verified on the device’s screen. It also has back-up and restore functions, meaning you can easily recover your accounts if you lose your device through a confidential recovery phrase. This makes it a great choice for activities like retirement planning.

LEDGER BLUE

Ledger Blue is described as a premium hardware wallet which places the emphasis on advanced privacy and user experience. Unlike the Ledger Nano, Ledger Blue comes with a large touchscreen wallet interface and it is built around a conveniently secured element that includes all regular features you can expect from a cold wallet. It similarly garners a near-universally positive Bitcoin wallet review as one of the best Bitcoin wallets.
Naturally, Ledger Blue stores a wide range of different cryptocurrencies – over 30. The device allows you to manage up to 11 crypto assets at the same time. The touch screen is colorful and it allows you to easily manage your holdings.
Ledger Nano

COINOMI WALLET

Coinomi wallet is an application which supports multiple languages and, hence, offers international usage. Some of these multiple languages include Spanish, Russian, Chinese, German, English, and others.
It’s a web-based wallet that you can get from the App Store or the Google Play Store, regardless of whether you are using iOS device like an iPhone and iPad with apps, or Android device with an Android app. The application stores multiple cryptocurrencies and comes with 2-factor authentication for further security. It is fairly easy to use and has a beginner friendly wallet interface which allows novice users to easily manage and store your bitcoin. A glance at a wallet review shows just how popular this wallet is.

ELECTRUM WALLET

Electrum represents a free download software wallet which is released under MIT-issued license. It supports hardware wallets such as KeepKey, Trezor, and Ledger. It is capable of being used with a multisignature wallet and offers comprehensive offline storage.
It comes with 2-factor authentication to deliver greater security. It can be used on mobile and desktop. The solution is forgiving because it enables the user to recover funds through a secret phrase. It is particularly safe and very fast. It has different add-ons such as third-party plugins. There are no downtimes, which is a significant benefit. It’s regarded as one of the best Bitcoin wallets.

EXODUS WALLET

This hot wallet represents a combination of services in one. It is a portfolio, an exchange, as well as a wallet for your crypto assets. Apart from advanced privacy, the solution allows you to exchange different digital currencies right from the wallet interface, which is quite convenient, especially for novice users.
The app is personalized and allows full control over your private keys. It comes with easy to understand and beginner friendly live charts. This will enable you to easily track the value of your entire crypto asset portfolio in real time.

JAXX WALLET

The Jaxx wallet is a lesser-known hot wallet which requires no registration and claims to be entirely free. You can use it on your iOS Device — like an iPhone and iPad — or Android wallets as a free download on an Android app, Windows, Mac and Linux. You can also use it on your desktop through Google Chrome. It can be paired on multiple devices.
The wallet supports over 85 different crypto assets, something, which allows for great portfolio diversification. It has a beginner-friendly wallet interface and it is fairly simple to use all of its features. Naturally, the 2-factor authentication improves the security, among the other features that the device comes with.

GREENADDRESS WALLET

This wallet is supposedly going to enable the user to have full control over personal finance when it comes to storing bitcoin. It allows the setting of spending limits, rate limit transactions, and others of the kind.
One of the unique features of the wallet is that it has a ‘per-transaction’ 2-factor authentication. In other words, in order to further guarantee the security of your funds and the integrity of your transactions, you’d have to double verify them each time. This does, however, make transacting a bit slower. On the other hand, the wallet has a beginner friendly interface and it’s not challenging to get a handle on it. Bitcoin wallet reviews tend to be generous.

SAMOURAI WALLET

The Samourai Wallet is a hot wallet which comes with a range of different perks. Advanced privacy, high security, and transactional integrity are just a few of its perks.
samouri
The wallet is intended to provide the user with complete control over privacy and miners fee with every single transaction. It takes pride in offering the first full BIP 47 implementation which brings privacy to public payment addresses. It also has remote SMS commands which provide for a great amount of flexibility and increased usability. Many consider Samourai to be their favorite and best Bitcoin wallet.

MYCELIUM WALLET

Mycelium wallet prides itself as one of the top-rated applications on the Google Play Store. According to the application’s official website, there are new tools which will come out soon and supplement the functionality of the wallet.
For instance, it’s projected that the app will feature fully-fledged, blockchain-based fiat accounts as well as debit cards which are linked to the wallet and issued by it. The solution also intends to introduce an option to exchange cryptocurrencies through its software wallet which is quite convenient.

EDGE.APP WALLET

This is yet another hot wallet which enables the user to control and store a wide variety of different digital assets. It has an app for iOS devices including iPhone and iPad, and an Android app for an Android device. It is easy to use and available on both the App Store and the Google Play Store.
The wallet comes with multi-asset support and it is designated for both long-term holders and for active traders. It allows the user to exchange between different assets on the go. You can also buy and sell cryptocurrencies from within the application itself, which improves user-experience and overall flexibility.

BRD WALLET

BRD is intended to be a very simple and secure storage solution for Bitcoin, Ethereum, and a range of other digital currencies. It’s available for download on the App Store and the Google Play Store.
The wallet enables the user to purchase bitcoin through a range of different methods, which include credit cards, bitcoin ATM in-person purchase, and others of the kind. It is also possible to convert cryptocurrencies. The design is simple and user-friendly, allowing for seamless storage experience and exchange. Purportedly, the wallet is directly connected to the blockchain through a 12-word paper key. In turn, there are no accounts that you have to set up or passwords that you have to remember. Check out a wallet review online!

BLOCKCHAIN.INFO WALLET

This hot wallet is one which allows the user to buy, sell, exchange, and to transact with Bitcoin, Bitcoin Cash, and Ether. The API blockchain wallet is particularly easy to use and it allows you to go over specific transactions, to access live bitcoin data, and many more of the kind.
The blockchain wallet is purportedly convenient for those users who seek additional market insight and are keen on interacting with the cryptocurrency market frequently instead of just holding for the long term.

COINBASE WALLET

Coinbase is the largest US-based cryptocurrency exchange, and it also has a wallet service. Often making the rounds among Bitcoin wallet review circuit, it’s a hot wallet which supports the cryptocurrencies offered by the exchange itself. The wallet allows the user to transact with cryptocurrencies in a fairly seamless manner.
One of the benefits is that Coinbase keeps conventional checking accounts through the so-called “Coinbase vault” which adds for more security. Also popular with the retirement planning crowd. transaction fees are a downside.
Coinbase

CONCLUSION

Clearly, there are plenty of different bitcoin wallets that you can take advantage of. While the above are some of the more popular, there are other solutions that you are free to take a look at as well.
One of the most important things that you ought to keep in mind is the purpose of you using the wallet. Turn to a solid wallet review or go online to find a match.
If you want to be actively interacting with the cryptocurrency market and trade regularly, you might be better off with a highly-secured hot wallet, as it is easier to access your funds. Furthermore, hot wallets are most commonly compatible with a wide range of different mobile devices like an Android device, making transacting with cryptocurrencies on the go possible.
On the other hand, if you are looking at cryptocurrency as a long-term play and investment, it goes without saying that your better bet would be to store your private keys within a cold wallet. As it doesn’t connect to the internet, it is much more challenging to hack. Again, a good wallet review can help here.
A general rule of thumb is to check which digital assets the selected solution supports. If you intend to hold only bitcoin, you might be better off with a simple bitcoin wallet but if you want to store your cryptocurrency differently than you should obviously look another way.
Keep in mind that there are plenty of different bitcoin wallets which allow you to purchase cryptocurrencies right from the web interface, which is something very convenient for beginner users as it takes away the hassle of interacting with the market through cryptocurrency exchanges. There are also wallets with built-in exchange features, which would allow you to exchange your cryptocurrencies directly from the app, without having to register and verify accounts on different exchanges. It is always helpful to also find a good wallet review.
In other words, the best Bitcoin wallet is easily that which serves the best purpose based on your investment intentions.
What do you think is the best Bitcoin wallet? Do you have a favorite hardware and software, web interface, or preferred software wallets? What about security features you find most useful? Do you have a particular purpose for storing bitcoin and crypto — savings, retirement planning, etc. What about Bitcoin Core and the choice of an operating system, transaction fees, mining hardware, and more? Don’t hesitate to let us know in the comments below! 

Thursday, 26 February 2015

, , , , , , , , , , , , , , ,

PHP File Uploading

A PHP script can be used with a HTML form to allow users to upload files to the server. Initially files are uploaded into a temporary directory and then relocated to a target destination by a PHP script.
Information in the phpinfo.php page describes the temporary directory that is used for file uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as upload_max_filesize. These parameters are set into PHP configuration file php.ini

The process of uploading a file follows these steps
  • The user opens the page containing a HTML form featuring a text files, a browse button and a submit button.
  • The user clicks the browse button and selects a file to upload from the local PC.
  • The full path to the selected file appears in the text filed then the user clicks the submit button.
  • The selected file is sent to the temporary directory on the server.
  • The PHP script that was specified as the form handler in the form's action attribute checks that the file has arrived and then copies the file into an intended directory.
  • The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.

Creating an upload form:

The following HTM code below creates an uploader form. This form is having method attribute set to post and enctype attribute is set to multipart/form-data
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="/php/file_uploader.php" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This will display following result:
File Upload:
Select a file to upload: 




NOTE: This is just dummy form and would not work.

Creating an upload script:

There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables:
  • $_FILES['file']['tmp_name']- the uploaded file in the temporary directory on the web server.
  • $_FILES['file']['name'] - the actual name of the uploaded file.
  • $_FILES['file']['size'] - the size in bytes of the uploaded file.
  • $_FILES['file']['type'] - the MIME type of the uploaded file.
  • $_FILES['file']['error'] - the error code associated with this file upload.
The following example below attempts to copy a file uploaded by the HTML Form listed in previous section page to /var/www/html directory which is document root of your PHP server and it will display all the file's detail upon completion. Please note that if you are going to display uploaded file then don't try with binary files like images or word document.
Here is the code of uploader.php script which will take care of uploading a file.
<?php
if( $_FILES['file']['name'] != "" )
{
   copy( $_FILES['file']['name'], "/var/www/html" ) or 
           die( "Could not copy file!");
}
else
{
    die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name'];  ?>
<li>File size: <?php echo $_FILES['file']['size'];  ?> bytes
<li>File type: <?php echo $_FILES['file']['type'];  ?>
</ul>
</body>
</html>
When you will upload a file using upload form and upload script, it will display following result:
Uploaded File Info:
  • Sent file: uploadedfile.txt
  • File size: 2003 bytes
  • File type: image/jpg

You try out above example yourself on your webserver. If you have any problem then post it to Discussion Forums to get any further help.

Wednesday, 25 February 2015

, ,

PHP Select Data From MySQL

Select Data From a MySQL Database

The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
To learn more about SQL, please visit our SQL tutorial.

Select Data With MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on the page:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

Code lines to explain from the example above:
First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The next line of code runs the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

You can also put the result in an HTML table:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "<table><tr><th>ID</th><th>Name</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>


Select Data With PDO (+ Prepared Statements)

The following example uses prepared statements.
It selects the id, firstname and lastname columns from the MyGuests table and displays it in an HTML table:

Example (PDO)


<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

Tuesday, 24 February 2015

, , ,

PHP Forms - Validate E-mail and URL


This chapter shows how to validate names, e-mails, and URLs.

PHP - Validate Name

The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "Only letters and white space allowed";
}
Note The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

PHP - Validate E-mail

The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format";
}

PHP - Validate URL

The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  $websiteErr = "Invalid URL";
}

PHP - Validate Name, E-mail, and URL

Now, the script looks like this:

Example


<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
    }
  }

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL";
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}
?>

The next step is to show how to prevent the form from emptying all the input fields when the user submits the form.
, , , ,

AJAX Introduction

AJAX is about updating parts of a web page, without reloading the whole page.

What is AJAX?

AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works

AJAX

AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:
  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)
Note AJAX applications are browser- and platform-independent!

Google Suggest

AJAX was made popular in 2005 by Google, with Google Suggest.
Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.

Start Using AJAX Today

In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP.
If you want to learn more about AJAX, visit our AJAX tutoria
, , ,

PHP MySQLi Functions

PHP MySQLi Introduction

PHP MySQLi = PHP MySQL Improved!
The MySQLi functions allows you to access MySQL database servers.
Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.

Installation / Runtime Configuration

For the MySQLi functions to be available, you must compile PHP with support for the MySQLi extension.
The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was included in PHP version 5.3.0.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php
For runtime configuration details, go to: http://php.net/manual/en/mysqli.configuration.php


PHP 5 MySQLi Functions

Function Description
mysqli_affected_rows() Returns the number of affected rows in the previous MySQL operation
mysqli_autocommit() Turns on or off auto-committing database modifications
mysqli_change_user() Changes the user of the specified database connection
mysqli_character_set_name() Returns the default character set for the database connection
mysqli_close() Closes a previously opened database connection
mysqli_commit() Commits the current transaction
mysqli_connect_errno() Returns the error code from the last connection error
mysqli_connect_error() Returns the error description from the last connection error
mysqli_connect() Opens a new connection to the MySQL server
mysqli_data_seek() Adjusts the result pointer to an arbitrary row in the result-set
mysqli_debug() Performs debugging operations
mysqli_dump_debug_info() Dumps debugging info into the log
mysqli_errno() Returns the last error code for the most recent function call
mysqli_error_list() Returns a list of errors for the most recent function call
mysqli_error() Returns the last error description for the most recent function call
mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both
mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both
mysqli_fetch_assoc() Fetches a result row as an associative array
mysqli_fetch_field_direct() Returns meta-data for a single field in the result set, as an object
mysqli_fetch_field() Returns the next field in the result set, as an object
mysqli_fetch_fields() Returns an array of objects that represent the fields in a result set
mysqli_fetch_lengths() Returns the lengths of the columns of the current row in the result set
mysqli_fetch_object() Returns the current row of a result set, as an object
mysqli_fetch_row() Fetches one row from a result-set and returns it as an enumerated array
mysqli_field_count() Returns the number of columns for the most recent query
mysqli_field_seek() Sets the field cursor to the given field offset
mysqli_field_tell() Returns the position of the field cursor
mysqli_free_result() Frees the memory associated with a result
mysqli_get_charset() Returns a character set object
mysqli_get_client_info() Returns the MySQL client library version
mysqli_get_client_stats() Returns statistics about client per-process
mysqli_get_client_version() Returns the MySQL client library version as an integer
mysqli_get_connection_stats() Returns statistics about the client connection
mysqli_get_host_info() Returns the MySQL server hostname and the connection type
mysqli_get_proto_info() Returns the MySQL protocol version
mysqli_get_server_info() Returns the MySQL server version
mysqli_get_server_version() Returns the MySQL server version as an integer
mysqli_info() Returns information about the most recently executed query
mysqli_init() Initializes MySQLi and returns a resource for use with mysqli_real_connect()
mysqli_insert_id() Returns the auto-generated id used in the last query
mysqli_kill() Asks the server to kill a MySQL thread
mysqli_more_results() Checks if there are more results from a multi query
mysqli_multi_query() Performs one or more queries on the database
mysqli_next_result() Prepares the next result set from mysqli_multi_query()
mysqli_num_fields() Returns the number of fields in a result set
mysqli_num_rows() Returns the number of rows in a result set
mysqli_options() Sets extra connect options and affect behavior for a connection
mysqli_ping() Pings a server connection, or tries to reconnect if the connection has gone down
mysqli_prepare() Prepares an SQL statement for execution
mysqli_query() Performs a query against the database
mysqli_real_connect() Opens a new connection to the MySQL server
mysqli_real_escape_string() Escapes special characters in a string for use in an SQL statement
mysqli_real_query() Executes an SQL query
mysqli_reap_async_query() Returns the result from async query
mysqli_refresh() Refreshes tables or caches, or resets the replication server information
mysqli_rollback() Rolls back the current transaction for the database
mysqli_select_db() Changes the default database for the connection
mysqli_set_charset() Sets the default client character set
mysqli_set_local_infile_default() Unsets user defined handler for load local infile command
mysqli_set_local_infile_handler() Set callback function for LOAD DATA LOCAL INFILE command
mysqli_sqlstate() Returns the SQLSTATE error code for the last MySQL operation
mysqli_ssl_set() Used to establish secure connections using SSL
mysqli_stat() Returns the current system status
mysqli_stmt_init() Initializes a statement and returns an object for use with mysqli_stmt_prepare()
mysqli_store_result() Transfers a result set from the last query
mysqli_thread_id() Returns the thread ID for the current connection
mysqli_thread_safe() Returns whether the client library is compiled as thread-safe
mysqli_use_result() Initiates the retrieval of a result set from the last query executed using the mysqli_real_query()
mysqli_warning_count() Returns the number of warnings from the last query in the connection
, , ,

PHP Variables


Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example


<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
Note Think of variables as containers for storing data.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for PHP variables:
  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)
Note Remember that PHP variable names are case-sensitive!

Output Variables

The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:

Example


<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>

The following example will produce the same output as the example above:

Example

<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>

Run example »
The following example will output the sum of two variables:

Example

<?php
$x = 5;
$y = 4;
echo $x + $y;
?>

Note: You will learn more about the echo statement and how to output data to the screen in the next chapter.

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
  • local
  • global
  • static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

Example

<?php
$x = 5; // global scope

function myTest() {
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";
?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

Example

<?php
function myTest() {
    $x = 5; // local scope
    echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>

Note You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

PHP The global Keyword

The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):

Example

<?php
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
The example above can be rewritten like this:

Example


<?php
$x = 5;
$y = 10;

function myTest() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:

Example

<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}

myTest();
myTest();
myTest();
?>

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.
Note: The variable is still local to the function.