Rectangle 27 9

Get and Post methods have nothing to do with the server technology you are using, it works the same in php, asp.net or ruby. GET and POST are part of HTTP protocol. As mark noted, POST is more secure. POST forms are also not cached by the browser. POST is also used to transfer large quantities of data.

forms - When should I use GET or POST method? What's the difference be...

forms http post get http-method
Rectangle 27 9

Get and Post methods have nothing to do with the server technology you are using, it works the same in php, asp.net or ruby. GET and POST are part of HTTP protocol. As mark noted, POST is more secure. POST forms are also not cached by the browser. POST is also used to transfer large quantities of data.

forms - When should I use GET or POST method? What's the difference be...

forms http post get http-method
Rectangle 27 1

In contrary to what is suggested by their names, $_GET and $_POST are not tied to the GET and POST methods of the HTTP specification.

The query string (which is represented as an associative array in PHP's $_GET variable) can be part of any URL, wether you are doing a GET, POST, PUT or any other method on that URL. Although query strings are most commonly used with GET methods, they are certainly not limited to them. So, when POSTing a form to a URL that contains a query string (as per the example), the keys and values of the query string will be available in the $_GET variable.

$_QUERY_STRING would probably have been a better name for this variable.

It works slightly different the other way around. Although the POST method is not the only one that can contain a body (for instance, a PUT request can as well), some testing reveals that $_POST only contains data in case of a POST request - it is empty in all other cases.

PHP does not have a $_PUT variable to use with PUT request, probably because browsers only support GET and POST requests for form submission. Instead, you can use file_get_contents("php://input") to read from the incoming stream to PHP, and then use str_parse() to load the keys and values as an associative array:

parse_str(file_get_contents("php://input"), $data);

I found a number of questions about GET vs POST and about $_GET vs $_POST, but none of them covered this specific aspect. If you find one that does, let me know.

@OptimusCrime - answering your own question is fine. That's why the "ask question" page has a checkbox that opens an answer form to be posted at the same time as the question.

Are PHP's $_GET and $_POST tied to the HTTP GET and POST methods, resp...

php http post get
Rectangle 27 666

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 662

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 648

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

This would be a better answer without the highly opinionated order of best practice.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 644

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 644

1. Use AJAX to get the data you need from the server

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

  • Use AJAX to get the data you need from the server.
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

your server side and client side scripts are completely separate

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for async data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.
  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g. if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 * 
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well. 
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); //In the end, you need to echo the result. 
                      //All data should be json_encode()d.

                      //You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); //New request object
    oReq.onload = function() {
        //This is where you handle what to do with the response.
        //The actual data is found on this.responseText
        alert(this.responseText); //Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to 
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.
  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JS that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php 
        $output = "42"; //Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

This is probably the easiest to understand, and the most horrible to use. Don't do this unless you know what you're doing.

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.
  • Insecure - PHP has no trivial JavaScript escape functions, and they aren't trivial to implement. Especially when using user inputs, you are extremely vulnerable to second tier injections. Disputed see comments
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.
  • Structured data is hard - You can probably do JSON... kinda. But XML and HTML will require special attention.
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; //Don't forget the extra semicolon!
</script>
<!-- snip -->

"PHP has no trivial JavaScript escape functions" What is wrong with json_encode?

I disagree with "Highly insecure!!" and "Structured data is hard". Encode data as JSON (JavaScript Object Notation, after all), and there you go!

What about the significant overhead and code complexity asynchronousity introduces when making an AJAX request? When working on a JavaScript light website - making an AJAX request is tedious and not best practices.

@BenjaminGruenbaum JS being invalid JSON is irrelevant. I can't think of any JSON that is invalid in JavaScript on the right hand side of an assignment.

@SecondRikudo In method 3, that example can kill the website. Example: <?php $output = '<!--<script>'; echo json_encode($output); ?>. See this question for details. Solution: Use JSON_HEX_TAG to escape < and > (requires PHP 5.3.0).

How to pass variables and data from PHP to JavaScript? - Stack Overflo...

javascript php
Rectangle 27 3

If you do not want to use CURL, you could find some examples on stackoverflow, just like this one here: How do I send a POST request with PHP?. I would recommend you watch a few tutorials on how to use GET and POST methods within PHP or just take a look at the php.net manual here: httprequest::send. You can find a lot of tutorials: HTTP POST from PHP, without cURL and so on...

php - POST request with JSON body - Stack Overflow

php json post
Rectangle 27 13

Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.

$method = $_SERVER['REQUEST_METHOD']
if ($method == 'POST') {
    // Method is POST
} elseif ($method == 'GET') {
    // Method is GET
} elseif ($method == 'PUT') {
    // Method is PUT
} elseif ($method == 'DELETE') {
    // Method is DELETE
} else {
    // Method unknown
}

You could also do it using a switch if you prefer this over the if-else statement.

If a method other than GET or POST is required in an html form, this is often solved using an hidden field in the form.

<!-- DELETE method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="DELETE">
</form>

<!-- PUT method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="PUT">
</form>

Detecting request type in PHP (GET, POST, PUT or DELETE) - Stack Overf...

php request
Rectangle 27 13

Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.

$method = $_SERVER['REQUEST_METHOD']
if ($method == 'POST') {
    // Method is POST
} elseif ($method == 'GET') {
    // Method is GET
} elseif ($method == 'PUT') {
    // Method is PUT
} elseif ($method == 'DELETE') {
    // Method is DELETE
} else {
    // Method unknown
}

You could also do it using a switch if you prefer this over the if-else statement.

If a method other than GET or POST is required in an html form, this is often solved using an hidden field in the form.

<!-- DELETE method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="DELETE">
</form>

<!-- PUT method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="PUT">
</form>

Detecting request type in PHP (GET, POST, PUT or DELETE) - Stack Overf...

php request
Rectangle 27 13

Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.

$method = $_SERVER['REQUEST_METHOD']
if ($method == 'POST') {
    // Method is POST
} elseif ($method == 'GET') {
    // Method is GET
} elseif ($method == 'PUT') {
    // Method is PUT
} elseif ($method == 'DELETE') {
    // Method is DELETE
} else {
    // Method unknown
}

You could also do it using a switch if you prefer this over the if-else statement.

If a method other than GET or POST is required in an html form, this is often solved using an hidden field in the form.

<!-- DELETE method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="DELETE">
</form>

<!-- PUT method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="PUT">
</form>

Detecting request type in PHP (GET, POST, PUT or DELETE) - Stack Overf...

php request
Rectangle 27 13

Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.

$method = $_SERVER['REQUEST_METHOD']
if ($method == 'POST') {
    // Method is POST
} elseif ($method == 'GET') {
    // Method is GET
} elseif ($method == 'PUT') {
    // Method is PUT
} elseif ($method == 'DELETE') {
    // Method is DELETE
} else {
    // Method unknown
}

You could also do it using a switch if you prefer this over the if-else statement.

If a method other than GET or POST is required in an html form, this is often solved using an hidden field in the form.

<!-- DELETE method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="DELETE">
</form>

<!-- PUT method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="PUT">
</form>

Detecting request type in PHP (GET, POST, PUT or DELETE) - Stack Overf...

php request
Rectangle 27 168

To make ajax request using jQuery you can do this by following code

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
/* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {
           // you will get response from your php page (what you echo or print)                 

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
     var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    /* I am not aborting previous request because It's an asynchronous request, meaning 
       Once it's sent it's out there. but in case you want to abort it  you can do it by  
       abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

      /*  request cab be abort by ajaxRequest.abort() */

     ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          $("#result").html('Submitted successfully');
     });

     /* On failure of request this function will be called  */
     ajaxRequest.fail(function (){

       // show error
       $("#result").html('There is error while submit');
     });

The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.

MDN: abort() . If the request has been sent already, this method will abort the request.

PHP

As we make a POST request in ajax call ( type: "post" ) we can now grab data using either $_REQUEST or $_POST

$bar = $_POST['bar']

You can also see what you get in POST request by simply either, Btw make sure that $_POST is set other wise you will get error.

var_dump($_POST);
// or
print_r($_POST);

And you are inserting value to database make sure you are sensitizing or escaping All request ( weather you made GET or POST) properly before making query, Best would be using prepared statements.

and if you want to return any data back to page, you can do it by just echoing that data like below.

// 1. Without JSON
   echo "hello this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

and than you can get it like

ajaxRequest.done(function (response){  
    alert(response);
 });

There are Couple of Shorthand Methods you can use below code it do the same work.

var ajaxRequest= $.post( "test.php",values, function(data) {
  alert( data );
})
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

Pointer : what is bar in $id = $_POST['bar']; and how it works ???

@Clarence bar is input type text name and since i am suing post method so $_POST['bar'] is used to get value of it

For anyone wanting to use json - while using JSON the call should contain the parameter dataType: 'json'

@CarlLindberg - What if you want jQuery to guess based on the MIME type of the response (which is what it should do when you don't set the dataType), so that you can potentially accept JSON or some other format?

@nnnnnn you are right - that's way better - indeed is default: Intelligent Guess

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post
Rectangle 27 162

To make ajax request using jQuery you can do this by following code

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
/* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {
           // you will get response from your php page (what you echo or print)                 

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
     var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    /* I am not aborting previous request because It's an asynchronous request, meaning 
       Once it's sent it's out there. but in case you want to abort it  you can do it by  
       abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

      /*  request cab be abort by ajaxRequest.abort() */

     ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          $("#result").html('Submitted successfully');
     });

     /* On failure of request this function will be called  */
     ajaxRequest.fail(function (){

       // show error
       $("#result").html('There is error while submit');
     });

The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.

MDN: abort() . If the request has been sent already, this method will abort the request.

PHP

As we make a POST request in ajax call ( type: "post" ) we can now grab data using either $_REQUEST or $_POST

$bar = $_POST['bar']

You can also see what you get in POST request by simply either, Btw make sure that $_POST is set other wise you will get error.

var_dump($_POST);
// or
print_r($_POST);

And you are inserting value to database make sure you are sensitizing or escaping All request ( weather you made GET or POST) properly before making query, Best would be using prepared statements.

and if you want to return any data back to page, you can do it by just echoing that data like below.

// 1. Without JSON
   echo "hello this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

and than you can get it like

ajaxRequest.done(function (response){  
    alert(response);
 });

There are Couple of Shorthand Methods you can use below code it do the same work.

var ajaxRequest= $.post( "test.php",values, function(data) {
  alert( data );
})
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

Pointer : what is bar in $id = $_POST['bar']; and how it works ???

@Clarence bar is input type text name and since i am suing post method so $_POST['bar'] is used to get value of it

For anyone wanting to use json - while using JSON the call should contain the parameter dataType: 'json'

@CarlLindberg - What if you want jQuery to guess based on the MIME type of the response (which is what it should do when you don't set the dataType), so that you can potentially accept JSON or some other format?

@nnnnnn you are right - that's way better - indeed is default: Intelligent Guess

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post
Rectangle 27 162

To make ajax request using jQuery you can do this by following code

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
/* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {
           // you will get response from your php page (what you echo or print)                 

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
     var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    /* I am not aborting previous request because It's an asynchronous request, meaning 
       Once it's sent it's out there. but in case you want to abort it  you can do it by  
       abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

      /*  request cab be abort by ajaxRequest.abort() */

     ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          $("#result").html('Submitted successfully');
     });

     /* On failure of request this function will be called  */
     ajaxRequest.fail(function (){

       // show error
       $("#result").html('There is error while submit');
     });

The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.

MDN: abort() . If the request has been sent already, this method will abort the request.

PHP

As we make a POST request in ajax call ( type: "post" ) we can now grab data using either $_REQUEST or $_POST

$bar = $_POST['bar']

You can also see what you get in POST request by simply either, Btw make sure that $_POST is set other wise you will get error.

var_dump($_POST);
// or
print_r($_POST);

And you are inserting value to database make sure you are sensitizing or escaping All request ( weather you made GET or POST) properly before making query, Best would be using prepared statements.

and if you want to return any data back to page, you can do it by just echoing that data like below.

// 1. Without JSON
   echo "hello this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

and than you can get it like

ajaxRequest.done(function (response){  
    alert(response);
 });

There are Couple of Shorthand Methods you can use below code it do the same work.

var ajaxRequest= $.post( "test.php",values, function(data) {
  alert( data );
})
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

Pointer : what is bar in $id = $_POST['bar']; and how it works ???

@Clarence bar is input type text name and since i am suing post method so $_POST['bar'] is used to get value of it

For anyone wanting to use json - while using JSON the call should contain the parameter dataType: 'json'

@CarlLindberg - What if you want jQuery to guess based on the MIME type of the response (which is what it should do when you don't set the dataType), so that you can potentially accept JSON or some other format?

@nnnnnn you are right - that's way better - indeed is default: Intelligent Guess

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post
Rectangle 27 162

To make ajax request using jQuery you can do this by following code

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
/* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {
           // you will get response from your php page (what you echo or print)                 

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
     var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    /* I am not aborting previous request because It's an asynchronous request, meaning 
       Once it's sent it's out there. but in case you want to abort it  you can do it by  
       abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

      /*  request cab be abort by ajaxRequest.abort() */

     ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          $("#result").html('Submitted successfully');
     });

     /* On failure of request this function will be called  */
     ajaxRequest.fail(function (){

       // show error
       $("#result").html('There is error while submit');
     });

The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.

MDN: abort() . If the request has been sent already, this method will abort the request.

PHP

As we make a POST request in ajax call ( type: "post" ) we can now grab data using either $_REQUEST or $_POST

$bar = $_POST['bar']

You can also see what you get in POST request by simply either, Btw make sure that $_POST is set other wise you will get error.

var_dump($_POST);
// or
print_r($_POST);

And you are inserting value to database make sure you are sensitizing or escaping All request ( weather you made GET or POST) properly before making query, Best would be using prepared statements.

and if you want to return any data back to page, you can do it by just echoing that data like below.

// 1. Without JSON
   echo "hello this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

and than you can get it like

ajaxRequest.done(function (response){  
    alert(response);
 });

There are Couple of Shorthand Methods you can use below code it do the same work.

var ajaxRequest= $.post( "test.php",values, function(data) {
  alert( data );
})
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

Pointer : what is bar in $id = $_POST['bar']; and how it works ???

@Clarence bar is input type text name and since i am suing post method so $_POST['bar'] is used to get value of it

For anyone wanting to use json - while using JSON the call should contain the parameter dataType: 'json'

@CarlLindberg - What if you want jQuery to guess based on the MIME type of the response (which is what it should do when you don't set the dataType), so that you can potentially accept JSON or some other format?

@nnnnnn you are right - that's way better - indeed is default: Intelligent Guess

javascript - jQuery Ajax POST example with PHP - Stack Overflow

php javascript jquery ajax post
Rectangle 27 4

The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:

'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/save-json/',
                'defaults' => array(
                    'controller' => 'CDB\Controller\Index',
                    'action'     => 'save-json',
                ),
            ),
        ),

and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend

$this->params()->fromPost('paramname');

didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':

$content = file_get_contents('php://input');
print_r(json_decode($content));

If you need the raw POST body use the getContent() of the request object. From a controller, you could do: $content = $this->getRequest()->getContent()

On ZF2 how can we retrieve a URL parameter in the form of ?name=mike ?

php - How to access route, post, get etc. parameters in Zend Framework...

php file-upload zend-route zend-framework2
Rectangle 27 1

If you want a simple ajax update, say, when the user presses a refresh button try using jQuery's .get or .post methods

If your looking for real time or "Push" updates, you'll need websockets and mysql triggers. You'll need a "daemon" script to handle your connections and you'll need to notify that script some how that the database has changed.

Option #3 Another option for "Real Time" depending on how many users you need to accommodate and your server stats is to do a "Pull" method. In this case you use a javascript timer to do the ajax request mentioned in option 1 every X amount of seconds.

This is a lot easier then building a push service or integrating with an existing one but the draw back is obviously if there is no new data then the users are making unnecessary requests to the server and also technically this is not "Real Time" as it only updates as fast as you set your timer

Your refresh button needs to be outside of the element thats being refreshed. So I would recommend something like this:

<div> 
   <button onclick="updateData();">Refresh</button> 
</div> 
<div id="dataContainer"> 
    <?php include "db-info.php"; ?> 
</div>

<script> 
function updateData(){    
     $.get( "db-info.php", function(data ) {       
        $( "#dataContainer" ).html( data );    
      }); 
}; 
</script>

Also I would try to avoid doing the extra ajax callback onload to load the initial data, unless there is a reason for it. By using the php include for the initial page load, your saving your self at least 1 extra request per page load.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

mysql - how to force refresh of included php when database is updated ...

php mysql ajax page-refresh
Rectangle 27 24

<?php
echo readfile("http://example.com/");   //needs "Allow_url_include" enable
//OR
echo include("http://example.com/");    //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
?>
echo get_remote_data('http://example.com/?var2=something&var3=blabla');     // GET request 
echo get_remote_data('http://example.com/', 'var2=something&var3=blabla' ); // POST request


//See Updates and explanation at: https://github.com/tazotodua/useful-php-scripts/

function get_remote_data($url, $post_paramtrs = false) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    if ($post_paramtrs) {
        curl_setopt($c, CURLOPT_POST, TRUE);
        curl_setopt($c, CURLOPT_POSTFIELDS, "var1=bla&" . $post_paramtrs);
    } curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:33.0) Gecko/20100101 Firefox/33.0");
    curl_setopt($c, CURLOPT_COOKIE, 'CookieName1=Value;');
    curl_setopt($c, CURLOPT_MAXREDIRS, 10);
    $follow_allowed = ( ini_get('open_basedir') || ini_get('safe_mode')) ? false : true;
    if ($follow_allowed) {
        curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
    }curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 9);
    curl_setopt($c, CURLOPT_REFERER, $url);
    curl_setopt($c, CURLOPT_TIMEOUT, 60);
    curl_setopt($c, CURLOPT_AUTOREFERER, true);
    curl_setopt($c, CURLOPT_ENCODING, 'gzip,deflate');
    $data = curl_exec($c);
    $status = curl_getinfo($c);
    curl_close($c);
    preg_match('/(http(|s)):\/\/(.*?)\/(.*\/|)/si', $status['url'], $link);
    $data = preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/|\/)).*?)(\'|\")/si', '$1=$2' . $link[0] . '$3$4$5', $data);
    $data = preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/)).*?)(\'|\")/si', '$1=$2' . $link[1] . '://' . $link[3] . '$3$4$5', $data);
    if ($status['http_code'] == 200) {
        return $data;
    } elseif ($status['http_code'] == 301 || $status['http_code'] == 302) {
        if (!$follow_allowed) {
            if (empty($redirURL)) {
                if (!empty($status['redirect_url'])) {
                    $redirURL = $status['redirect_url'];
                }
            } if (empty($redirURL)) {
                preg_match('/(Location:|URI:)(.*?)(\r|\n)/si', $data, $m);
                if (!empty($m[2])) {
                    $redirURL = $m[2];
                }
            } if (empty($redirURL)) {
                preg_match('/href\=\"(.*?)\"(.*?)here\<\/a\>/si', $data, $m);
                if (!empty($m[1])) {
                    $redirURL = $m[1];
                }
            } if (!empty($redirURL)) {
                $t = debug_backtrace();
                return call_user_func($t[0]["function"], trim($redirURL), $post_paramtrs);
            }
        }
    } return "ERRORCODE22 with $url!!<br/>Last status codes<b/>:" . json_encode($status) . "<br/><br/>Last data got<br/>:$data";
}

p.s.on GNU/Linux distro servers, you might need to install the php5-curl package to use it.

Why curl is "Better way"? Are these reasons absolute or relative-to requirements? thanks :)

There's conflicting information in those above links: "FWIW there's little difference with regards to speed. I've just finished fetching 5,000 URLs and saving their HTML to files (about 200k per file). I did half with curl and half with file_get_contents as an experiment and there was no discernible difference." and follow-on comment "I benchmarked the two on 5.3 and 5.4, and cURL still is considerably faster than file_get_contents, especially for multiple calls on the same request." vs "A few years ago I benchmarked the two and CURL was faster."...

You sir have saved me today, thank you for thy good deed !

@tazo todua How can I get the html text, when I run this example it display the whole website view.

get url content PHP - Stack Overflow

php url curl file-get-contents