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.
Related
this is my first time using PHP, so I'm here because I don't even know how to look for the information I want (function name's, properties, etc). As I said before, my code receives a string with two variables and uploads it to a log with the format:
Raw time data, var1, var2
So, I want to add some lines that allow the code to send an "OK" confirmation when data has been successfully posted. How can I get it?
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "<pre>";
echo "hello! \n";
$file = 'measures.txt';
$time = time();
$row = "$time";
if ( isset( $_GET["T"] ) )
{
$new_measure = $_GET["T"];
echo "Temperature: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
if ( isset( $_GET["H"] ) )
{
$new_measure = $_GET["H"];
echo "Humidity: $new_measure \n";
$row = $row.", $new_measure";
} else {
$row = $row.", ";
}
file_put_contents($file, "$row\n", FILE_APPEND | LOCK_EX);
echo "</pre>";
?>
Julio,
in your file_put_contents function you could simply echo a " OK" message if the file is successfully stored in the location you set. Now if you are trying to do email confirmation you would need to setup a mail function within your php application and have the proper smtp configurations so your server can do that.
I am assuming you have verification checks before the file is given to your file_put_contents function.
I have a php script handling an incoming ajax request. It looks up some credentials from text files and if they match requirements it sets two cookies, one called username and one called creds on the client machine.
When I do this from my local web server, all three cookies get set and I receive all the php feedback from the echoes.
When I do this from my hosted web server the first setcookie works ("cookies","enabled") but the next two dont! However I get all the echoes confirming that php has reached the point in my script where they should be set. Any ideas please? I am thoroughly stumped.
<?php
//george:bloog
//emeline:sparg
setCookie("primacy[cookies]","enabled", time()+3600*24*30,'/');
//convert string to summed int
function pwdInt($pw)
{
$pwdIntVal = 0;
for($i=0; $i<strlen($pw);$i++)
{
$pwdIntVal = $pwdIntVal + ( ord(strtolower($pw[$i])) - 96 );
}
return $pwdIntVal;
}
//retrieve user account creation date by parsing savefile for accountCreate var
function getACD($aUSR)
{
$saveFileName = "saveFiles/" . $aUSR . ".txt";
echo "Fetched save successfully.<br>";
$lines = file($saveFileName);
foreach($lines as $line)
{
if( explode(":",$line)[0] == "accountCreate");
$lineDate = explode(":",$line)[1];
return $lineDate;
}
}
//accept incoming vars
if(isset($_POST['username']) && !empty($_POST['username']))
{
$uN = strtolower($_POST['username']);
$pwd = strtolower($_POST['password']);
$found = "Invalid user";
//test for presence in creds
$lines = file("creds/creds.txt");
foreach($lines as $line)
{
$lineName = explode("_",$line)[0];
if($uN == $lineName)
{
//matched username before delimiter "_"
$found = $lineName;
echo "Found user, " . explode("_",$line)[0] . " checking password<br>";
//check two: use int of pwd with account creation date from user save
$usrACD = getACD($uN);
echo $usrACD;
if( (pwdInt($pwd) * $usrACD) == (explode("_",$line)[1]) )
{
echo "Tests passed: granting access cookies";
setCookie("uN",$uN, time()+3600*24*30,'/');
setCookie("cred",(pwdInt($pwd) * $usrACD), time()+3600*24*30,'/');
}
else
{
echo "Failed password check for allowed user<br>";
}
}
}
}
else
{
echo $found . pwdInt($pwd) . "<br>";
}
?>
You should either enable output buffering or move echoes after setCookie method. Setting cookies is thing that happens during headers of response. All headers should be sent before content. Echoing things is setting up content, so every header edition (like setting cookies) after first echo will fail.
I want to implement recaptcha in a very simple form
I have a index.html file on client-side, and a post.php server side.
I've tried to integrate recaptcha on the server site, as you can see in my code bellow.
I've made some tests, that seem to have an expected result...
The problem appeard when I tried this query
for X in `seq 0 100`; do curl -D - "http://example.com/post.php" -d
"email=email${X}%40example.com&tos=on&g-recaptcha-response[]=plm&submit="; done
The result was that I've bypassed recaptcha succesfully, and I'm not sure what the problem is.
Most probably, there's a problem in my php code, but what exactly?
post.php
<?php
$email;$submit;$captcha;
if(isset($_POST['submit']))
{
$email=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
}
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Le[whatever[7_t&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else
{
$file = 'email-list.txt';
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
if(!(exec('grep '.escapeshellarg($email).' '.$file)))
{
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $email . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
header('Location: index.html?success='.urlencode($email));
}
else
header('Location: index.html?fail='.urlencode($email));
}
else
{
echo "$email is <strong>NOT</strong> a valid email address.<br/><br/>";
}
}
?>
index.html
...
<div class="form-group" ng-cloak>
<div class="g-recaptcha" ng-show="IAgree" data-sitekey="6LeEW[whatever]-UXo3"></div>
</div>
...
How can I solve this? English is not my native language; please excuse typing errors.
As mentioned in my comments above - file_get_contents returns a string. You need to decode the json string into a php object using the json_decode function:
$url = "https://www.google.com/recaptcha/api/siteverify?"
$response = json_decode(file_get_contents($url));
if($response->success == false) {
echo "Oh no";
}
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 have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.