I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest
I´m currently working on a school project, where we are using Apache cordova (HTML, CSS and JS side) and currently our school has a server, where our .php file is located.
In our project, (one of the HTML files) we use API key and an domain address, that we want to get rid off from source code (so other students cant see it). What would be easiest way to execute this?
We´ve been thinking following;
We use the php-file as a wrapper with the following code;
IE.
<?php
function getJson($data){
$decoded = json_decode($data);
if (isset($decoded)){
// Toteutusten haku
$url = "URL THAT WE DONT WANT TO BE SEEN";
$apiKey = "API KEY GOES HERE";
// curl
$ch = curl_init($url);
// curl_exec returnsanswer (not boolean)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Asets api key, ":"
curl_setopt($ch, CURLOPT_USERPWD, $apiKey.":");
// Setting message - JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Sets false if necessary
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Sends request
$responseJson = curl_exec($ch);
return $responseJson;
curl_close($ch); //close session
**}
}
?>
And in HTML file we have code snippets that looks like following;
// B building rooms
if (buildingcode.startsWith("B", 5)) {
var requestB = new XMLHttpRequest();
requestB.onreadystatechange = function () {
if (requestB.readyState === 4) {
if (requestB.status === 200) {
try {
var jsonB = JSON.parse(requestB.responseText);
for (var fb = 0; fb < jsonB.resources.length; fb++) {
var resB = jsonB.resources[fb];
if (resB.type === "room") {
if (bTilat.indexOf("code")) {
bTilat.push(resB.code + resB.name.slice(resB.name.indexOf(' ('), 50));
}
}
}
} catch (e) {
console.log(e.message);
return;
}
}
}
//console.log(bTilat);
};
requestB.open("GET", 'THIS PART HAS THE DOMAIN WE WANT TO HIDE', true, "THIS PART HAS THE API WE WANT TO HIDE", "");
requestB.send(null);
}
So my question is following; I guess we need to get rid off
requestB.open("GET", 'THIS PART HAS THE DOMAIN WE WANT TO HIDE', true, "THIS PART HAS THE API WE WANT TO HIDE", "");
requestB.send(null);
From html, but how do we request the code from wrapper?
Thank you in advance.
I paid a programmer to make a shop basket script to work with Spreadshirt API. Everything is working perfectly, except that the basket keeps emptying itself. I think the session is lost at some point so the script creates another BasketId.
I tried to find if there was a specific reason it was happening, without any success... I can't reproduce the bug. It just happens randomly without any reason. Closing the browser, resetting apache or even the whole webserver won't provoke session lost.
I've got two different scripts working with cookies on the same domain and they don't have any problem (one is a cookie for the admin login session and the other cookie is to save the user's last viewed articles on the shop)
I tried all solutions found on google without any success : editing php.ini , forcing ini settings through php, tried the htaccess way, ...
Here's the "sessions" part of my phpinfo: http://gyazo.com/168e2144ddd9ee368a05754dfd463021
shop-ajax.php (session handling # line 18)
ini_set('session.cookie_domain', '.mywebsite.com' );
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
$language = addslashes($_GET['l']);
$shopid = addslashes($_GET['shop']);
// if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
// die("no direct access allowed");
// }
if(!session_id()) {
$lifetime=60 * 60 * 24 * 365;
$domain = ".mywebsite.com";
session_set_cookie_params($lifetime,"/",$domain);
#session_start();
}
// Configuration
$config['ShopSource'] = "com";
$config['ShopId'] = $shopid;
$config['ShopKey'] = "*****";
$config['ShopSecret'] = "*****";
/*
* add an article to the basket
*/
if (isset($_POST['size']) && isset($_POST['appearance']) && isset($_POST['quantity'])) {
/*
* create an new basket if not exist
*/
if (!isset($_SESSION['basketUrl'])) {
/*
* get shop xml
*/
$stringApiUrl = 'http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $config['ShopId'];
$stringXmlShop = oldHttpRequest($stringApiUrl, null, 'GET');
if ($stringXmlShop[0]!='<') die($stringXmlShop);
$objShop = new SimpleXmlElement($stringXmlShop);
if (!is_object($objShop)) die('Basket not loaded');
/*
* create the basket
*/
$namespaces = $objShop->getNamespaces(true);
$basketUrl = createBasket('net', $objShop, $namespaces);
$_SESSION['basketUrl'] = $basketUrl;
$_SESSION['namespaces'] = $namespaces;
/*
* get the checkout url
*/
$checkoutUrl = checkout($_SESSION['basketUrl'], $_SESSION['namespaces']);
// basket language workaround
if ($language=="fr") {
if (!strstr($checkoutUrl,'/fr')) {
$checkoutUrl = str_replace("spreadshirt.com","spreadshirt.com/fr",$checkoutUrl);
}
}
$_SESSION['checkoutUrl'] = $checkoutUrl;
}
/*
Workaround for not having the appearance id :(
*/
if ($_POST['appearance']==0) {
$stringApiArticleUrl = 'http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $config['ShopId'].'/articles/'.intval($_POST['article']).'?fullData=true';
$stringXmlArticle = oldHttpRequest($stringApiArticleUrl, null, 'GET');
if ($stringXmlArticle[0]!='<') die($stringXmlArticle);
$objArticleShop = new SimpleXmlElement($stringXmlArticle);
if (!is_object($objArticleShop)) die('Article not loaded');
$_POST['appearance'] = intval($objArticleShop->product->appearance['id']);
}
/*
* article data to be sent to the basket resource
*/
$data = array(
'articleId' => intval($_POST['article']),
'size' => intval($_POST['size']),
'appearance' => intval($_POST['appearance']),
'quantity' => intval($_POST['quantity']),
'shopId' => $config['ShopId']
);
/*
* add to basket
*/
addBasketItem($_SESSION['basketUrl'] , $_SESSION['namespaces'] , $data);
$basketData = prepareBasket();
echo json_encode(array("c" => array("u" => $_SESSION['checkoutUrl'],"q" => $basketData[0],"l" => $basketData[1])));
}
// no call, just read basket if not empty
if (isset($_GET['basket'])) {
if (array_key_exists('basketUrl',$_SESSION) && !empty($_SESSION['basketUrl'])) {
$basketData = prepareBasket();
echo json_encode(array("c" => array("u" => $_SESSION['checkoutUrl'],"q" => $basketData[0],"l" => $basketData[1])));
} else {
echo json_encode(array("c" => array("u" => "","q" => 0,"l" => "")));
}
}
function prepareBasket() {
$intInBasket=0;
if (isset($_SESSION['basketUrl'])) {
$basketItems=getBasket($_SESSION['basketUrl']);
if(!empty($basketItems)) {
foreach($basketItems->basketItems->basketItem as $item) {
$intInBasket += $item->quantity;
}
}
}
$l = "";
$pQ = parse_url($_SESSION['checkoutUrl']);
if (preg_match("#^basketId\=([0-9a-f\-])*$#i", $pQ['query'])) {
$l = $pQ['query'];
}
return array($intInBasket,$l);
}
// Additional functions
function addBasketItem($basketUrl, $namespaces, $data) {
global $config;
$basketItemsUrl = $basketUrl . "/items";
$basketItem = new SimpleXmlElement('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<basketItem xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">
<quantity>' . $data['quantity'] . '</quantity>
<element id="' . $data['articleId'] . '" type="sprd:article" xlink:href="http://api.spreadshirt.'.$config['ShopSource'].'/api/v1/shops/' . $data['shopId'] . '/articles/' . $data['articleId'] . '">
<properties>
<property key="appearance">' . $data['appearance'] . '</property>
<property key="size">' . $data['size'] . '</property>
</properties>
</element>
<links>
<link type="edit" xlink:href="http://' . $data['shopId'] .'.spreadshirt.' .$config['ShopSource'].'/-A' . $data['articleId'] . '"/>
<link type="continueShopping" xlink:href="http://' . $data['shopId'].'.spreadshirt.'.$config['ShopSource'].'"/>
</links>
</basketItem>');
$header = array();
$header[] = createAuthHeader("POST", $basketItemsUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketItemsUrl, $header, 'POST', $basketItem->asXML());
}
function createBasket($platform, $shop, $namespaces) {
$basket = new SimpleXmlElement('<basket xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://api.spreadshirt.net">
<shop id="' . $shop['id'] . '"/>
</basket>');
$attributes = $shop->baskets->attributes($namespaces['xlink']);
$basketsUrl = $attributes->href;
$header = array();
$header[] = createAuthHeader("POST", $basketsUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketsUrl, $header, 'POST', $basket->asXML());
$basketUrl = parseHttpHeaders($result, "Location");
return $basketUrl;
}
function checkout($basketUrl, $namespaces) {
$basketCheckoutUrl = $basketUrl . "/checkout";
$header = array();
$header[] = createAuthHeader("GET", $basketCheckoutUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketCheckoutUrl, $header, 'GET');
$checkoutRef = new SimpleXMLElement($result);
$refAttributes = $checkoutRef->attributes($namespaces['xlink']);
$checkoutUrl = (string)$refAttributes->href;
return $checkoutUrl;
}
/*
* functions to build headers
*/
function createAuthHeader($method, $url) {
global $config;
$time = time() *1000;
$data = "$method $url $time";
$sig = sha1("$data ".$config['ShopSecret']);
return "Authorization: SprdAuth apiKey=\"".$config['ShopKey']."\", data=\"$data\", sig=\"$sig\"";
}
function parseHttpHeaders($header, $headername) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach($fields as $field) {
if (preg_match('/(' . $headername . '): (.+)/m', $field, $match)) {
return $match[2];
}
}
return $retVal;
}
function getBasket($basketUrl) {
$header = array();
$basket = "";
if (!empty($basketUrl)) {
$header[] = createAuthHeader("GET", $basketUrl);
$header[] = "Content-Type: application/xml";
$result = oldHttpRequest($basketUrl, $header, 'GET');
$basket = new SimpleXMLElement($result);
}
return $basket;
}
function oldHttpRequest($url, $header = null, $method = 'GET', $data = null, $len = null) {
switch ($method) {
case 'GET':
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
if (!is_null($header)) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
break;
case 'POST':
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true); //not createBasket but addBasketItem
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
There's also 2 other parts of the script : a form to add a sample tshirt to the basket (example.php) and a script to call the ajax (shop-controller.js). Can post it if needed but there's no session handling stuff.
update - Maybe the problem is not related to sessions. The BasketId is lost, but PHPSESSID stays the same in the browser cookies.
I did the following tests for the last 3 days (tested with diferent computers and browsers):
Empty browser cookies then start a new session during the afternoon
Add 1 item to basket, i write down the BasketId and check the browsers cookies to write down the PHPSESSID
Usually always around midnight, the basket empty itself
PHPSESSID stays the same in my browser cookies, even after basket empty itself
However the BASKETID is not the same, the one used during the afternoon is lost and a new one is regenerated
Server is CentOS 5.9 - PHP Version 5.2.9 (from OVH). Dedicated server on a dedicated IP.
First you need to find if the problem is in session's garbage collection or a logical error within the code. For that, you can:
// Add this right after session_start()
if (!isset($_SESSION['mySessionCheck'])) {
$_SESSION['mySessionCheck'] = "This session (" . session_id() . ") started " . date("Y-m-d H:i:s");
}
// For HTML pages, add this:
echo '<!-- ' . $_SESSION['mySessionCheck'] . ' -->';
// For AJAX pages, add "mySessionCheck" to the JSON response:
echo json_encode(
array(
"c" => array(
"u" => $_SESSION['checkoutUrl'],
"q" => $basketData[0],
"l" => $basketData[1]
),
"mySessionCheck" => $_SESSION['mySessionCheck']
)
);
If this message changes at the same time the basket empties, then you'll know for sure it's a problem with PHP sessions.
In that case, there are a few things you can try:
1) You are doing
$lifetime=60 * 60 * 24 * 365;
$domain = ".mywebsite.com";
session_set_cookie_params($lifetime,"/",$domain);
#session_start();
But according to a user contributed note from PHP.net docs:
PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params().
So you may try using setcookie() instead:
$lifetime=60 * 60 * 24 * 365;
session_start();
setcookie(session_name(),session_id(),time()+$lifetime);
Even though it's a 4 year old note as pointed in the comments, I tested it and it still happens (I'm on PHP 5.5.7, Windows Server 2008, IIS/7.5). Only setcookie() produced the HTTP headers to change the expiring date (example setting $lifetime to 600):
Set-Cookie: PHPSESSID=(the id); expires=Mon, 22-Jun-2015 15:03:17 GMT; Max-Age=600
2) If you're using a Debian servers or some derivative, they use a cron job to clear out PHP sessions, so you might try:
Increasing server's configured maxlifetime;
Saving your sessions somewhere else;
Using memcached.
3) To find out if there is some process clearing your sessions, you can place a watch on the directory where the session files are stored (actual path varies from server to server, use session_save_path to find out the location on yours). I'm no server admin, but I've read you can use auditctl for that, just make sure you log who made the changes to your files.
4) If you don't have access to server configuration, or don't want to depend on server config (good if you switch hosts), you can implement your own session handler. Check out this example by Pedro Gimeno.
You put only #session_start(); in the top of your all script.
An also put in the top of your ajax script.
Example Like following:
#session_start();
// you may use session script here or header file
include("header.php");
//some code. you may use session script here or header file
include("main.php");
//-----------next code
I post here, even if is an old post, in case someone experience this problem, check in php.ini session.gc_maxlifetime, or print ini_get('session.gc_maxlifetime'); you have to set it in your php script or php.ini, on my php version the default is 1440 seconds, I have changed it to 1 month, is enough in my case.
Also after start session you can
setcookie(session_name(),session_id(),time() + $sessionLifetime, "", "", false, true);
I hope this helps.
I my case, I replaced session_destroy(); with session_unset(); and problem was solved.
I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.
as title says, is it possible to monitor a local dir in the real filesystem (not html5 sandbox)? I'd like to write an automatic photo uploader that looks for new photos and uploads them.
Potential repeat of Local file access with Javascript.
My understanding is that you can't access the local filesystem directly through a web browser, you have to use an intermediary like the form input tag or drag and drop.
You may be able to get away with accessing the filesystem if you were to use the operating system's javascript interpreter or something like V8. There may also be experimental javascript api's in Chrome that you could look for on the Chrome flags page if thats your browser of choice. That all depends on whether or not you were doing a personal project or something for the web.
Otherwise another scripting language such as PHP, Ruby, or Python would better suit your needs.
You can set a Javascript Timing event. ie: use the setInterval() method.
On the other hand, you can make a button to trigger an onClick event, or any other event, to execute the following code.
NOTE:
If you set an interval, make sure the request was received before sending it again.
For achieving this, you need to check that the readyState of your XML HTTP Request equals 4, as follows:
xmlhttp.readyState == 4
NOTE:
This is for sending the request, parsing the response and putting it in a Javascript array:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "check_dirs.php", true);
xmlhttp.send();
fileArray = new Array();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlDoc = xmlhttp.responseXML;
fileList = xmlDoc.getElementsByTagName("filesChanged");
while (fileArray.length > 0)
// clean the whole array.
// we want to store the newly generated file list
{
fileArray.pop();
}
for (i = 0; i < fileList.length; i++)
{
fileArray[fileArray.length] = fileList[i].childNodes[0].nodeValue;
}
}
}
Moreover, you will need to write a little PHP script to check your custom directory for files newer than a given date, that could be sent in the request by the way, and send an XML response back, like this:
<?php
(...) // check dir. output $files contain the xml nodes for the files to send
// mockup below
// Get our XML. You can declare it here or even load a file.
$xml_builder = '<?xml version="1.0" encoding="utf-8"?>';
$xml_builder .= $files;
// We send XML via CURL using POST with a http header of text/xml.
$ch = curl_init('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.hello..co.uk');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ch_result = curl_exec($ch);
curl_close($ch);
/*
echo $ch_result;
*/
?>
Here are some mockup functions to check the directory and build the XML response:
<?php
function analizeDir($dir)
{
if (is_dir($dir))
{
$dir_resource = opendir($dir);
while (false !== ($res = readdir($dir_resource)))
{
if ($res != "." && $res != ".." && $res != "old")
{
if (is_dir($dir . "\\" . $res)) // this is a subforder
{
analizeDir($dir . "\\" . $res);
} else { // this is a file
checkFile($dir . "\\" . $res);
}
}
}
}
}
function checkFile($file)
{
$today = date("Y-m-d H:i:s");
// if the difference in days between today
// and the date of the file is more than 10 days,
// print it in the response
if (date_diff(datemtime($file), $today) > 10)
{
$files .= "<filesChanged>" . $file . "</filesChanged>";
}
}
?>