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 :)
Related
I am trying to setup a PHP document but I currently am looking for a way to use the die() function and display some content on every page using my global configuration file. The way I am think how it should work is that IF the requested URL (e.g. domain.com/services/disabledservice) would have /services/disabled service and a value of 1 to make the value true in a MYSQL DB.
The plan is to have the URL be collected and checked with a table than if the row has a value of 1 for status it will display a disabled page message but if it’s 0 it will load normally.
Some research I have conducted may lead be to think that using the SQL query and the if function could work for this.
The idea I have is this but it may not be correct.
<?php $pageurl = [requested URL content here]
$checkstatus = "SELECT * FROM servicestatus WHERE page =" . $pageurl . "AND status = 1";
if ($status = mysqli_query($conn, $servicestatus)) {
if (mysqli_num_rows($status) = 1) { ?> html content here
<?php }
} else { ?>
page as normal
<?php } ?>
Edit:
To explain what I am trying to do.. I am trying to fetch the URL without everything past “?” Than I am trying to use that in a DB query to check with the database if that has a value of “m” or “d” and if it has one of those values next to the URL which is being fetched it will display the appropriate error page. This is being included as part of my core configuration file which includes my “$conn” and the core values for most stuff. The problem I am facing is that when I send my URL without everything past the “?” I am not receiving my error page and everything is loading like normal.
Use any one the following php functions:
include 'path_to_the_page.php' (or) require 'path_to_the_page.php';
The difference between include and require arises when the file being included cannot be found: include will emit a warning ( E_WARNING ) and the script will continue, whereas require will emit a fatal error ( E_COMPILE_ERROR ) and halt the script.
Since I asked my question (Previous question) in a way no doubt most users think "dude this is tl;dr" let me put it more simple. I want to use post-redirect-get pattern to avoid user refreshing the site and resubmiting the data etc... I understand that in order to do so I have to redirect the user from html form, through php processing script and back to a new site (or original html form site) that displays the processed data.
Now my question. How do I GET my processed data back from my php? I don't understand the GET part... Currently I don't know how to show php generated data in a nice html display (view) page without include 'site.html';. This example isn't what I am looking for either: Simple Post-Redirect-Get code example. Code in the below example just redirects me to a current page.
It depends on context, but for example:
Given: invoice-form.html, invoice-processing.php and current-invoices.php:
User fills in data on invoice-form
User submits form which has action="invoice-processing.php"
Browser POSTs data to invoice-processing
invoice-processing takes the data from the form and puts it in a database
invoice-processing outputs 302 status and a Location header
Browser goes to current-invoices
current-invoices fetches a list of invoices (including the most recently submitted one) from the database and sends them to the browser as an HTML document
I hope this will help because it has taken me quite a while to get it as well. I tested my understanding like this. I have two php pages, the first page (prg1.php) sends the form to the database, action set to the second one (prg2.php). prg2.php checks the POST data, updates the database and issues a redirect to prg1.php with anything I need to pass back as GET variables. prg2.php looks like this
<?php
if (isset($_POST['gameid'])){
// process the data, update the database
$gameid = htmlspecialchars($_POST['gameid']);
$playerid = htmlspecialchars($_POST['playerid']);
$message = htmlspecialchars($_POST['message']);
//redirect, after updating the database
$getinfo = '?gameid=' . $gameid . '&playerid=' . $playerid;
header("Location: prg1.php" . $getinfo );
exit();
}
?>
You could try something like this:
/****************************************/
/* Fetch my data. */
/****************************************/
$mydata = $_GET["data"];
/****************************************/
/* Has to be sent before anything else! */
/****************************************/
header( 'Location: http://www.yoursite.com/index.php?data='.$mydata );
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
I'm working on a jQuery AJAX call where I get a set of results from a search. I return html with an echo and I need to backup the results by inserting into the db. Will also have to check if they already exist before inserting.
I want the html to be returned as soon as possible. If I add insert code below the echo will the entire code have to finish running before the html is returned?
The most important thing is content returning back to the user right away.
This is all on mobile so every 100 milliseconds count.
$data = file_get_contents($url);
$result = json_decode($data, true);
foreach ( $result->results as $items ) {
$name = $items->name;
$description = $items->desc;
$id = $items->id;
$coverurl = $items->coverurl;
$returnhtml .= "<h3>".$name."</h3>";
$returnhtml .= "<h4>".$description."</h$>";
}
echo $returnhtml;
//how to backup to database
//check if already in db
//insert into db
To answer your question, yes. The entire script must complete before the HTML is outputted back to the client. You can use output buffering to capture the output, send it, and then continue on with other processing. The server will then try to output the remaining when the script finished but AJAX doesn't know how to handle the second part so it just ignores it.
Look into http://www.php.net/manual/en/ref.outcontrol.php
It'll be something like:
ob_start();
... generate html for client
ob_flush();// send output buffer to the client
... insert data into database
ob_end_clean();
After do the ob_flush as explained before, you can try MySQL INSERT DELAYED if you don't wait for the INSERT to complete.
http://dev.mysql.com/doc/refman/5.5/en/insert-delayed.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();
}
}