Thursday, 2 March 2017

PHP7 Features

With that out of the way, let’s check out PHP 7.

1. The Name’s PHP 7 (Not 6)

The current stable release uses the version number PHP 5.6. After some dispute the development team decided they would omit the PHP 6 name for the next major release. PHP 6 already existed in the past as an experimental project but never reached the production phase.
To prevent users from mixing up the former attempt with the latest development, the new major release will run under the name of PHP 7.

2. The Brand Spanking New Zend Engine

The Zend engine has been powering PHP since 1999 when it was introduced with the then new PHP 4 release. Zend – not to confused with the Zend Framework – is an open-source execution engine written in C that interprets the PHP language. The current PHP 5.X series use Zend Engine II that enhanced the funtionality of the initial engine and adds an extensible object model and a significant performance enhancement to the language.

3. Twice The Speed

The most easily recognizable advantage of the new PHPNG engine is the significant performance improvement. The development team of PHPNG refactored the Zend Engine, and remarkably o

4. Facilitates Error Handling

To say the least, handling fatal and catchable fatal errors have never been an easy task for PHP coders. The new Engine Exceptions will allow you to replace these kind of errors with exceptions. If the exception is not caught, PHP will continue to return the same fatal errors as it does in the current 5.X series.
The new \EngineException objects don’t extend the \Exception Base Class. This ensures backward compatibility and results in two different kinds of exceptions in error handling: traditional and engine exceptions.
To enable programmers to catch both, PHP 7 introduces a new shared Parent Class under the name of \BaseException.

IMAGE: Wiki.PHP.net

5. 64-Bit Windows Systems Support

PHP is a prominent member of the LAMP stack which means its native environment is Linux – but it’s also possible to run it on a Windows system. The 5.X series don’t yet provide 64-bit integer or large file support, so until now x64 builds have been considered experimental.
PHP 7 will change this as it introduces consistent 64-bit support which means both native 64-bit integers and large files will be supported, allowing you to confidently run the language on your 64-bit Windows system in the future.ptimized memory usage.
The results? You can see the performance benchmarks provided by the Zend Performance Team below. By using PHP 7 not only your code will be executed faster but you will also need fewer servers to serve the same amount of users.

6. New Spaceship and Null Coalescing Operators

The Spaceship operator runs under the official name of Combined Comparison Operator. The notation of the new operator looks like this: <=> (kind of like a simplified spaceship, if you imagine it right).
The spacehip operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It’s also called a three-way comparison operator, and it already exists in other popular programming languages like Perl and Ruby.

IMAGE: Wiki.PHP.net

The Null Coalescing operator is denoted with two question marks ( ?? ). You can use it when you want to check if something exists and return a default value, in case it doesn’t. The coalesce operator returns the result of its first operand if it exists and is not null, and the second operand in any other cases.
Here’s how the new operator reduces the time spent with basic declarations:

IMAGE: Wiki.PHP.net

7. Enables Accurate Type Declarations

Have you ever wanted to prevent unintended return values by declaring the return type of a function? Well, the new PHP 7 enables developers to enhance the quality of their code with the help of return type declarations.
The image below depicts a very simple use case where the foo() function is supposed to return an array. Check out more complicated examples here.

IMAGE: Wiki.PHP.net

To enhance the feature even more, PHP 7 introduces 4 new type declarations for scalar types: int, float, string and bool. The new scalar types allow developers to denote that they are expecting integers, floats, strings, or booleans to be returned. The new scalar types introduced by PHP 7 will also be supported by argument Type Hints that enables developers to force the type of parameters since the PHP 5.X series.

8. Adds Anonymous Classes

PHP 7 enables you to use anonymous classes, already a well-established practice in other object-oriented languages like C# and Java. An anonymous class is a class without a name. The object it instantiates has the same functionality as an object of a named class.
The syntax is the same as what we are used to in traditional PHP classes, only the name is missing. If anonymous classes are used well, they can speed up coding as well execution time. Anonymous classes are excellent when a class is used only once during execution and in cases when a class doesn’t need to be documented.

IMAGE: Wiki.PHP.net

9. Facilitates Imports From the Same Namespace

The new Group Use Declarations feature will be godsent to those of you who want to import many classes from the same namespace. The new syntax cuts verbosity, makes your code tidier and easier on the eyes, and saves you a lot of typing time.
It will also be easier to read through and debug codes, as group use declarations help you identify the imports that belong to the same module.

IMAGE: Wiki.PHP.net

10. Cleans Up The Room

The goal of PHP 7 was to free up the space to enable improvement, so it was necessary to get rid of many deprecated functionalities and old and unsupported Server APIs and extensions. If you want to check which are these in detail, click here and here.
All the removed items have been deprecated for a while in PHP 5 so most likely you haven’t used them for a long time. However please note if you have a legacy app running on older PHP versions the new PHP 7 can potentially break the code.

Tuesday, 28 February 2017

why to use framework




down voteaccepted
Framework abstracts you from low level details, makes you more productive, and protects you from low level error ( such as preventing SQL injection attacks).
A good PHP framework forces you to separate your concern and implements the proven architecture, which in the end improves your design, and makes your code much easier to read and maintain and unit test.
framework streamlines application development by automating many of the patterns employed for a given purpose. A framework also adds structure to the code, prompting the developer to write better, more readable, and more maintainable code. Ultimately, a framework makes programming easier, since it packages complex operations into simple statements.

For a simple web application or a website with basic features it’s wiser to use some good open source system. However for more complex and bespoke functionality requirement it’s more recommended to work with framework.

Huge amount of development time can be saved with the use of Frameworks due to availability of large variety of tools like input sanitization and abstraction layers in particular.
It's very common scenario in website development companies where clients are really pressurizing and so often demand quick turnaround. Frameworks can be real life savers under high pressure as they help enormously in quickly delivering repetitive and commons tasks.

There are pretty good reasons to use the Frameworks:
  • Code and file organization is extremely easy
  • Countless numbers of tools and libraries that can help you with:
    • Form validation
    • Database abstraction
    • Input/Output filtering
    • Session and Cookie handling
    • Email, Calender and pagination and much more
  • MVC (Model View Controller) Architecture
  • Less code which ultimately speeds up your development
  • Security - PHP has many input and output filtering functions which can add extra security layer to protect your website against certain attacks
  • Suitable for teamwork
  • PHP frameworks have great active community support. You will find the accurate solution of any query quickly


why to use javascript frameworks ?



Don't Reinvent The Wheel

Why write code that's already been written (better)? A good programmer is a lazy programmer, so be lazy. The tools are there -- use them

Do More With Less Code

Most JavaScript frameworks provide function "chaining." Chaining allows you to do more with less code. Less code means less maintenance time, less download time, and less coding time. Check out MooTools chaining.

Save Time -- You Don't Code Your Own OS, Do You?

I love JavaScript as much as the next guy, but some programmers REALLY love developing JavaScript. Let the experts do the tough part, you take their work and make what you'd like of it.

Chances Are, You Aren't The Expert

As big as any programmer's ego is, there are people out there that are smarter, more inventive than you. Most Web Developers need to be a jack of all trades and it's difficult to keep up with every language when you're needed in every facet of a website's construction and launch. The minds behind the frameworks have their eyes on JavaScript daily -- trust in them.

Speed Thrills

The creators of these JavaScript frameworks have their own private pissing contest when it comes to JavaScript speed put a lot of effort into making sure their frameworks are fast. The first job of JavaScript for mass web visitor usage is to be fast -- users expect accuracy, speed is the most important part. Who's fastest today? Check out SlickSpeed.

Avoid Cryptic JavaScript Base Code

Why use JavaScript's default functions when you can use a framework's English-named functions? For example:
//standard JavaScript
document.getElementbyId('mydiv').style.color = '#f00'; // camel-case the style!

//mootools JavaScript
$('mydiv').setStyle('color','#foo');
These are the reasons I use JavaScript frameworks. Need I say more?
7. Unified browser API, most of the time You dont have to think about browser compatibility because guys from Your framework took care (btw. I love jQuery).

Monday, 27 February 2017

Random Question Answers


What is CORS? How does it work?

Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated. It’s a mechanism supported in HTML5 that manages XMLHttpRequest access to a domain different.
CORS adds new HTTP headers that provide access to permitted origin domains. For HTTP methods other than GET (or POST with certain MIME types), the specification mandates that browsers first use an HTTP OPTIONS request header to solicit a list of supported (and available) methods from the server. The actual request can then be submitted. Servers can also notify clients whether “credentials” (including Cookies and HTTP Authentication data) should be sent with requests.

Explain the purpose of each of the HTTP request types when used with a RESTful web service.


The purpose of each of the HTTP request types when used with a RESTful web service is as follows:
  1. GET: Retrieves data from the server (should only retrieve data and should have no other effect).
  2. POST: Sends data to the server for a new entity. It is often used when uploading a file or submitting a completed web form.
  3. PUT: Similar to POST, but used to replace an existing entity.
  4. PATCH: Similar to PUT, but used to update only certain fields within an existing entity.
  5. DELETE: Removes data from the server.
  6. TRACE: Provides a means to test what a machine along the network path receives when a request is made. As such, it simply returns what was sent.
  7. OPTIONS: Allows a client to request information about the request methods supported by a service. The relevant response header is Allow and it simply lists the supported methods. (It can also be used to request information about the request methods supported for the server where the service resides by using a * wildcard in the URI.)
  8. HEAD: Same as the GET method for a resource, but returns only the response headers (i.e., with no entity-body).
  9. CONNECT: Primarily used to establish a network connection to a resource (usually via some proxy that can be requested to forward an HTTP request as TCP and maintain the connection). Once established, the response sends a 200 status code and a “Connection Established” message.

Explain the basic structure of a MIME multipart message when used to transfer different content type parts. Provide a simple example


A simple example of a MIME multipart message is as follows:
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=frontier

This is a message with multiple parts in MIME format.
--frontier
Content-Type: text/plain

This is the body of the message.
--frontier
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64

PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg
Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==
--frontier--
Each MIME message starts with a message header. This header contains information about the message content and boundary. In this case Content-Type: multipart/mixed; boundary=frontier means that message contains multiple parts where each part is of different content type and they are separated by --frontier as their boundary.
Each part consists of its own content header (zero or more Content- header fields) and a body. Multipart content can be nested. The content-transfer-encoding of a multipart type must always be 7bit8bit, or binary to avoid the complications that would be posed by multiple levels of decoding. The multipart block as a whole does not have a charset; non-ASCII characters in the part headers are handled by the Encoded-Word system, and the part bodies can have charsets specified if appropriate for their content-type.


What is Long polling, how does it work, and why would you use it? Considering server and client resources, what is the main drawback of using long polling? Which HTML5 feature is the best alternative to long polling

The HTTP protocol is based on a request/response pattern, which means that the server cannot push any data to the client (i.e., the server can only provide data to the client in response to a client request). Long polling is a web application development pattern used to emulate pushing data from server to client. When the long polling pattern is used, the client submits a request to the server and the connection then remains active until the server is ready to send data to the client. The connection is closed only after data is sent back to the client or connection timeout occurs. The client then creates a new request when the connection is closed, thus restarting the loop.
There are two important drawbacks that need to be considered when using long polling:
  1. Long polling requests are not different from any other HTTP request and web servers handle them the same way. This means that every long poll connection will reserve server resources, potentially maxing out the number of connections the server can handle. This can lead to HTTP connection timeouts.
  2. Each web browser will limit the maximum number of connections web application can make. This means that your application load time and performance may be degraded.
In HTML5, a useful alternative to long polling is using a WebSocket. A WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content and eliminates the need for the long polling paradigm.
Another potential answer could be Server-sent DOM Events. Which is method of continuously sending data from a server to the browser, rather than repeatedly requesting it. However, this HTML5 feature is not supported by Microsoft Internet Explorer, thus making it less attractive solution.

What is an ETag and how does it work?

An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at an URL. If the resource content at that URL ever changes, a new and different ETag is assigned.
In typical usage, when an URL is retrieved the web server will return the resource along with its corresponding ETag value, which is placed in an HTTP “ETag” field:
ETag: "unique_id_of_resource_version"
The client may then decide to cache the resource, along with its ETag. Later, if the client wants to retrieve the same URL again, it will send its previously saved copy of the ETag along with the request in a "If-None-Match" field.
If-None-Match: "unique_id_of_resource_version"
On this subsequent request, the server may now compare the client’s ETag with the ETag for the current version of the resource. If the ETag values match, meaning that the resource has not changed, then the server may send back a very short response with a HTTP 304 Not Modified status. The 304 status tells the client that its cached version is still good and that it should use that.
However, if the ETag values do not match, meaning the resource has likely changed, then a full response including the resource’s content is returned, just as if ETag were not being used. In this case the client may decide to replace its previously cached version with the newly returned resource and the new ETag.

Explain the difference between stateless and stateful protocols. Which type of protocol is HTTP? Explain your answer.

stateless communications protocol treats each request as an independent transaction. It therefore does not require the server to retain any session, identity, or status information spanning multiple requests from the same source. Similarly, the requestor can not rely on any such information being retained by the responder.
In contrast, a stateful communications protocol is one in which the responder maintains “state” information (session data, identity, status, etc.) across multiple requests from the same source.
HTTP is a stateless protocol. HTTP does not require server to retain information or status about each user for the duration of multiple requests.
Some web servers implement states using different methods (using cookies, custom headers, hidden form fields etc.). However, in the very core of every web application everything relies on HTTP which is still a stateless protocol that is based on simple request/response paradigm.


Describe the key advantages of HTTP/2 as compared with HTTP 1.1.

HTTP/2 provides decreased latency to improve page load speed by supporting:
  • Data compression of HTTP headers
  • Server push technologies
  • Loading of page elements in parallel over a single TCP connection
  • Prioritization of requests
An important operational benefit of HTTP/2 is that it avoids the head-of-line blocking problem in HTTP 1.



Thursday, 19 January 2017

Random Question - PHP

Question: How array_walk function works in PHP?
Purpose: It is used to update the elements/index of original array.
How: in array_walk, two parameter are required. 
1st: original array
2nd: An callback function, with use of we update the array.

How to find duplicate email records in users table?


SELECT u1.first_name, u1.last_name, u1.email FROM users as u1
INNER JOIN (
    SELECT email FROM users GROUP BY email HAVING count(id) > 1
    ) u2 ON u1.email = u2.email;
Question: How to pass data in header while using CURL?
$url='http://www.web-technology-experts-notes.in';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'headerKey: HeaderValue ',
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));
echo curl_exec($ch);
curl_close($ch);



Question: How to pass JSON Data in CURL?
$url='http://www.web-technology-experts-notes.in';
$jsonData='{"name":"Web Technology Experts","email":"contact@web-technology-experts-notes.in"}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_close($ch);



Question: What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final keyword.

Question: How can we prevent SQL-injection in PHP? Sanitize the user data before Storing in database.
While displaying the data in browser Convert all applicable characters to HTML entities using htmlentities functions.



Question: How to redirect https to http URL and vice versa in .htaccess?
Redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Redirect http to https
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Question: What are benefits of htaccess?
We can do following benefits stuff with htaccess.
Routing the URL
Mange Error Pages for Better SEO
Redirection pages
Detect OS (like Mobile/Laptop/Ios/Android etc)
Set PHP Config variable
Set Environment variable
Allow/Deny visitors by IP Address
Password protection for File/Directory
Optimize Performance of website
Improve Site Security

Question: Difference between Apache and Nginx?
Nginx is based on event-driven architecture.
Apache is based on process-driven architecture

Nginx development started only in 2002. 
Apache initial release was in 1995.

Nginx doesn't create a new process for a new request.
Apache creates a new process for each request.

In Nginx, memory consumption is very low for serving static pages
Apache’s nature of creating new process for each request, that's why it  increases the memory consumption.

Nginx is extremely fast for serving static pages as compare to Apache.

In complex configurations apache can be configured easily as compare to Nginx.

Apache has excellent documentation as compare to Nginx. 

Nginx does not support Operating Systems like OpenVMS and IBMi where as Apache supports much wider range of Operating Systems. 

The performance and scalability of Nginx is not completely dependent on hardware resources.
The Performance and scalability of the Apache is dependent on underlying hardware resources like memory and CPU.

How does HTTPS actually work?

HTTPS is simply your standard HTTP protocol slathered with a generous layer of delicious SSL/TLS encryption goodness. Unless something goes horribly wrong (and it can), it prevents people like the infamous Eve from viewing or modifying the requests that make up your browsing experience; it’s what keeps your passwords, communications and credit card details safe on the wire between your computer and the servers you want to send this data to. Whilst the little green padlock and the letters “https” in your address bar don’t mean that there isn’t still ample rope for both you and the website you are viewing to hang yourselves elsewhere, they do at least help you communicate securely whilst you do so.

1. What is HTTPS and what does it do?

HTTPS takes the well-known and understood HTTP protocol, and simply layers a SSL/TLS (hereafter referred to simply as “SSL”) encryption layer on top of it. Servers and clients still speak exactly the same HTTP to each other, but over a secure SSL connection that encrypts and decrypts their requests and responses. The SSL layer has 2 main purposes:
  • Verifying that you are talking directly to the server that you think you are talking to
  • Ensuring that only the server can read what you send it and only you can read what it sends back
The really, really clever part is that anyone can intercept every single one of the messages you exchange with a server, including the ones where you are agreeing on the key and encryption strategy to use, and still not be able to read any of the actual data you send.

2. How an SSL connection is established

An SSL connection between a client and server is set up by a handshake, the goals of which are:
  • To satisfy the client that it is talking to the right server (and optionally visa versa)
  • For the parties to have agreed on a “cipher suite”, which includes which encryption algorithm they will use to exchange data
  • For the parties to have agreed on any necessary keys for this algorithm
Once the connection is established, both parties can use the agreed algorithm and keys to securely send messages to each other. We will break the handshake up into 3 main phases - Hello, Certificate Exchange and Key Exchange.
  1. Hello - The handshake begins with the client sending a ClientHello message. This contains all the information the server needs in order to connect to the client via SSL, including the various cipher suites and maximum SSL version that it supports. The server responds with a ServerHello, which contains similar information required by the client, including a decision based on the client’s preferences about which cipher suite and version of SSL will be used.
  2. Certificate Exchange - Now that contact has been established, the server has to prove its identity to the client. This is achieved using its SSL certificate, which is a very tiny bit like its passport. An SSL certificate contains various pieces of data, including the name of the owner, the property (eg. domain) it is attached to, the certificate’s public key, the digital signature and information about the certificate’s validity dates. The client checks that it either implicitly trusts the certificate, or that it is verified and trusted by one of several Certificate Authorities (CAs) that it also implicitly trusts. Much more about this shortly. Note that the server is also allowed to require a certificate to prove the client’s identity, but this typically only happens in very sensitive applications.
  3. Key Exchange - The encryption of the actual message data exchanged by the client and server will be done using a symmetric algorithm, the exact nature of which was already agreed during the Hello phase. A symmetric algorithm uses a single key for both encryption and decryption, in contrast to asymmetric algorithms that require a public/private key pair. Both parties need to agree on this single, symmetric key, a process that is accomplished securely using asymmetric encryption and the server’s public/private keys.
The client generates a random key to be used for the main, symmetric algorithm. It encrypts it using an algorithm also agreed upon during the Hello phase, and the server’s public key (found on its SSL certificate). It sends this encrypted key to the server, where it is decrypted using the server’s private key, and the interesting parts of the handshake are complete. The parties are sufficiently happy that they are talking to the right person, and have secretly agreed on a key to symmetrically encrypt the data that they are about to send each other. HTTP requests and responses can now be sent by forming a plaintext message and then encrypting and sending it. The other party is the only one who knows how to decrypt this message, and so Man In The Middle Attackers are unable to read or modify any requests that they may intercept.

3. Certificates

3.1 Trust

At its most basic level, an SSL certificate is simply a text file, and anyone with a text editor can create one. You can in fact trivially create a certificate claiming that you are Google Inc. and that you control the domain gmail.com. If this were the whole story then SSL would be a joke; identity verification would essentially be the client asking the server “are you Google?”, the server replying “er, yeah totally, here’s a piece of paper with ‘I am Google’ written on it” and the client saying “OK great, here’s all my data.” The magic that prevents this farce is in the digital signature, which allows a party to verify that another party’s piece of paper really is legit.
There are 2 sensible reasons why you might trust a certificate:
  • If it’s on a list of certificates that you trust implicitly
  • If it’s able to prove that it is trusted by the controller of one of the certificates on the above list
The first criteria is easy to check. Your browser has a pre-installed list of trusted SSL certificates from Certificate Authorities (CAs) that you can view, add and remove from. These certificates are controlled by a centralised group of (in theory, and generally in practice) extremely secure, reliable and trustworthy organisations like Symantec, Comodo and GoDaddy. If a server presents a certificate from that list then you know you can trust them.
The second criteria is much harder. It’s easy for a server to say “er yeah, my name is er, Microsoft, you trust Symantec and er, they totally trust me, so it’s all cool.” A somewhat smart client might then go and ask Symantec “I’ve got a Microsoft here who say that you trust them, is this true?” But even if Symantec say “yep, we know them, Microsoft are legit”, you still don’t know whether the server claiming to be Microsoft actually is Microsoft or something much worse. This is where digital signatures come in.

3.2 Digital signatures

As already noted, SSL certificates have an associated public/private key pair. The public key is distributed as part of the certificate, and the private key is kept incredibly safely guarded. This pair of asymmetric keys is used in the SSL handshake to exchange a further key for both parties to symmetrically encrypt and decrypt data. The client uses the server’s public key to encrypt the symmetric key and send it securely to the server, and the server uses its private key to decrypt it. Anyone can encrypt using the public key, but only the server can decrypt using the private key.
The opposite is true for a digital signature. A certificate can be “signed” by another authority, whereby the authority effectively goes on record as saying “we have verified that the controller of this certificate also controls the property (domain) listed on the certificate”. In this case the authority uses their private key to (broadly speaking) encrypt the contents of the certificate, and this cipher text is attached to the certificate as its digital signature. Anyone can decrypt this signature using the authority’s public key, and verify that it results in the expected decrypted value. But only the authority can encrypt content using the private key, and so only the authority can actually create a valid signature in the first place.
So if a server comes along claiming to have a certificate for Microsoft.com that is signed by Symantec (or some other CA), your browser doesn’t have to take its word for it. If it is legit, Symantec will have used their (ultra-secret) private key to generate the server’s SSL certificate’s digital signature, and so your browser use can use their (ultra-public) public key to check that this signature is valid. Symantec will have taken steps to ensure the organisation they are signing for really does own Microsoft.com, and so given that your client trusts Symantec, it can be sure that it really is talking to Microsoft Inc.

3.3 Self-signing

Note that all root CA certificates are “self-signed”, meaning that the digital signature is generated using the certificate’s own private key. There’s nothing intrinsically special about a root CA’s certificate - you can generate your own self-signed certificate and use this to sign other certificates if you want. But since your random certificate is not pre-loaded as a CA into any browsers anywhere, none of them will trust you to sign either your own or other certificates. You are effectively saying “er yeah, I’m totally Microsoft, here’s an official certificate of identity issued and signed by myself,” and all properly functioning browsers will throw up a very scary error message in response to your dodgy credentials.
This puts an enormous burden on all browser and OS publishers to trust only squeaky clean root CAs, as these are the organisations that their users end up trusting to vet websites and keep certificates safe. This is not an easy task.

3.4 What are you trusting?

It’s interesting to note that your client is technically not trying to verify whether or not it should trust the party that sent it a certificate, but whether it should trust the public key contained in the certificate. SSL certificates are completely open and public, so any attacker could grab Microsoft’s certificate, intercept a client’s request to Microsoft.com and present the legitimate certificate to it. The client would accept this and happily begin the handshake. However, when the client encrypts the key that will be used for actual data encryption, it will do so using the real Microsoft’s public key from this real certificate. Since the attacker doesn’t have Microsoft’s private key in order to decrypt it, they are now stuck. Even if the handshake is completed, they will still not be able to decrypt the key, and so will not be able to decrypt any of the data that the client sends to them. Order is maintained as long as the attacker doesn’t control a trusted certificate’s private key. If the client is somehow tricked into trusting a certificate and public key whose private key is controlled by an attacker, trouble begins.

4. Really really fun facts

4.1 Can a coffee shop monitor my HTTPS traffic over their network?

Nope. The magic of public-key cryptography means that an attacker can watch every single byte of data exchanged between your client and the server and still have no idea what you are saying to each other beyond roughly how much data you are exchanging. However, your normal HTTP traffic is still very vulnerable on an insecure wi-fi network, and a flimsy website can fall victim to any number of workarounds that somehow trick you into sending HTTPS traffic either over plain HTTP or just to the wrong place completely. For example, even if a login form submits a username/password combo over HTTPS, if the form itself is loaded insecurely over HTTP then an attacker could intercept the form’s HTML on its way to your machine and modify it to send the login details to their own endpoint.

4.2 Can my company monitor my HTTPS traffic over their network?

If you are also using a machine controlled by your company, then yes. Remember that at the root of every chain of trust lies an implicitly trusted CA, and that a list of these authorities is stored in your browser. Your company could use their access to your machine to add their own self-signed certificate to this list of CAs. They could then intercept all of your HTTPS requests, presenting certificates claiming to represent the appropriate website, signed by their fake-CA and therefore unquestioningly trusted by your browser. Since you would be encrypting all of your HTTPS requests using their dodgy certificate’s public key, they could use the corresponding private key to decrypt and inspect (even modify) your request, and then send it onto it’s intended location. They probably don’t. But they could.
Incidentally, this is also how you use a proxy to inspect and modify the otherwise inaccessibleHTTPS requests made by an iPhone app.

4.3 So what happened with Lavabit and the FBI?

Lavabit was Edward Snowden’s super-secure email provider during the NSA leaks insanity of 2013. As we’ve seen, no amount of standard hackery could allow the FBI to see any data on its way between Lavabit and its customers. Without the private key for the Lavabit SSL certificate, the agency was screwed. However, a helpful US judge told the Lavabit founder, Ladar Levison, that he had to hand over this key, effectively giving the FBI free reign to snoop traffic to its heart’s content. Levison made a valiant attempt to stall by handing over the 2,560 character key in 11 hard copy pages of 4-point type, but was slammed with an order requiring him to hand over the key in a useful format or face a $5,000/day fine until he did.
Once he complied, GoDaddy, the Lavabit CA, revoked the certificate, having (correctly) deemed it compromised. This added the Lavabit certificate to a Certificate Revocation List (CRL), a list of discredited certificates that clients should no longer trust to provide a secure connection. Compromised, self-signed or otherwise untrustworthy certificates cause browsers to display a big red error message and to either discourage or outright prohibit further actions by the user. Unfortunately, browsers will continue to trust a broken certificate until they pull the newest updates to the CRL, a process which is apparently imperfect in practice.

5. Conclusion

HTTPS is not unbreakable, and the SSL protocol has to evolve constantly as new attacks against it are discovered and squashed. But it is still an impressively robust way of transmitting secret data without caring who sees your messages. There are of course many implementation details not mentioned here, such as the exact format and order of the handshake messages, abbreviated handshakes to pick up recent sessions without having to renegotiate keys and cipher suites, and the numerous different encryption options available at each stage. The key thing to remember is that whilst HTTPS keeps data safe on the wire to its destination, it in no way protects you (as a user or a developer) against XSS or database leaks or any of the other things-that-go-bump-in-the-night. Be happy that it’s got your back, but stay vigilant. In the immortal words of Will Smith, “Walk in shadow, move in silence, guard against extra-terrestrial violence.”
If you enjoyed this, you’ll probably enjoy my post explaining the details of 2015’s FREAK vulnerability in SSL.

What is the difference between Amazon S3 and Amazon EC2 instance?

An EC2 instance is like a remote computer running Windows or Linux and on which you can install whatever software you want, including a Web server running PHP code and a database server.
Amazon S3 is just a storage service, typically used to store large binary files. Amazon also has other storage and database services, like RDS for relational databases and DynamoDB for NoSQL.
=>Although your title suggests that you are asking about the difference between Amazon S3 and Amazon EC2 instance but in post you said you want to use it for serving your clients/users so I would point that if you want a CDN (Content Delivery Network) then Amazon S3 is not a true CDN. S3 was designed for content storage. The correct Amazon service to use for content delivery is Amazon CloudFront. Rest the answer of your title has been asked. May be it help someone in future.