Unable to echo or print from PHP functions - php

I am having an issue echoing or printing from my PHP to my HTML. I am sure I am missing something basic with how PHP works, however I have been unable to find anything about this issue on the internet or on here. I am very confused, because I am not receiving an errors or any context to the problem at all. The rest of my code works fine, except for echo.
I normally use echo() for testing to ensure stuff exists, however this issue has plagued me during the entire development of this application. It only now bothers me because I will need to echo out a script to load in data (Which I will hide after the load using Vue).
This issue oddly enough only has happened inside of areas where I am using if to do things, especially when it has array_key_exists.
If anyone could help I would appreciate it (Or if someone could provide a better idea for me to transfer json data from PHP to JavaScript other than having to echo it out, since that opens a weak spot in my code for users to cheat my clicker game).
I have tried to test this in other parts of my code with the same results. I cannot use echo() or print() within any if statement. I can use it elsewhere however.
All of my PHP files end up inside of my index.php by usage of require
<?php
if (array_key_exists("saveData", $_POST)) {
$saveData = $_POST['saveData'];
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
}
if (array_key_exists("logSubmit", $_POST)) {
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
echo("SALO Ready!");
}
?>
I would expect for this to echo out "SALO Ready" however I get nothing instead.
EDIT: PHP's white screen of death does not work or apply. Everything else in my application works as expected
UPDATE #1: I have done some testing as recommended, and found that when I echo out of my if statements, one of two things happen
1) The echo() fires, and in the preview under Network on Chrome you can see it their however it does not display in the DOM. This is the case for any if statement that does not meet the below situation.
2) If the echo() is fired from a block used for registering or logging in, it will not display in the preview either. I will be restructuring my code to have those be functions called by the forms when submitted, instead of them just being conditional blocks. While this code is not included in this question, the initial login runs the code below as well to load up user data.
UPDATE #2: I have consolidated my code and followed some recommendations. My code is now inside of functions, that are fired by some if isset conditions. This actually PARTLY fixed my issue. I can echo from all of my functions (Register, Login, Save, Load). Now my issue would appear to be a comment below in relations to output buffering. While my initial question is (Mostly) solved, would anyone be able to help explain how to solve this? I only have ob_start() right now, followed by my functions, if isset conditions, and then everything else in my application. How can I get the echo go to them DOM? I will include the chunk of my code below that will absolutely need to echo out down the road.
EDIT: I have changed how I have ob_start() setup within my code. I call it in the functions that need it and then flush it afterwards. I will be testing with my load script later tonight to try to force the echo() out of the function. Genuinely confused as to why it had not worked in functions but works outside of them, even before this edit
function load() {
$link = // Link Excluded for Security ;
if (mysqli_connect_error()) {
die ("DB Connection Error");
}
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
mysqli_close($link);
echo("Loading Triggered!");
}
if(isset($_POST['logSubmit'])) {
login();
load();
}
As mentioned, this shows the echo() inside of the network tab when I click on primary.php and click preview, it just isn't going to the DOM

Just use keep your code inside a function and call the function name while post your input
Ex:
function yourFunctionName(){
if (array_key_exists("saveData", $_POST)) {
$saveData = $_POST['saveData'];
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
}
if (array_key_exists("logSubmit", $_POST)) {
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
echo("SALO Ready!");
}
}

There is a way to output contents to the DOM when using ob_start by using ob_flush();
ob_start(), when called stores all outputs buffer until instructed to be sent to the browser.
See:
What is Output Buffering?
(The suggested solution provides a re usable function to empty the buffer, sending contents to browser)
How to flush output after echo call

Related

PHP - running function returns empty page

When I run the following PHP code in my browser, I get an empty page in return. Why is this so?
<?php
require_once "conf.php";
function nuser()
{
$fname = $_POST['name'];
$uname = $_POST['user'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$query = "INSERT INTO websign(name,uname,email,pass)VALUES('$fname','$user','$email','$pass')";
$data = mysql_query($query)or die(mysql_error());
if ($data)
{
echo "your registration is completed";
}
}
function signup()
{
.......
.......
}
?>
Your code doesn't do anything.
You have defined two functions, but you never call either of them.
You need to add nuser() to the end of the script.
This assumes that the script executes at all. You said "when i run it on browser", but PHP doesn't run in browsers, it runs on servers. See this question on the subject.
Your program might also fail because you are using an obsolete database API that has been removed from PHP. You should select a modern replacement. You are vulnerable to SQL injection attacks that a modern API would make it easier to defend yourself from.

My php header tag will not redirect

I've tried doing my research and it doesn't look like I'm coming up successful. I made sure there is no content being printed out to the screen before my header tags.
This page is taking information given from the form in the previous login page and using that information to determine which page the user should be redirected to. Unfortunately, it doesn't look like any of my header tags are redirecting to anything, it just stays on this php page.
To debug, I have echo'd each scenario (logged in, out, wrong pw) and each scenario works, but obviously when I echo'd the redirect wouldn't work. I just wanted to test that the information was being transmitted correctly.
Can anyone else help and give me an outsider's perspective?
<?php
session_start();
include('dbconnect.php');
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$query = "SELECT password FROM artists WHERE email='$email'";
$passwordMatch = mysqli_query($db, $query);
$row = mysqli_fetch_array($passwordMatch);
if($row[0] == $password){
$query = "SELECT active FROM artists WHERE email = '$email'";
$active = mysqli_query($db, $query);
$active = mysqli_fetch_array($active);
$active = $active[0];
if ( $active == 0 ){
header('Location: validate.php');
}
else{
header('Location: artistHome.php'); //redirect to user home page and update session
$_SESSION['user']= $email;
unset($_SESSION['error']);
}
}
else{
header("Location: login.php");
$_SESSION['error']= 'Invalid Password';
}
?>
There were about thousands of posts like this one over here.Get rid of php closing tag ?> and whitespaces, html, blank lines before php opening tag <?php. Also check if there is no output before :
header("Location:");
Like print,var_dump, echo and so on.
Also check your if condition, maybe you are just skipping it.
If you include,include_once,require_once or require check all the things above in the included files too.
To narrow a circle of the things to correct look into your php error_log and provide us with error description.
header("Location: login.php"); will always fail if anything is returned to the browser before it. That includes whitespace, or even errors PHP are returning. Make sure nothing is being returned before the header function is used.

PHP header if num_rows greater than zero

Something weird is happening with the following code. Instead of completely redirecting. It loads the page of the redirect into the login page and mixes things up.
Q1: How do i make a complete redirect.
- session start is the first line
- There's nothing being output before header.
- As for spaces, I'm not sure what will count as a space in the below script.
Q2: How do i preg_replace a string to only allow both lower cases and uppercases and 0 - 9 numbers and again how do i preg replace emaail to allow the '#' charecter and alphanumerics.
Q3: What's the best way to check if the user trying to login matches exactly the registered user?
Q4: What danger can a hacker do with my session variables?
PHP CODE
<?php
session_start();
require_once 'db_conx.php';
$email = preg_replace ('#[^A-Z, 0-9 ]#i', '', $_POST['email']);
$pwd = preg_replace ('#[^A-Z, 0-9 ]#i', '', $_POST['pwd']);
if ($uname == '' || $pwd == ''){
echo '<span style="color:#F00">Please fill in all login details.</span>';
} else {
$Result = mysql_query("SELECT * FROM users WHERE uemail = '$uname' && pwd = '$pwd'")
or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$_SESSION['Sname'] = $row['firstname'];
$_SESSION['Slname'] = $row['lastname'];
$_SESSION['SUid'] = $row['uid'];
$_SESSION['Semail'] = $row['uemail'];
$_SESSION['Suid'] = $row['uid'];
$_SESSION['Szip'] = $row['zip'];
}
if (mysql_num_rows($Result) > 0){
header ('Location: ../user.php');
} else {
echo '<span style="color:#F00">Your account details do not match, please check your details and try again or try to recover your account if you forgot your password</span>';
}
}
?>
Thanks.
Q1
instead of using header( 'Location...)
you can use
echo '<meta http-equiv="refresh" content="0; URL= http://something.com">';
EDIT
i believe you can also use the following. the die should allow for the redirect, but in my experience it doesn't always get along with jquery.
header('Location: http://something.com');
die();
This is especially useful if you are using event.preventDefault(); in jquery on the same page, which will almost always cause header location redirects to be ignored. this method is also appropriate when you are using get requests to include a php page in your index file, causing a url like http://somesite.com/index.php?page=home
EDIT the above information was wrong it wasn't working for me because php had already sent the headers. i'm an idiot.
instead of this meta refresh, you could do this which should produce the desired result.
echo '<script type="text/javascript">window.location = "yoururlhere"</script>';die;
Q2
$step1 = preg_replace('#[^A-Z, 0-9 ]#i', $_POST["variable"]);
$step2 = strtolower($step1);
echo $step2;
Q3
This is a tough question to answer, but basically you want to hash there password, then check if it matches the password in the db. heres a brief pseudocode.
$username = $db->real_escape_string(strip_tags($_POST["username"]));
$password = hash('sha512', $salt.$_POST["Password"});
$db->query("SELECT * FROM `usertable` WHERE `Username`='$username' AND `Password`='$password' AND Username IS NOT NULL AND Username != '' LIMIT 1");
$result = $db->get();
if(!$result){
//the query returned a null result, so the username or password was incorrect.
}else{
//set user session and log them in.
}
Q4
I'm no expert, but it all depends on the architecture of your application and how you are setting sessions and cookies.in my opinion look into using formkeys and preventing xss, rfi, sql injection and lfi, then worry about session variables. the experience gained tackling the aforementioned problems will give you confidence and a broader understanding when attempting to secure your user sessions.
further information can be obtained from php.net/manual/en/session.security.php and stackoverflow.com/questions/328/php-session-security
thanks to the suggestions of DanFromGermany who improved on this answer.

Why will this page not work correctly when loaded dynamically in a div tag?

This is an adaption of a much longer question, because I pinpointed the question to be more direct without so much information. I'm using This to dynamically load pages in my div tag, but certain things stop working when loaded. Specifically some jquery stuff. The registration does not check the username ect when loaded in this div, and I can't figure out why. If code is needed to be posted I can do so, but I think it may simply lie in the way the pages are loaded, just not sure which or why. Here is the link to my test page to see what I'm talking about. Hover over login then click "register". it will load the form but it doesn't check the username with the jquery and such I have. Here is the single registration page that works just fine by itself, and this shows what I'm trying to do as well. Fiddle with javascript/jquery and html. I left some PHP in just in case it's doing something funky, and left out the css because its for the message box, and that doesn't effect this, and will still show up for tests without it.
This is the PHP that process the registration:
<?php
//have to use &_POST instead of vars for regular vars because of bug
//hash the password
$hash = hash('sha256', $_POST['pass1']);
//creates a 3 character sequence, hash pass again
function createSalt(){
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
//check registration code
require('config/config.php');
//match the id with the registration code to update the correct row
$result = mysql_query("SELECT id FROM user WHERE regcode=
'". mysql_real_escape_string($_POST['regcode']) ."'") or die('Unable to query!');
$row = mysql_fetch_array($result);
if ($row['id'] != "") {
$updateid = $row['id'];
} else {
die("No matching registration code!");
}
//check if id is blank, means registration is blank
if (isset($updateid)) {
//update into database
$result = mysql_query("UPDATE user SET username='". mysql_real_escape_string($_POST['username']) ."',
password='". $hash ."', salt='". $salt ."',
email='". mysql_real_escape_string($_POST['email']) ."',
firstname='". mysql_real_escape_string($_POST['firstname']) ."',
lastname='". mysql_real_escape_string($_POST['lastname']) ."',
regcode='', joined=NOW(), lastlogin=NOW(), active='yes'
WHERE id='". $updateid ."'") or die(mysql_error());
//echo $query.",".$_POST['username'].",".$hash.",".$_POST['email'].",".$_POST['firstname'].",
// ".$_POST['lastname'].",".$_POST['regcode'].",". $updateid ."";
//mysql_close();
echo 'yes';
} else {
echo 'noregcode';
}
?>
P.S. Please ignore outdated PHP. While it is bad, I just haven't fixed it yet and know I will have to soon.
The reason it doesn't work is that that code you're using simply does nothing to make it work. The code stuffs the response into a DOM element but doesn't try to run the scripts. A simple update to the innerHTML property of an element doesn't cause embedded scripts to be run.
You could modify that script if you want, but since you tagged this question with jQuery I would urge you in the strongest possible terms to dump that script and do this with jQuery, which (if you do it right) will do the work necessary to cause embedded scripts to be run.

Search & Amend User Details

I wonder whether someone can help me please.
I'm trying to put together a form and PHP script (below) which allows an administrator to search and update member details via the email address, populating a second email address, forename and surname fields with the retrieved information ready for them to be amended.
<?php
mysql_connect ("hostname","username","password") or die (mysql_error());
mysql_select_db ("databasename");
if ($_POST['search'])
{
$searchemailaddress = $_POST['searchemailaddress'];
$sql = mysql_query("select * from userdetails where emailaddress like '$searchemailaddress'");
while ($row = mysql_fetch_array($sql))
{
$emailaddress = $_POST['emailaddress'];
$forename = $row['forename'];
$surname = $row['surname'];
}
elseif ($_POST[['update'])
{
$userid = $_POST['userid'];
$emailaddress = $_POST['emailaddress'];
$forename = $_POST['forename'];
$surname = $_POST['surname'];
//replace TestTable with the name of your table
$sql = ("UPDATE `userdetails` SET `emailaddress` = '$emailaddress', `forename` = '$forename',`surname` = '$surname' WHERE `userdetails`.`userid` = '$userid' LIMIT 1");
}
}
}
?>
I'm receiving the following error:
Parse error: syntax error, unexpected T_ELSEIF in /homepages/2/d333603417/htdocs/development/searchandamend.php on line 13
with line 13 being this line in my script. elseif ($_POST[['update'])
Could someone perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
The line
$surname = $row['surname'];}
should have another } afterwards. The one you have only closes the while loop. You also may want to consider using some indentation - that really helps seeing errors like this one.
Also, the error basically says it all - the else if appears unexpectedly there, so the PHP processor expects something else (in this case a closing brace).
As was mentioned in a comment to your answer your closing } are improperly placed and it appears you have too many of them.
if
{
// stuff here
}
elseif
{
// other stuff here
}
As was also mentioned in a previous answer if you properly format your code, similar to how it appears in the edited question, you will have a much easier time finding errors like this.
I also feel obliged to point you to the PHP documentation on choosing the correct MySQL API as the extension you are using is outdated and is not recommended for new project use.

Categories