I'm trying to make my xml file URL dynamic so multiple people can be using my site and querying data at once. I order to do so I'm inserting a random number php variable in front of my xmlfile. For some reason I'm having issues creating and writing xml files when trying to use this variable. When I use a static URL like 'wine.xml' it works fine.
$fp = fopen($randnumb.'wine.xml', 'w');
fwrite($fp, $string);
fclose($fp);
I might be wrong (so any one let's correct me) if you have an xml and want to allow many people to read it why do you have to make multiple copies of it?!
Isn't the server supposed to do this job serving a file to many peple? If I am wrong and there is something else you try to then this php only works okay. This way you don't have to look for errors in php.
<?php
$fileName = rand().'file.xml';
$fp = fopen($fileName, 'w');
fwrite($fp, 'Hello!');
fclose($fp);
?>
<?php
$handle = fopen($fileName, "rb");
$contents = fread($handle, filesize($fileName));
print_r($contents);
fclose($handle);
?>
var winexml=loadXMLDoc("<?=$randnumb?>wine.xml");
Does <? work for you? cause wamp asks <?PHP (must be the php.ini)
Why do you have a second = in the loadxmldoc parameters?!
Does this work:
<?PHP
$dbq="\"";
echo 'var winexml=loadXMLDoc(',$dbq,$randnumb,'wine.xml',$dbq,');';
?>
Okay I see. I don't know what is you preference of final xml file display, however this scripts has stuff that might let you have your job done, just adjust it to your needs.
index.html and getXml.php
<html>
<head>
<script type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
</script>
<script type="text/javascript">
var fileOption;
var fileName;
function runPhp(makeFile)
{
var url = "getXml.php";
fileOption = makeFile;
var params = "makeFile=" +makeFile+"";
request.open("POST", url, true);
//Some http headers must be set along with any POST request.
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = updatePage;
request.send(params);
}////////////////////
function getXml( )
{
if(fileName==null){alert('please click create file first');return;}
var url = fileName;
var params = null;
request.open("POST", url, true);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = displayFile;
request.send(params);
}////////////////////
//You're looking for a status code of 200 which simply means okay.
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200)
{
if(fileOption==1)
{fileName=request.responseText; return;}
document.getElementById('divResults').innerHTML=request.responseText;
document.getElementById('textareaResults').innerHTML=request.responseText;
}
else{
//alert("status is " + request.status);
}
}
}
function displayFile() {
if (request.readyState == 4) {
if (request.status == 200)
{
document.getElementById('textareaResults').innerHTML=request.responseText;
document.getElementById('divResults').innerHTML='File loaded in text area above.';
}
else{
//alert("status is " + request.status);
}
}
}
</script>
</head>
<body >
<span style="background-color:blue;color:yellow;"
onClick="runPhp(0)"/>
Click for Xml Results.<br>
(<font color=pink>I prefer this one!!!</font>)
</span><br><br>
<span style="background-color:blue;color:yellow;"
onClick="runPhp(1)"/>
Click to create an xml file.<br>
</span>
<span style="background-color:blue;color:yellow;"
onClick="getXml(1)"/>
Click to read the xml file.<br>
</span>
<textarea rows="10" cols="88" id="textareaResults">
</textarea>
<br><br>
<pre><div id="divResults"></div></pre>
<br><br>
</body>
</html>
<?PHP
mysql_connect('localhost', 'root','');
mysql_select_db("mysql");
$query="select * from help_category;";
$resultID = mysql_query($query ) or die("Data not found.");
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<records>\n";
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= "\t<record>\n";
$xml_output .= "\t\t<help_category_id>" . $row['help_category_id'] . "</help_category_id>\n";
$xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
$xml_output .= "\t\t<parent_category_id>" . $row['parent_category_id'] . "</parent_category_id>\n";
$xml_output .= "\t</record>\n";
}
$xml_output .= "</records>";
if($_POST['makeFile']==0)
echo $xml_output;
else
{
$fileName = rand().'file.xml';
$fp = fopen($fileName, 'w');
fwrite($fp, $xml_output);
fclose($fp);
$dbq="\"";
echo $fileName;
}
?>
Related
I'm working with the coordinates. I don't want to use a GeoIP database. So I tried first to get the coordinates, then send them with a post to a php file which write them in an html file.
This is the index.html code:
<p> Hello. </p>
<script type="text/javascript">
$.get("http://ipinfo.io", function (response) {
var ip = response.ip;
var city = response.city;
var region = response.region;
var details = JSON.stringify(response, null, 4);
$.ajax({
type: "POST",
url: 'write.php',
data: '&ip='+ ip + '&city=' + city + '®ion=' + region + '&details=' + details,
success: function (data) {
alert("Sent!");
},
error: function(jqXHR, text, error){
alert("Error: not sent.");
}
});
}, "jsonp");
this is the write.php code:
<?php
$ip = $_POST['ip'];
$city = $_POST['city'];
$region = $_POST['region'];
$details = $_POST['details'];
$fh = fopen('lol.html', 'a') or die("can't open file");
fwrite($fh,'IP: $ip ;');
fwrite($fh,'Details: $details');
fclose($fh);
echo "Created";
?>
If I host and open index.html it alert "Sent!". But then, when I open lol.html I see the string: IP: $ip ;Details: $details
Why? What am I doing wrong?
This is because you are trying to use variables inside single quotes ' when writing data; so the variables aren't getting evaluated but instead being treated as literals.
So, try this instead:
<?php
// Parse input
$ip = isset($_POST['ip']) ? $_POST['ip'] : '';
$city = isset($_POST['city']) ? $_POST['city'] : '';
$region = isset($_POST['region']) ? $_POST['region'] : '';
$details = isset($_POST['details']) ? $_POST['details'] : '';
// Open file for writing
$fh = #fopen('lol.html', 'a');
if (!$fh) exit('Failed to open file for writing')
// Write data
fwrite($fh, "IP: $ip\r\n");
fwrite($fh, "Details: $details");
// Finished
fclose($fh);
echo "Created";
?>
Update
Based on your comment, I have optimised this script into the following, try this out:
index.html (or what ever .html file)
<p> Hello. </p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$.getJSON('http://ipinfo.io', function(response) {
$.post('write.php', { response: JSON.stringify(response) })
.done(function(result) {
alert(result);
});
});
</script>
write.php
<?php
// Parse input
$response = isset($_POST['response']) ? $_POST['response'] : '';
// Decode input
$response = #json_decode($response, true);
if (!$response) {
exit('Invalid input.');
}
// Open file for writing
$fh = #fopen('lol.html', 'a');
if (!$fh) {
exit('Failed to open file for writing.');
}
// Write data
$result = '<pre>';
foreach ($response as $key => $value) {
$result .= "$key = $value\r\n";
}
$result .= '</pre>';
fwrite($fh, $result);
// Finished
fclose($fh);
echo "Created";
?>
The resulting lol.html file will now look like this (when index.html is executed):
<pre>ip = 90.152.2.38
hostname = host90-152-2-38.ipv4.regusnet.com
city = St Albans
region = England
country = GB
loc = 51.8379,-0.4399
org = AS8220 COLT Technology Services Group Limited
postal = AL3
</pre>
And if you were to open this lol.html file in browser, it will render like this:
Is this what you are after?
I have a file upload page that works but I'm trying to do some error alerts to choose if you want to replace or not.
This is my php file that does the upload
<?php
require ("connect.php");
$filename = "docs/".$_FILES['datafile']['name']."";
$d=explode(".",$_FILES['datafile']['name']);
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
} else {
$target_path = "docs/";
$target_path = $target_path . basename( $_FILES['datafile']['name']);
if(move_uploaded_file($_FILES['datafile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['datafile']['name'])." has been uploaded";
$error = 0;
}
else
{
echo "There was an error uploading the file, please try again!";
$error = 1;
}
}
if ($error != 1)
{
$r1 = mysql_query("insert into full_dump (file_name) values ('".$_FILES['datafile']['name']."')")or die(mysql_error());
$file1 = "docs/".$_FILES['datafile']['name']."";
$lines = file($file1);
$count = count($lines);
$fp = fopen("docs/".$_FILES['datafile']['name']."","r");
$data=fread($fp,filesize("docs/".$_FILES['datafile']['name'].""));
$tmp=explode ("\n", $data);
for ($i=0; $i<$count; $i++)
{
$a=$tmp[$i];
$b=$i+1;
$r2 = mysql_query("update full_dump set field_".$b."='".$a."' where file_name='".$_FILES['datafile']['name']."'")or die(mysql_error());
}
echo"</br>";
echo "Uploading Complete</br>";
echo "Uploaded File Info:</br>";
echo "Sent file: ".$_FILES['datafile']['name']."</br>";
echo "File size: ".$_FILES['datafile']['size']." bytes</br>";
echo "File type: ".$_FILES['datafile']['type']."</br>";
}
?>
What I want to have is instead of
if (file_exists($filename)) {
echo "<script>alert('Full dump for ".$d[0]." already exists.')</script>";
$error = 1;
}
to have an alert if I would like to replace the file or not. If it's yes it would replace the file, delete the old record in the db and insert the new record. I it's no don't do nothing...or show a message "canceled by user". Could I have $error to be assigned a value for YES or NO on user choosing or not to replace?
UPDATE
This is the form page for upload.
<html>
<head>
<script language="Javascript">
function fileUpload(form, action_url, div_id) {
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function () {
if (iframeId.detachEvent) iframeId.detachEvent("onload", eventHandler);
else iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
}
else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
}
else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
document.getElementById(div_id).innerHTML = content;
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener) iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent) iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");
// Submit the form...
form.submit();
document.getElementById(div_id).innerHTML = "Uploading...";}
</script>
</head>
<body>
<form enctype=\"multipart/form-data\" method=\"POST\">
<input type="file" name="datafile" />
<input type="button" value="upload" onClick="fileUpload(this.form,'file_upload.php','upload'); return false;" >
<div id="upload"></div>
</form>
<?php
require("connect.php");
$result = mysql_query("SELECT * FROM full_dump")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Job number: ".$row['file_name']."</br>";
}
?>
you should do this with ajax... when you will send ajax request you will check if file exist or not .. if yes return eg -1 and ask user for relapsing ...
Enjoy :)
instead of using upload code on same page. do one thing, upload file by using ajax request. then check on backend site file is aleady exist or not and according to that show message as you like
I am using AJAX to track the number of clicks of a button on my site and I would like to display that value on the page as well. Currently the tracking is working great and the number of clicks is being printed to a document called clicks.txt and I was wondering how I could go about reading the value from that text file and printing it to the page.
I tried searching SO and Google for an answer, but I guess I can't think of how to word it properly because the answers I have found so far have been unrelated to what I'm trying to do.
Here is the AJAX included in index.php
<script type="text/javascript">
function getXMLHttp()
{
var xmlHttp
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "counter.php", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
Here is the external PHP(counter.php) I am using to track the button clicks:
<?php
$clicks = file_get_contents("clicks.txt");
$clicks++;
$fp = fopen("clicks.txt", "w+");
while ( !flock($fp, LOCK_EX) ) {
usleep(500000); // Delay half a second
}
fwrite($fp, $clicks);
fclose($fp);
flock($fp, LOCK_UN);
?>
Thanks in advance!
$clicks = file_get_contents("clicks.txt");
echo $clicks;
If the page that the button exists on is a .PHP file, you can embed code similar to this directly on the page where you want it to be displayed:
<?php
$clicks = file_get_contents("clicks.txt");
echo $clicks;
?>
Hi i have a requirement where i need to execute mysql queries once user will confirm Ok from confirmation box.In my case what ever data i am passing to insert_details.php is not working. one more thing i would like to bring to your notice that i need to send data to different script and navigate it to different page.kindly suggest where is the problem?
<script type="text/javascript">
var r=confirm("This email address already exits in our database. Do you want to continue?");
if (r==true)
{
var dataObj = {
fname : document.getElementById('fname').value,
phone : document.getElementById('phone').value,
pemail : document.getElementById('email').value
}
var xhr = new XMLHttpRequest();
xhr.open("POST","insert_details.php", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify(dataObj));
xhr.onreadystatechange = function() {
if (xhr.readyState>3) {
window.location = 'http://localhost/myproject/test.php?eid=<?php echo $primary_email; ?>';
}
}
alert("test");
}
else
{
window.location = 'http://localhost/myproject/registration_request.php'
}
</script>
code in insert_details.php
$date = "Date:" . date("d/m/Y h:i:s") . "\n"; //to get today's date and time
$logfile = "testing";
$fpath ="myproject/";
$filepath = $fpath .$logfile . '-log-' . date('Y-m-d') . '.csv'; //path of error log file
$fh1 = fopen($filepath, 'a') or die("can't open file"); //opening the error log file
fwrite($fh1, "******************index*******************" . "\n");
fwrite($fh1, $date);
$test=json_decode(file_get_contents('php://input'));
fwrite($fh1, $test[0]);
You are not sending up a named pair. You are just sending up the value of the textbox.
what is looks like as a string.
xhr.send("myEmail#example.com");
Second you have a race condition between the Ajax call and the window.location.href.
You need to wait for the response to come back before doing the redirection.
Basic idea:
var dataObj = {
fname : document.getElementById('fname').value,
phone : document.getElementById('phone').value,
pemail : document.getElementById('email').value
}
xhr.onreadystatechange = function() {
if (xhr.readyState>=3) {
window.location = 'http://localhost/myproject/test.php?eid=<?php echo $primary_email; ?>';
}
}
xhr.send(JSON.stringify(dataObj));
Okay so I have a PHP script which handles file uploads, KML files specifically, extracts the center point and the location of the uploaded file, saves these details in text files, and then loads another page via "header". This other page then uses AJAX calls to set variable names as gathered from the text files, for the location of the KML file and the center point, in order to call the Google Maps API to show the KML layer upon a map.
That is what is supposed to happen, but instead nothing appears. I browse for my KML file, hit the upload button, and a blank page is shown. When I check my server, the file as been uploaded and the relevant details written into their respective text files, so obviously something is going wrong when I try to call the Google Maps API.
PHP upload and file info saving:
<?php
//Check that we have a file
if((!empty($_FILES["UploadedFile"])) && ($_FILES['UploadedFile']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 3Mb
$filename = basename($_FILES['UploadedFile']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "kml") && ($_FILES["UploadedFile"]["size"] < 3145728)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/kml/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['UploadedFile']['tmp_name'],$newname))) {
findCenter($newname);
saveName($newname);
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["UploadedFile"]["name"]." already exists";
}
} else {
echo "Error: Only .kml files under 3Mb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
function findCenter($file) {
$kmlContent = file_get_contents($file);
$startName = "#sh_green-circle";
$endName = "#sh_red-circle";
$startCoords = getCoords($kmlContent, $startName);
$endCoords = getCoords($kmlContent, $endName);
$startLat = substr($startCoords, strrpos($startCoords, ',') +1);
$startLong = substr($startCoords, 0, strrpos($startCoords, ','));
$endLat = substr($endCoords, strrpos($endCoords, ',') +1);
$endLong = substr($endCoords, 0, strrpos($endCoords, ','));
$midLat = ($startLat+$endLat)/2;
$midLong = ($startLong+$endLong)/2;
$midCoord = "$midLat,$midLong";
$saveCenter = "kmlcenter.txt";
$fh = fopen($saveCenter, 'w') or die ("Can't create file");
$stringData = $midCoord;
fwrite($fh, $stringData);
fclose($fh);
}
function getCoords($kml, $name) {
$startSearch = strpos($kml, $name);
$midSearch = strpos($kml, "<coordinates>", $startSearch+1);
$endSearch = strpos($kml, "</coordinates>", $midSearch+1);
$longlat = substr($kml, $midSearch+13, $endSearch-($midSearch+13));
return $longlat;
}
function saveName($filename) {
$saveFile = "kmlfilename.txt";
$fh = fopen($saveFile, 'w') or die("Can't create file");
$stringData = "$filename";
fwrite($fh, $stringData);
fclose($fh);
header("Location: initgmaps.html");
}
?>
Map intitialisation:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
<script type="text/javascript">
function initialize() {
var kmlName = getName()
var kmlCoords = getCoords()
var mapcenter = new google.maps.LatLng(kmlCoords);
var myOptions = {
zoom: 11,
center: mapcenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("infoArea"), myOptions);
var kmlLayer = new google.maps.KmlLayer(kmlName);
kmlLayer.setMap(map);
}
</script>
Relevant AJAX functions:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getName(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlName;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlName = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlfilename.txt", false);
ajaxRequest.send(null);
}
//-->
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getCoords(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlCoords;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlCoords = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlcenter.txt", false);
ajaxRequest.send(null);
}
//-->
And of course in the body of initgmaps.html I have:
onload="initialize()"
infoArea is the ID for my inline frame.
Can anyone see why it doesn't load? I'm completely and utterly new to web development, learning as I go, so sorry if the code is terrible and I'm sure I've made some obvious errors. Many thanks.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
You have missed an ampersand here... Should be:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[[YOUR-GMAPS-KEY]]&sensor=false"></script>
(Where [[YOUR-GMAPS-KEY]] is your Google Maps Key - "AIzaSyB8P7CzxiwQFf-RdK9QV...".)
Try adding an ampersand '&' after your key and before the sensor=false parameter.
Additionally
var kmlCoords = getCoords()
is javascript, but function getCoords() is PHP. Javascript cannot execute a PHP function.
the error might be caused by not following this format:
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
see, after "YOUR_API_KEY" there shouldn't be "sensor=false".
try it. hope it works.