i'm trying to make a online editor for a CMS panel. So that if I click on a file online I will get the file returned to me with the PHP/HTML etc. in it.
The problem now is that when I use the function stream_get_contents I'm not exactly getting back what I want...
This is my PHP part to get the file:
$fileAdresRoot = $_SERVER['DOCUMENT_ROOT'];
if(empty($_GET['name']))
{
header('Location: ftp-directory');
exit();
}
else
{
$fileName = trim($_GET['name']);
$fileAdres = $fileAdresRoot.'/'.$fileName.'';
}
if(isset($_GET['doublename']))
{
$fileMaps = trim($_GET['doublename']);
$fileAdres = $fileAdresRoot.'/'.$fileMaps.'/'.$fileName.'';
}
$fileContents = fopen($fileAdres, 'rb', false);
$fileContent = stream_get_contents($fileContents);
I'm echoëing $fileContent like this:
<pre id="editor"><?php echo $fileContent; ?></pre>
So it needs to give me this, it needs to show me this:
<?php
$getPage = 'Blog beheren';
include_once 'includes/header.php';
/* Starting with selecting the blog information and post from the database. */
if (isset($_GET["page"])) { $page = trim($_GET["page"]); } else { $page=1; }
$start_from = ($page-1) * 5;
$stmt = $mysqli->prepare("SELECT id, datum, auteur, comments, titel FROM blog ORDER BY id DESC LIMIT ?, 5");
$stmt->bind_param('s', $start_from);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($blogId, $blogDatum, $blogAuteur, $blogComments, $blogTitel);
$intBlog = $mysqli->query("SELECT id FROM blog")->num_rows;
?>
<!-- Matter -->
<div class="matter">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="widget">
<div class="widget-head">
But instead it's showing me this:
prepare("SELECT id,datum,comments,tags,titel,omschrijving,image,auteur FROM blog ORDER BY id DESC LIMIT ?,5");
$stmt->bind_param('i', $start);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($blogId, $blogDate, $blogComments, $blogTags, $blogTitle, $blogDesc, $blogImg, $blogAuth);
$intInfo = $stmt->num_rows;
?>
Home
Blog
Blog
So not only the HTML div's etc will not be shown, but also the
I believe what is happening currently is that your string is not being encoded to display as html entities, and so they are being rendered as actual HTML.
With what you are going for, you would want to echo your file contents with the htmlentities function
so it would look something like this:
<?php echo htmlentities($fileContent, ENT_HTML5); ?>
Related
so i have webpage called news.php where i show all the website news from database.
i want to make new page to view only single news by news id from database, for example the page is shownews.php
so this is my index.php
<?php
include('config/webconf.php');
include('includes/head.php');
include('includes/nav.php');
include('includes/body.php');
include('includes/foot.php');
?>
my body.php contain this to modify the url to /?p=pagename :
<?php
if(isset($_GET['p'])) {
if(file_exists("pages/" . $_GET['p'] . ".php")) {
include("pages/" . $_GET['p'] . ".php");
}else{
include("pages/notfound.php");
}
}else{
include("pages/info.php");
}
?>
news.php (show all news)
mysqli_select_db($conn, $webdb);
$stmt = $conn->prepare("SELECT id,title, content, author FROM news");
$stmt->execute();
$stmt->bind_result($newsid, $title, $content, $author);
$stmt->store_result();
if($stmt->num_rows > 0) {
while($stmt->fetch()) {
echo $title." (<a href='/?p=shownews?id=".$newsid."' target='_blank'>view</a>)";
}
}
so in shownews.php i want to get the id from $newsid, but i think cannot get it because of the url is /?p=shownews?id=1 where the url name function will not find shownews?id=1 (page not found)
so i tried to change /?p=shownews to pages/shownews.php?id=$newsid :
mysqli_select_db($conn, $webdb);
$stmt = $conn->prepare("SELECT id,title, content, author FROM news");
$stmt->execute();
$stmt->bind_result($newsid, $title, $content, $author);
$stmt->store_result();
if($stmt->num_rows > 0) {
while($stmt->fetch()) {
echo $title." (<a href='pages/shownews.php?id=".$newsid."' target='_blank'>view</a>)";
}
}
now i can get $news id by $_GET function in shownews.php, but the website styles is gone like div/background etc.
my question is, can i get the news id in page shownews.php without changing the url name function?
I am pulling data out of a DB and then displaying it on my html page. I had thought that my code below would work and it does as far as getting the data and placing it into variables. It breaks down when trying to inject the variable into a html tag. I had also, probably incorrectly, assume that by placing my html tags inside a php foreach loop that it would dynamically create all the tags needed depending on the number of rows returned. I need the foreach as the data is an array so to get each record I need to look through the array.
I have this code placed on in my body tag where I want the elements to be placed.
PHP functions in body tag above section where elements are to be.
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $connection;
// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('\assets\con_config.ini');
$connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
// Connect to the database
$connection = db_connect();
// Query the database
$result = mysqli_query($connection,$query);
return $result;
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
$rows = db_select("select CONCAT_WS(' ', fname, mname, lname) as author_name, title, image_location, rating, review, (Select mid(date_reviewed,1,2) from reviews where reviews.book_id = books.id) as day, (Select mid(date_reviewed,4,3) from reviews where reviews.book_id = books.id) as month, (Select mid(date_reviewed,8,2) from reviews where reviews.book_id = books.id) as year, sellers_site, twitter_site, fb_site, twitter_id, fb_id, genre from authors, books, book_genre, book_link, reviews, social_media where books.author_id = authors.id and book_genre.book_id = books.id and book_link.book_id = books.id and reviews.book_id = books.id and social_media.author_id = authors.id group by ireviews.reviews.date_reviewed ASC");
if($rows === false) {
$error = db_error();
// Handle error - inform administrator, log to file, show error page, etc.
}
//foreach($rows as $value){
//echo $value['author_name'] . "<br />\n";
//echo $value['title'] . "<br />\n";
//echo $value['rating'] . "<br />\n";
//}
?>
<? php foreach($rows as $value); ?>
HTML part for displaying the returned data.
<? php foreach($rows as $value); ?>
<div class="block">
<div class="row">
<div class="col-md-4 col-md-8">
<div class="widget-block">
<input id="rate1" value="<?php echo $value['rating']?>" type="number" class="rating" data-max="5" data-min="0" data-size="sm" data-show-clear="false" readOnly="readOnly">
<img class="img-responsive wow fadeInLeftBig animated" data-wow-duration="1.5s" src="<?php echo $value['$image_location']?>" alt="<?php echo $value['$author_name']?>">
<br>
Buy this book
</div>
</div>
<div class="col-md-6 col-md-8">
<div class="section-sub-title">
<article class="section-title-body white">
<h1 class="head-title">Author: <span><?php echo $value['$author_name']?> -</span> <?php echo $value['$title']?></h1>
<span class="point-line hidden-xs hidden-sm"></span>
<p>
<?php echo $value['$review']?>
</p>
</article>
</div>
</div>
</div>
</div>
<?php } ?>
Thank you!
You had a space between "<" and php keywords in your foreach, also you didn't have opening bracket or colon on the end of the same line. Try something like:
<?php foreach($rows as $value): ?>
....
<?php endforeach; ?>
I had also, probably incorrectly, assume that by placing my html tags
inside a php foreach loop that it would dynamically create all the
tags needed depending on the number of rows returned.
That's exactly how it works, except for a few sintax mistakes you made:
1:
<? php
should be
<?php
2:
foreach($rows as $value); ?>
should be this
foreach($rows as $value){ ?>
Also, if you're using a somewhat modern version of PHP (5.4+) you can use the short php tags and short output.
This
value="<?php echo $value['rating']?>"
equals to
value="<?=$value['rating']?>"
Try changing your foreach to:
foreach($rows as $value) { ?>
On the current page I've been working on, I've set the code out in a way that it would work as a live blog / update kind of system. The problem is, I load the stuff in from my database in my PHP, then I have AJAX which links to another file which will get the database content and refresh the area it is contained in on my site.
Thus' meaning it will auto-update every 15000 miliseconds with the data from the database. The Problem is, it already has the existing data loaded in. So no matter what. every 15000 milisecond it will refresh that div, so data that is already on the page will be duplicated.
More Clear Bulletpoint form
PHP queries database, echo's out the data.
AJAX checks another php page every 15000 miliseconds and echo's that out onto the first page.
Instead of only posting new content, it simply duplicates the original content. (Can have double posts or even tripple. It seems to vary)
I'm only really getting into PHP, I haven't put much time into it, and my knowledge of AJAX is non-exisistant so it presents problem doing something like this. I've tried searching on how to only echo out the existing data on page one, even though page two is handling the updates.
Here is the code however, sorry if it's messy, or does things in correctly. I am still learning this language.
First Page matchdayupdates.php?id=(in this case the id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
}
else {
}
if(!$requestEventsInformation && !$requestMatchInformation) {
echo '<div class="match-notice"><h4>There are currently no updates, this page will auto-update when there are new updates.</h4></div>';
}
echo $id;
?>
<script>
var auto_refresh = setInterval(function () {
$('.center-match-container').fadeOut('slow', function() {
$(this).load('/esports/match/matchinforequest.php?id=<?php echo $id; ?>', function() {
$(this).fadeIn('slow');
});
});
$.ajaxSetup({ cache: true });
}, 15000);
</script>
Second Page matchinforequest.php?id=(again this id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
echo "Received Data";
}
else {
}
The problem is that you are loading the new data into any HTML element with the class center-match-container, but the new data you get with AJAX also contains an element with the class center-match-container, so the second call loads it into two places and so on.
In matchinforequest.php remove <div class='center-match-container'> and the corresponding </div> and it should work.
As a side note, you are not using prepared statements, but instead putting the contents of $_GET['id'] directly into your database query. This means someone could easily wipe your database by setting id to something like 0'; DELETE FROM matchinfo; '. Please look into prepared statements http://php.net/manual/en/mysqli.prepare.php and update your code to avoid this security risk!
My question to you is how do I get the code below to echo its entirety? I have multiples of these that I need to echo using while and I have toyed with it but have yet to figure out what to do. The answers I have seen, I have tried but they just don't work on my code. I need to have all this code here in one bunch but I am having an issue inserting the "like button" section. The issue starts at
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
and here's the full code
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$row['formtype'].'
</div>
</div>
<div class="top-submit">
“'. $row["actual_quote"] . '”
</div>
<div class="poster">- '. $row["poster"].'
<div class = "like">- '.
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
$dislikes = (empty($_POST['dislike'])) ? : $_POST['dislike'] ;
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['like'])){
$likes1 = $likes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (likes) VALUES ( :likes)");
$update1->bindParam(':likes', $likes1, PDO::PARAM_STR);
$update1->execute();
}
if(isset($_POST['dislike'])){
$dislikes1 = $dislikes+1;
$voted1 = $voted+1;
$query2 = $db->prepare("INSERT INTO voters (voted, ip) VALUES ( :voted, :ip)");
$query2->bindParam(':voted', $voted1, PDO::PARAM_STR);
$query2->bindParam(':ip', $ip, PDO::PARAM_STR);
$query2->execute();
header("Location: like.php?");
$update1 = $db->prepare("INSERT INTO votes (dislikes) VALUES ( :dislikes)");
$update1->bindParam(':dislikes', $dislikes1, PDO::PARAM_STR);
$update1->execute();
}
$stmt = $db->query("SELECT * FROM voters");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row3 = $stmt->fetch();
echo "Likes: $likes <br /> Dislikes: $dislikes<br />";
if(isset($row3['voted'])){
if(isset($row3['ip'])){
echo "You have already voted for this.";
}
} else {
echo "<form action = '' method = 'post'> <input type = 'submit' name = 'like' value = 'like'> <input type = 'submit' name = 'dislike' value = 'dislike'></form>";
}'
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
There may be a very simple solution but I have searched everywhere for it. I have tried using a . at the end but it doesn't like that. Any suggestions?
EDIT I have changed one portion, the whole code starting at $likes and ending after else{} has been put as this:
<div class = "like">';
include("like.php");
echo'</div>
You don't. You stop your echo, do your other code, and start echoing again.
echo 'foo';
bar();
echo 'baz';
You shouldn't use echo in this way.
Try to keep your HTML in variable and concatenate all needed additional HTML using dot after checking all necessary conditions.
$output = '<div>blahblah</div>';
if ($somedatafromDB == true) {
$output .= '<p>true!!</p>';
} else {
$output .= '<p>false :/</p>';
}
// and finally
echo $output;
An issue might also be the ternary operator:
Your code is currently
$likes = (empty($_POST['like'])) ? : $_POST['like'] ;
Try to change it to
$likes = (empty($_POST['like'])) ? 0 : $_POST['like'];
You need to specify what you would like to return if the $_POST['like'] is empty.
The ternary operator (x?y:z) returns y if x is true, else it returns z. In your case y is missing which might cause an error during execution.
A good practice is ini_set("display_errors", "on"); at the beginning of the script for debugging purposes.
here is my problem - i have Div with include "file.php" with content of Database then i Insert new data to database and want to reload .load() file.php to div but content is same until i refresh the page. Someone who know what it is ?
File.php
<?php
include "../lib/dbconnect.php";
$class = $_GET['class'];
$get_posts = mysql_query("SELECT content, date, author, author_id FROM classPosts WHERE class = '$class' ORDER BY id DESC");
while (list($content, $time, $author, $author_id) = mysql_fetch_row($get_posts)){
$get_user_name = mysql_query("SELECT name, lastName FROM users WHERE nick = '$author'");
while (list($name, $lastName) = mysql_fetch_row($get_user_name)){
$time = new Cokidoo_DateTime("#" . $time);
echo "
<div class=\"div\">
<div class=crop-small title=\"$author\">
<a href=/user/user.php?user=$author_id><img src=/user/pics/$author_id.jpg class=img-small></a>
</div>
<span class=small-text><b style=\"color: rgb(100,100,100)\">$name $lastName</b><br>
<span class=\"small-text\">Přezdívka <b style=\"color: rgb(100,100,100)\">$author</b></span><br>
Přidáno $time</span><p><br></p>
<span class=\"small-text\">$content</span>
</div>
";
}
}
?>
there is Javascript
if(data.success)
{
$("#class_posts").fadeOut(function(){
$("#new_post").hide(0);
$("#class_posts").load("../trida/get_posts.php");
$("#class_posts").fadeIn();
$("#new_post_text").html("");
});
}
try appending a random number on the end as a query string - to prevent caching.
var randNum = Math.floor(Math.random() * 999999);
$("#class_posts").load("../trida/get_posts.php?"+randNum);