{"id":959,"date":"2016-06-02T11:47:29","date_gmt":"2016-06-02T18:47:29","guid":{"rendered":"http:\/\/blog.ls-al.com\/?p=959"},"modified":"2016-06-02T11:47:29","modified_gmt":"2016-06-02T18:47:29","slug":"cors-example-with-php","status":"publish","type":"post","link":"https:\/\/blog.ls-al.com\/cors-example-with-php\/","title":{"rendered":"CORS Example with PHP"},"content":{"rendered":"
Mostly serving web pages you have the capability to do dynamic scripting since it is done on the same server. However if you do need to do this CORS allows the mechanism. Explained well at this link: http:\/\/enable-cors.org\/<\/p>\n
\"JavaScript and the web programming has grown by leaps and bounds over the years, but the same-origin policy still remains. This prevents JavaScript from making requests across domain boundaries, and has spawned various hacks for making cross-domain requests.<\/em><\/span><\/p>\n CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed. CORS continues the spirit of the open web by bringing API access to all.\"<\/em><\/span><\/p>\n In my case I wanted to proof this because I have a http enabled S3 bucket on Amazon AWS. Meaning all static. So one example of a need for this would be a contact form or quick lookup in a database etc. My example below is very simple. S3 website has a submit form button that use javascript to send the request to a PHP enable nginx server. PHP script look up the JSON value passed to it in an array and pass the value back.<\/p>\n S3 static web page:<\/strong><\/p>\n PHP script.<\/strong><\/p>\n In this case you can see all the headers are handled inside the PHP script. You can of course handle it with the web server also. Details for web servers here: http:\/\/enable-cors.org\/server.html<\/p>\n Thanks to this excellent reference. There are a lot of very confusing discussions on this topic. Especially around pre-flight checking. Mostly serving web pages you have the capability to do dynamic scripting since it is done on the same server.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[66,55,19],"tags":[65],"class_list":["post-959","post","type-post","status-publish","format-standard","hentry","category-cors","category-javascript","category-php","tag-cors"],"_links":{"self":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/959","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/comments?post=959"}],"version-history":[{"count":0,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/959\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/media?parent=959"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/categories?post=959"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/tags?post=959"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}\r\n<html>\r\n\r\n<head>\r\n<script type="text\/javascript">\r\n\r\n\/\/window.onload = doAjax();\r\n\r\nfunction doAjax(last_name) {\r\n var url = "http:\/\/my.phpserver.domain\/api\/cors_contact.php";\r\n \r\n \/\/var request = JSON.stringify({searchterm:"doe"});\r\n \/\/var search_st = 'searchterm:' + 'last_name';\r\n \/\/alert(search_st);\r\n var request = JSON.stringify({searchterm:last_name});\r\n \/\/alert (request);\r\n var xmlhttp = new XMLHttpRequest();\r\n\r\n xmlhttp.open("POST", url);\r\n xmlhttp.setRequestHeader("Content-Type", "application\/json; charset=UTF-8");\r\n xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");\r\n xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");\r\n xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");\r\n xmlhttp.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");\r\n\r\n xmlhttp.onreadystatechange = function() {\r\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\r\n var jsondata = JSON.parse(xmlhttp.responseText);\r\n \/\/document.getElementById("id01").innerHTML = xmlhttp.responseText;\r\n document.getElementById("id02").innerHTML = jsondata.word;\r\n }\r\n };\r\n\r\n xmlhttp.send(request);\r\n}\r\n\r\nfunction searchKeyPress(e)\r\n{\r\n \/\/ look for window.event in case event isn't passed in\r\n e = e || window.event;\r\n if (e.keyCode == 13)\r\n {\r\n document.getElementById('Submit').click();\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\n<\/script>\r\n<\/head>\r\n<body>\r\n<div id="id01"><\/div>\r\n<div id="id02"><\/div>\r\n<form name="contactform" id="controlsToInvoke" action="">\r\n<table width="450px">\r\n<tr>\r\n<td valign="top"">\r\n <label for="last_name">Last Name *<\/label>\r\n <\/td>\r\n<td valign="top">\r\n <input type="text" id="last_name" name="last_name" maxlength="50" size="30" onkeypress="return searchKeyPress(event);" \/>\r\n <\/td>\r\n<\/tr>\r\n<tr>\r\n<td colspan="2" style="text-align:center">\r\n <input type="button" id="Submit" value="Submit" onclick="doAjax(document.getElementById('last_name').value)" \/>\r\n <\/td>\r\n<\/tr>\r\n<\/table>\r\n<\/form>\r\n<\/body>\r\n<\/html>\r\n<\/pre>\n
\r\n<?php $dictionary = array('doe' => 'j.doe@email.domain', 'smith' => 'asmith@email2.domain', 'stranger' => 'noname@noname.com');\r\n\r\nif ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {\r\n if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {\r\n header('Access-Control-Allow-Origin: *');\r\n header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');\r\n }\r\n exit;\r\n}\r\n\r\n$json = file_get_contents('php:\/\/input');\r\n$obj = json_decode($json);\r\n\r\nif (array_key_exists($obj->searchterm, $dictionary)) {\r\n $response = json_encode(array('result' => 1, 'word' => $dictionary[$obj->searchterm]));\r\n}\r\nelse {\r\n $response = json_encode(array('result' => 0, 'word' => 'Not Found'));\r\n}\r\n\r\nheader('Content-type: application\/json');\r\nheader('Access-Control-Allow-Origin: *');\r\necho $response;\r\n\r\n<\/pre>\n
\nhttp:\/\/www.mjhall.org\/php-cross-origin-resource-sharing\/<\/p>\n","protected":false},"excerpt":{"rendered":"