Code block not getting executed - php

I was trying to make a little report management system recently. Everything was going well till I encountered this weird problem. Since the code contains lots of html, I'll only include the important parts.
Basically this is a login page. I am storing the information in SESSION variable.
When the username and pass doesn't match, the error message is given to this below function for further processing.
Edit: Every page in my project includes a config.php with following contents
// Start of config.php
session_start();
error_reporting(E_ERROR);
// ********************* Database Config **********************//
$dbHost = "localhost"; // MySQL host
$dbUser = ""; // MySQL username
$dbPass = ""; // MySQL password
$dbDatabase = ""; // MySQL main database name
A part of login.php is shown below.
//START OF PHP CODE//
include("config.php");
function gotError($msg)
{
$_SESSION['err'] = $msg;
header("Location: login.php");
die();
}
//CODE FOR EVALUATION OF DATA//
// END OF THE PHP CODE & BELOW THE HTML WILL START //
And on the same page, below the starting php code, there is the html code of page. Between the html, there are some bits of php code for using the data set above.
----------- SOME HTML CODE HERE----
<?php
if(isset($_SESSION['err']))
{
$html.= "<script type='text/javascript'>";
$html.= '$.alert("'.$_SESSION['err'].'");';
$html.= "</script>";
print $html;
}
?>
----------------- SOME HTML CODE HERE--------
Now here's the weird behavior comes in. The page post the login data to itself & if error occurs, the error is set in session variable { $_SESSION['err'] } and then redirected to itself again which displays a jquery message box if $_SESSION[ 'err' ] is not empty.
The above code doesn't work in the original form, however, if I do like code shown below, the code works. I mean the whole code including the conditional components which didn't worked previously. As soon as I remove that particular line, the conditional evaluation doesn't work.
<?php
print($_SESSION['err']);
if(isset($_SESSION['err']))
{
$html.= "<script type='text/javascript'>";
$html.= '$.alert("'.$_SESSION['err'].'");';
$html.= "</script>";
print $html;
}
?>
Does anyone have a clue about this? I am using PHP Version 5.3.8.
Thank You.

Are you calling session_start() to actually enable the session? Without that, you'll just be wasting your time. Unless you start the session, php will NOT save any data your write to $_SESSION, not will it load any data that was previously saved elsewhere.

I resolved this problem. Comes out that changing the position of the php script between the HTML from head to body did the trick.

Related

Output Buffering: Easy way to make string out of HTML-Code

I'm currently using Chatfuel to open the index.php-file of my website which sends the user the html code into his browser. There he can register and set up his account.
An example URL might look like this:
https://my.domain.com?key_value='123456789'
Depending on if that user is a new or a existing one, I wanna present him with a different form. In order to check so, I do a simple query to the MySQL db and see if the passed on key_value is already in the db and safe true or false to a boolean. Stating the obvious: If hes not an existing user, the 'empty' form with no values should show up. If he is registered he should see the information he filled in from last time.
My idea:
At the top of my index.php I do the check whether he's an existing customer or not (Note: This is working already). Then I want to use outputbuffering to alter the html-code depending on the boolean, before it is sent to the client.
My problem:
I developed the blueprint of the website in plain html (see code below). And OB only catches it as output if its within a string. Since I use " as well as ' in the document the string gets interrupted every few lines. Is there a simple workaround to this? Because the OB function is unable to access anything within the <html>...</html> tags.
Or do i need to use redirecting after the check (in my index.php) and create a separate form + script for both edit customer data and add new customer data?
<?php
//Connection stuff
// Prepare statment: !TODO: string needs to be escaped properly first
$query_string = "SELECT * FROM tbl_customer WHERE unique_url = '$uniqueurl'";
$query_rslt = mysqli_query($conn, $query_string);
if($query_rslt == FALSE)
{
// Failure
echo "<br> Oops! Something went wrong with the querying of the db. " . $conn->connect_error;
//Handle error
}
else
{
if ($query_rslt->num_rows > 0)
{
// Set boolean
$existing_customer = TRUE;
// Create an array called row to store all tuples that match the query string
while($row = mysqli_fetch_assoc($query_rslt)) {
//...
}
}
}
// Custom post processing function
function ob_postprocess($buffer)
{
// do a fun quick change to our HTML before it is sent to the browser
$buffer = str_replace('Testing', 'Working', $buffer);
// Send $buffer to the browser
return $buffer;
}
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
if (!ob_start('ob_postprocess'))
{
// Failure
echo "<br> Oops! Something went wrong with output buffering. Check that no HTML-Code is sent to client before calling this start function.";
// Handle error
}
else
{
// Success
// This is where the string should get accessed before sending to the client browser
echo "Testing OB.";
}
?>
<!--DOCTYPE html-->
<html lang="en">
<head>
<meta charset="utf-8">
//...
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>
Output: "Working OB."
EDIT: I added source code example. This code won't compile.
Since, i can't comment, so i'll put some of my question here.
I dont really get the point, but give me a try, are you mean escaping string? you can use backslashes \ to escape string.
Like this "select from ".$dbname." where id = \"".$id."\"".
You can easily using addslashes($var) before adding the variable to the sql. like this
$id = addslashes($_POST['id']);
$sql = "select form db where id = '$id'";
If you mean checking the existent of the user to select which form to show in the page, why dont you do this?
if(userCheck()) {
?>
// here write the html code if user passed
<?php
} else {
?>
// here write the html code if user not passed
<?php
}
You can put userCheck() as global function or whereever you place it, as long as you can use it when you want to check the user before showing the form.
tl;dr: The thing I was looking for was a combination of file_get_contents() and object buffering.
file_get_contents() returns a string of a plain html-file of your choice. I could post a ton of explanation here or simply link you to phppot.com. The article offers you a directly executable demo with source (Download here). In case you wanna try it with a html file of yours, simply change the file path.
So once the whole html was converted into a string, I used the postprocessing function of OB to alter the string (= basically my html) if it's an existing user that came to alter his data. Then all the html-code (in a string still at this point) is sent to the client using ob_end_flush(). I will put up the actual code asap :)

Session variable not set within functions

I'm trying to set a session variable to record when people have voted but PHP is flat out refusing to set it. The code is as follows:
elseif (isset($_GET['group']) && isset($_GET['vote']))
{
include_once(_INC.'otherheader.php');
groupVotePage($group, $vote);
$_SESSION[$group] = '1';
echo $_SESSION[$group];
}
Nothing. The function groupVotePage adds the vote to the database and echoes a thanks message. $group is the name of the group being voted for. I have session_start(); at the top of the page and have tried to declare the variable inside the function called as well, putting session_start(); everywhere. Session variables are used elsewhere on the site so I know it's not a server issue, and it's the same on all browsers I tried.
Declaring the session var inside the function works but only within the function - it doesn't go global.
if(!isset($_SESSION[$group])) {
$totalVote=$totalVote+$vote;
$totalNumVotes=$totalNumVotes+1;
$totalRating=round($totalVote/$totalNumVotes);
$totalScore=$totalVote*$totalNumVotes;
...db stuff...
$mysqli->query($query);
echo'Thanks for voting!';
}
else {
echo'You have already voted for this group!';
}
Maybe you can use PHP error reporting code to figure out where you going wrong
// Report all errors
error_reporting(E_ALL);
Okay fixed it, the < !DOCTYPE HTML> section was before the session_start();, when I put it after the code worked.

PHP SESSIONS are empty after reload page

I have code
<?php
require_once("lib/functions.php");
$page = new page;
if(isset($_POST['jmeno'])){
$page->mailit($_POST, $_SESSION['result']);
}
$_SESSION['f'] = rand(1,9);
$_SESSION['s'] = rand(1,9);
$_SESSION['result'] = $_SESSION['f'] + $_SESSION['s'];
?>
Before POST form it prints the right values, but after POST form the sessions are empty. I don't know why, looks like something is bad configured. So it's always show Bad counted result
Here is session configuration....
make sure that this line of code:
session_start();
Is at the beggining of your php file, right after the opening php tag <?php
This line of code is used to start new or resume existing session, please see php manual here
Make sure that your file had UTF-8 encoding. (not UTF-8-BOM)

MySQL Update big amount of html content issue

I've created autosave via Ajax for my content management system. Having problem. Problem is, when i'm testing on my local server, the php side updates big piece of data easily but when i'm testing it on my webhost, I see that, if the updated content is a big data, then php doesn't update the table row on the first attempt, updates only after second attempt. Any suggestion? How to deal with that problem?
PHP Side
<?php
session_start();
require '../../core/includes/common.php';
$err=array();
$name=filter($_POST['name'],$db);
$id=$db->escape_string($_POST['id']);
$title=filter($_POST['title'], $db);
$parentcheck=$db->escape_string($_POST['parentcheck']);
if(isset ($_POST['parent'])) $parent=$db->escape_string($_POST['parent']);
else $parent=$parentcheck;
$menu=$db->escape_string($_POST['menu']);
$content = html($_POST['content'], $db);
if (!isset($content)) die('error');
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
if ($result){
echo "{";
echo '"msg": "Success" ';
echo "}";
}
else{
echo "{";
echo
'"err": "Error"';
echo "}";
}
?>
Your code looks like you can have tons of potential errors, this example should only show what you can do to always return something back which might be in the format your AJAX request can deal with:
You're mixing two types of error handling: die'ing straight away and reporting your action result to AJAX. You should do the one way or the other, this one is reporting back always:
<?php
session_start();
require '../../core/includes/common.php';
...
if (!isset($content)) die('{"err": "No content"}'); // This will never happen BTW.
$result = $db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id");
if ($result)
{
echo '{"msg": "Success"'}';
}
else
{
echo '{"err": "Error"}';
}
?>
Can you do something like this, parse the html content for only the important content ie the div and not the entire page, Mysql text datatype supports 2GB, but its not safe to overload mysql.
Idea 1
Can you by any chance save the HTML content on an XML and refer the link along with the node in the Mysql Column so that AJAX picks up the xml and the node to display data on the fly.
Idea 2
Gzip the content and store in Mysql

Describe how a php page template can write another php page as html

Describe the mechanics in PHP relevant terms of a PHP/MYSQL page (A.php) that will 1) use one template to write itself (simple), 2) take input from the user to update a database (simple), 3) upon command parse another PHP page (B.php) (???) and save (B.php) page as a static HTML (B.html) (???).
UPDATE= I found a post, here at SO, helpfully suggesting (to another, GROAN, non-Uber Geek with a completely Pedestrian Question) he could capture html from a php page using output buffer. Will this work for a different php file?
There are more complex and better answers to each question, but I'm going to jot down the most simple ones.
PHP is a template language, so a PHP file with your template is your answer. This question is a bit vague.
Access the user-provided data using the $_GET or $_POST superglobals, with the choice depending on your HTTP request method. Basically, GET is for URL data, POST for form data. Once you have the data, validate it. Then use PDO to connect to a database and execute an insertion query.
You can use an output buffer, like so:
ob_start(); // Start output buffer
require 'B.php'; // Execute B.php, storing its output to the buffer
file_put_contents('B.html', ob_get_clean()); // Clean the buffer, retrieve its contents and write them to B.html
It saddened me to get reamed on this question. To show my Q was in good faith, I'm answering my own question with what was a simple solution. I created generate.php to run when a change was made to the content. No cache needed.
// the switch...
$update_live = isset($_GET['update_live']) ? TRUE : FALSE;
// $adminPath, $livePath, $adminUrl are set in an include and contains site config data...
$tempfile = $adminPath . 'tempindex.html'; //a temp file...
$livefile = $livePath . 'index.html'; //the static live file...
$this_template = $adminUrl . 'main-index.php'; //the php template file...
$username = "php_admin";
$password = "123xyz456";
if(!($update_live)){
$errors[] = "Did not submit from an edit page. You can only access this page by referral!";
}else{
if(file_exists($tempfile)){
unlink($tempfile);
}
/* =3, $html = file_get_contents($this_template, false, $context);*/
$html = file_get_contents($this_template);
if($html === false){
$errors[] = "Unable to load template. Static page update aborted!";
exit();
}
if(!file_put_contents($tempfile, $html)){
$errors[] = "Unable to write $tempfile. Static page update aborted!";
exit();
}
if(!copy($tempfile, $livefile)){
$errors[] = "Unable to overwrite index file. Static page update aborted!";
exit();
}
if(!unlink($tempfile)){
$errors[] = "Unable to delete $tempfile. Static page update aborted!";
exit();
}
}

Categories