Thanks to stackoverflow I got my little project going, but I am in need of some advice again. I would like to check if a user is logged on domain1.com and return a message on domain2. There is a lot more to the code. Below I have included a basic example of it.
index.php on http://domain2.com
<script type="text/javascript" src="http://domain1.com/test.php?js"></script>
test.php is on http://domain1.com.
<?php
if (isset($_GET['js'])){
header("Content-type:text/javascript");
?>
function doAjax(){
$.getJSON("http://domain1.com/index.php/home/callback.php?name=name&callback=?",
function(message) {
alert("Data Saved");
});
}
document.write('<button onclick="doAjax();">Submit</button>');
<?php } ?>
<?php exit; } ?>
callback.php is on http://domain1.com. This is where I would like to check if the user is logged in or not. If the user is logged in, the file gets written, if not I want to send a message to domain2.com asking for login.
<?php
$callback = $_GET['callback'];
$name = $_GET['name'];
$myFile = "txt/tester.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, $name);
fclose($fh);
header("Content-Type: application/javascript");
?>
<?php echo $callback; ?>("Message from the server");
This last part I got from a previous question. <?php echo $callback; ?>("Message from the server"); If that's the message to domain2, how do I call it?
So, basically, domain 2 is expecting a JSONP object from callback.php on domain 1. To format your message in a JSON object, enclose your message in an associative array (e.g: $msg = array('message' => 'This is the callback message');, and then pass it back to domain 2 with echo $_GET['callback'].'('.json_encode($msg).')'; Also, set the Content-Type in your header() declaration to application/json.
Related
I have created a chat window using php, ajax, and jquery. It successfully reads and writes to a file called chatlog.html. I have made a button that clears the chat. It works fine, but all of the clients' chats don't clear until someone speaks. How would I fix this?
chat.php is here since I can't format it correctly: http://pastebin.com/AEwjeZ3w
sendchatmsg.php:
<?php
session_start();
if (isset($_SESSION['username'])) {
$text = $_POST['cmsg'];
$fp = fopen("chatlog.html", "a");
fwrite($fp, "<div><b>" . $_SESSION['username'] . "</b>: " . stripslashes(htmlspecialchars($text)) . "<br></div>");
fclose($fp);
}
?>
clearchat.php:
<?php
unlink("chatlog.html");
?>
You can write empty file to it when you clear it.
clearchat.php:
$fp = fopen("chatlog.html", "w");
fwrite($fp, " ";
fclose($fp);
Reload the chat log in user's screen once the clear chat event completes.
$("#clearchat").click(function() {
$.post("clearchat.php",function(res){
loadLog();
});
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to make a online "bank" for me and my friends to use in games, like Minecraft. I got most of the things working, but the trade thing. The setup is that I use a text file as the storage for the amount of money we have, then call those text files from within my PHP code, but the math isn't working right.I will put a link to a zipped version of the whole site. I did start a session, and all of those things.
Zipped file: [GOOGLE DOCS HOSTED ZIP]
<!DOCTYPE html>
<html>
<body>
<?php
$riley = fopen("riley.txt", "r") or die("Unable to read data!");
$ethan = fopen("ethan.txt", "r") or die("Unable to read data!");
$ethanw = fopen("ethan.txt", "w") or die("Unable to write data!");
$rileyw = fopen("riley.txt", "w") or die("Unable to write data!");
$user = $_SESSION["user"];
$amm = $_POST["amm"];
if ($user == "ethan") {
$txt = $ethan - $amm;
fwrite($ethanw, $txt);
$txt = $riley + $amm;
fwrite($rileyw, $txt);
}
if ($user == "riley") {
$txt = $riley - $amm;
fwrite($rileyw, $txt);
$txt = $ethan + $amm;
fwrite($ethanw, $txt);
}
fclose($riley);
fclose($ethan);
?>
<p> transaction made. Redirecting to home in 3 seconds </p>
<?php
sleep(3);
header("Location: bank.php");
die();
?>
</body>
</html>
The problem here is that you are referencing the file wrapper, not the contents of the file itself.
Example:
$txt = $ethan - $amm;
If passed, say, $10, This line of code is actually executing..
$txt = [file wrapper] - 10;
Since file wrapper is not a value, you're getting your math wrong. You need to either read from the wrapper with: http://php.net/manual/en/function.fread.php
OR
Just use a different function entirely. This is what I would do. I would pass these variables: amount, user. I would set user to the affected user's bank account (aside from my own, from the session, of course.)
<!DOCTYPE html>
<html>
<body>
<?php
$users = array('riley', 'ethan');
$banks = array();
foreach($users as $account_holder) {
// Set the path of your file holding this persons bank
$file_path = $account_holder . ".txt";
// Lets set the $values[name] variable to the contents of the file
// we also cast this as an integer, so that if empty, it will still be zero
// I also prepended the function with #, to suppress any errors (if this bank doesnt exist yet)
$banks[ $account_holder ] = (int) #file_get_contents($file_path);
}
function saveBanks() {
// Access from within the function scope
global $banks;
// Loop through the banks
foreach($banks as $account_holder => $balance) {
// Set the path of your file holding this persons bank
$file_path = $account_holder . ".txt";
// Open the file, create if necessary, empty either way
$fp = fopen($file_path, 'w');
// Write balance to file
fwrite($fp, $balance);
// Close file wrapper
fclose($fp);
}
}
// Let's grab our active user, and transaction amount
// If youre not familiar with this 'if' style, it's: condition ? value if true : value if false;
// http://davidwalsh.name/php-ternary-examples
$active_user = isset($_SESSION["user"]) ? $_SESSION["user"] : die("There is no active user.");
$txn_amount = isset($_POST["amount"]) ? $_POST["amount"] : die("There was no transaction amount received.");
$txn_user = isset($_POST["user"]) ? $_POST["user"] : die("There's no receiving bank account.");
// Process the transaction, check for validity
if(!isset($banks[ $txn_user ])) die("That receiving bank account doesn't exist.");
// Adjust balances
$banks[ $active_user ] -= $txn_amount;
$banks[ $txn_user ] += $txn_amount;
// Write to files
saveBanks();
?>
<p> Transaction made. Redirecting to home in 3 seconds. </p>
<p> New Balances: <?php foreach($banks as $user=>$bal): ?> <li><b><?php echo $user; ?></b>: <?php echo $bal; ?></li><?php endforeach; ?></p>
<meta http-equiv="refresh" content="3;url=bank.php" />
</body>
</html>
In an assignment I'm having trouble running a php script with page handling. It's outputting actual php code when submitted through another php page but works fine on its own.
I have a html login page which submits via submit buttons rather than form submit [a requirement]. This submits to login.php.
Seperately I have testBalance.php which checks a file balance.txt on my server which simply has an amount (1000). testBalance.php calls a function in getBalance.php to return the amount here.
THE PROBLEM IS when I run testBalance.php by itself it works just fine. Displaying "Account Balance: 1000.00" but when I attempt to set (in login.php) testBalance.php as the redirect url, the page literally displays code from my testBalance.php page: "Account balance: "); printf ( "%01.2f", $returnValue ); echo ("
"); ?> " I know it's convoluted, this is an intro to php portion of an web prog. class. I'm guessing it has to do with the value pairs that are being passed through to the pages. Can anyone help?
LOGIN.HTML snippit
<input type="button" name="sub_but" id="bal" value="check balance"
onclick="location.href = 'login.php' + '?' + 'name='+ document.forms[0].username.value +
'&redirectURL=' + 'bal';" />
LOGIN.PHP
<?php
$NAME=$_GET["name"];
$PAGE=$_GET["redirectURL"];
$DESTINATION="";
if ($NAME == ''){ /* HANDLES NAME ERRORS */
echo "PLEASE RETURN AND ENTER A NAME.";
}
elseif (ctype_alpha(str_replace(' ', '', $NAME)) === false) {
echo "$NAME is not a valid name. Name must contain letters and spaces only";
}
else{
if($PAGE=='with'){
$DESTINATION = "withdraw.html";
}
elseif($PAGE=='bal'){
//$DESTINATION = "balance.html";
$DESTINATION = "testBalance.php";
}
elseif($PAGE=='depos'){
$DESTINATION = "deposit.html";
}
elseif($PAGE=='weath'){
$DESTINATION = "weather.html";
}
elseif($PAGE=='xchang'){
$DESTINATION = "currency.html";
}
/*echo("$DESTINATION\r\n");*/
header("Content-Length: " .
strlen(file_get_contents($DESTINATION)));
header("Cache-Control: no-cache");
readfile($DESTINATION);
}
?>
testBalance.php body snippit
<?php
include 'getBalance.php';
$returnValue = readBalance();
echo "<p>Account balance: ";
printf( "%01.2f", $returnValue );
echo "</p>";
?>
getBalance.php
<?php
function readBalance(){
$file = "balance.txt";
$fp = fopen($file, "r");
if (!$fp){
echo "<p>Could not open the data file.</p>";
$balance = 0;
}
else{
$balance = fgets($fp);
fclose ($fp);
}
return $balance;
}
?>
readfile() doesn't EXECUTE anything it reads. It's literally just slurping in the file's bytes and spitting them out to the client. It's basically doing
echo file_get_contents(...);
If you want your other files to be executed, you need to include() or require() them instead. Or you could try eval(), but you really don't want to go down that route. eval() is evil and dangerous.
I have a simple script of code that reads a PHP file and when it get's changed it's supposed to say CHANGED on the page which I will change to refresh the page or change the content. For now, it shows the content, the function repeats once or twice and then it just shows nothing. Any help?
Here is the code:
<?php
$handle = fopen("../chat/real/chatserver.php", "r");
$contents = fread($handle, filesize("../chat/real/chatserver.php"));
fclose($handle);
$newcontents = $contents;
echo $contents;
?>
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("<?php $handle = fopen('../chat/real/chatserver.php', 'r');
$newcontents = fread($handle,filesize('../chat/real/chatserver.php'));fclose($handle);?>");
document.write("<?php if(!($contents==$newcontents)){echo 'Changed';} ?>");
setTimeout('checkchanged()',3000);
}
</script>
Link to example
Thanks for the help
This is because you can't include PHP in your JavaScript in order to execute it by the client. Yes, you can include PHP values, but that's it. Have a look at the source code in your browser:
<script type="text/javascript">
checkchanged();
function checkchanged() {
document.write("");
document.write("");
setTimeout('checkchanged()',3000);
}
</script>
As you can see, the function document.write gets called with an empty string "". This is because everything that is in <?php ?> gets executed on the server, not on the client, before the resulting page gets sent to the client.
Since every PHP code is parsed only once $contents==$newcontents will be true, so you'll never see Changed.
To achieve something like a chat server you'll need new http request. Have a look at AJAX.
So I have a simple form that takes a user input, passes it to a separate PHP script that does some processing on a different domain, and posts a txt file if successful. Example:
<form method="GET" action="inventory_check.php" target="_blank">
Part Number <input type="text" name="part" /><input type="submit" value="Check Inventory" />
</form>
<?php
$filename = $userInput;
if (file_exists('ftpMain/'.$filename.'')) {
$handle = fopen("ftpMain/".$filename."", "r");
$output = fread($handle, filesize('ftpMain/'.$filename.''));
fclose($handle);
$output = trim($output, '&l0O(10U');
$output = trim($output, 'E ');
echo $output;
}
else {
echo 'Failure.';
}
?>
So, inventory_check.php obviously is an inventory lookup for us, however, it's contained on another server (different domain) so it completes its processing and posts it to a file, that I read, cleanup, and display. Now my issue is twofold, I need to grab and keep the input from the user to find the filename and the second is I need to page to either reload or recheck if the file exists. What is the best approach to do this?
Note: We use an awful in house DBMS, so posting and retrieving from a DB is not an option, it took us a while to get it to read the input and FTP it correctly, so it looks like this is the only path.
Why don't you make the request in your server A? by using curl, so you could get the response right after the query.
Firstly, you'll need to get the user's input properly, and sanitize it. I'll leave out the details of the sanitize() method, as that's not really what you're asking.
<?php
if(isset($_POST)) {
$part_number = sanitize($_POST['part']);
$filename = "ftpMain/$part_number";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$output = fread($handle, filesize($filename));
fclose($handle);
/* Do things with output */
} else {
echo 'Failure.';
}
}
?>
However, you say that the file is on another server - looking for ftpMain/... is only going to look for a directory called ftpMain in your current directory. Is the file publicly available on the internet? If it is, you could do something like this:
<?php
$url = "http://yourserver.com/parts/$part_number.txt";
$response = get_headers($url, 1);
if ($response[0] == 'HTTP/1.1 200 OK') {
/* The file exists */
} else {
/* The file does not exist */
}
?>
I hope I've understood your question correctly - this assumes that the form action is pointing to itself. That is, your file with this code is also called inventory_check.php.