Jump to content

Dynamically Creating Page - Placeholders Not Working


Moorcam

Recommended Posts

Hi all,

Hope to find you all good.

I have the following, which creates a php file. This works fine and without error. However, once created, the content of the page, which is got from the Database, is not showing.

<?php
include_once('includes/header.php');

if(isset($_POST['new']) && $_POST['new']==1){
if(isset($_POST['submit'])){
    $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s"));
    $name = mysqli_real_escape_string($con, $_POST['name']);
    $description = mysqli_real_escape_string($con, $_POST['description']);
    $body = mysqli_real_escape_string($con, $_POST['body']);

    $submittedby = mysqli_real_escape_string($con, $_SESSION["username"]);

$sql = "SELECT * FROM pages WHERE name='$name'";

  	$res = mysqli_query($con, $sql);

  	if (mysqli_num_rows($res) > 0) {
  	  $message = '<i class="fa fa-times text-danger"> - A Page already exists with that name!</i>'; 	
  	}else{

    $ins_query="insert into pages (`trn_date`,`name`,`description`, `body`, `submittedby`)values ('$trn_date','$name','$description', '$body', '$submittedby')";
    mysqli_query($con,$ins_query)
    
    or die(mysqli_error($con));
    if(mysqli_affected_rows($con)== 1 ){

// Name of the template file.
$template_file = 'template.php';

// Root folder if working in subdirectory. Name is up to you ut must match with server's folder.
$base_path = '/protour/';

// Path to the directory where you store the "template.php" file.
$template_path = 'includes/';

// Path to the directory where php will store the auto-generated couple's pages.
$page_path = '../';

// Posted data.
$row['name'] = str_replace(' ', '', $_POST['name']);
$row['description'] = str_replace(' ', '', $_POST['description']);
$row['body'] = $_POST['body'];

// Data array (Should match with data above's order).
$placeholders = array('{name}', '{description}', '{body}');

// Get the template.php as a string.
$template = file_get_contents($template_path.$template_file);

// Fills the template.
$new_file = str_replace($placeholders, $row, $template);

// Generates couple's URL and makes it frendly and lowercase.
$page_url = str_replace(' ', '', strtolower($row['name'].'.php'));

// Save file into page directory.
$fp = fopen($page_path.$page_url, 'w');
fwrite($fp, $new_file);
fclose($fp);

// Set the variables to pass them to success page.
$_SESSION['page_url'] = $page_url;
// If working in root directory.
$_SESSION['page_path'] = str_replace('.', '', $page_path);
// If working in a sub directory.
$_SESSION['page_path'] = substr_replace($base_path, '', -1).str_replace('.', '',$page_path);

    $message = '<i class="fa fa-check"></i> - Page Created Successfully';
    }
}
}
}
?>
        <!-- Header-->

        <div class="breadcrumbs">
            <div class="col-sm-4">
                <div class="page-header float-left">
                    <div class="page-title">
                        <h1>Pages</h1>
                    </div>
                </div>
            </div>            <div class="col-sm-8">

            </div>
        </div>

        <div class="content mt-3">
            <div class="animated fadeIn">
                <div class="row">

                 <div class="col-lg-12">
                    <div class="card">
                      <div class="card-header"><strong>Add </strong><small>Page <?php 
                      if($message = isset($message) ? $message : ''){
                      printf($message); 
                      }
                      ?></small></div>
                      <div class="card-body card-block">
                            <form role="form" method="post" action"">
                                <input type="hidden" name="new" value="1" />
                            <div class="modal-body">
                                <div class="form-group"><label for="name" class=" form-control-label">Page Name</label><input type="text" id="name" name="name" placeholder="name" class="form-control">
                                </div>

                        <div class="form-group"><label for="description" class=" form-control-label">Description</label><input maxlength="100" type="text" id="description" name="description" placeholder="descriptioon" class="form-control"></div>

                        <div class="form-group"><label for="body" class=" form-control-label">Body</label>
                        <textarea class="form-control" id="body" name="body" placeholder="body"></textarea>
                        </div>

                            <div class="modal-footer">
                                <button type="submit" name="submit" id="submit" class="btn btn-primary">Confirm</button>
                            </div>
                            </form>
                  </div>
                </div>
            </div><!-- .animated -->
        </div><!-- .content -->


    </div><!-- /#right-panel -->

    <!-- Right Panel -->


    <script src="assets/js/vendor/jquery-2.1.4.min.js"></script>
    <script src="assets/js/popper.min.js"></script>
    <script src="assets/js/plugins.js"></script>
    <script src="assets/js/main.js"></script>
    <script src="assets/js/bing.js"></script>


    <script src="assets/js/lib/data-table/datatables.min.js"></script>
    <script src="assets/js/lib/data-table/dataTables.bootstrap.min.js"></script>
    <script src="assets/js/lib/data-table/dataTables.buttons.min.js"></script>
    <script src="assets/js/lib/data-table/buttons.bootstrap.min.js"></script>
    <script src="assets/js/lib/data-table/jszip.min.js"></script>
    <script src="assets/js/lib/data-table/pdfmake.min.js"></script>
    <script src="assets/js/lib/data-table/vfs_fonts.js"></script>
    <script src="assets/js/lib/data-table/buttons.html5.min.js"></script>
    <script src="assets/js/lib/data-table/buttons.print.min.js"></script>
    <script src="assets/js/lib/data-table/buttons.colVis.min.js"></script>
    <script src="assets/js/lib/data-table/datatables-init.js"></script>

 <script src="https://cdn.tiny.cloud/1/sw6bkvhzd3ev4xl3u9yx3tzrux4nthssiwgsog74altv1o65/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
  <script>
    tinymce.init({
      selector: 'textarea',
      plugins: 'advlist autolink lists link image charmap print preview hr anchor pagebreak',
      toolbar_mode: 'floating',
   });
  </script>

    <script type="text/javascript">
        $(document).ready(function() {
          $('#customer-table').DataTable();
        } );
    </script>


</body>
</html>

My guess is the placeholder section is not working.

// Posted data.
$row['name'] = str_replace(' ', '', $_POST['name']);
$row['description'] = str_replace(' ', '', $_POST['description']);
$row['body'] = $_POST['body'];

// Data array (Should match with data above's order).
$placeholders = array('{name}', '{description}', '{body}');

Here is template.php

<?php
include_once('includes/header.php');
require_once('admin/includes/config.php');
if(isset($_POST['new']) && $_POST['new']==1){

    $trn_date = mysqli_real_escape_string($con, date("Y-m-d H:i:s"));
    $name = mysqli_real_escape_string($con, $_POST['name']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $pickup = mysqli_real_escape_string($con, $_POST['pickup']);
    $dropoff = mysqli_real_escape_string($con, $_POST['dropoff']);
    $dep_date = mysqli_real_escape_string($con, $_POST['dep_date']);
    $ret_date = mysqli_real_escape_string($con, $_POST['ret_date']);
    $dep_time = mysqli_real_escape_string($con, $_POST['dep_time']);
    $pax_numbers = mysqli_real_escape_string($con, $_POST['pax_numbers']);



    $ins_query="insert into quotes (`trn_date`,`name`,`email`, `pickup`, `dropoff`, `dep_date`, `ret_date`, `dep_time`, `pax_numbers`) values ('$trn_date','$name','$email', '$pickup', '$dropoff', '$dep_date', '$ret_date', '$dep_time', '$pax_numbers')";
    mysqli_query($con,$ins_query)
    
    or die(mysqli_error($con));
    if(mysqli_affected_rows($con)== 1 ){
    $message = "Thank you. We will be in touch soon.";
    }
}
$sql = "SELECT * FROM slide";
$result = $con->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
    
    <div class="hero-wrap" style='background-image: url("admin/uploads/<?php echo $row['image']; ?>")' data-stellar-background-ratio="0.5">
      <div class="overlay"></div>
      <div class="container">
        <div class="row no-gutters slider-text justify-content-start align-items-center">
          <div class="col-lg-6 col-md-6 ftco-animate d-flex align-items-end">
          	<div class="text">
	            <p style="font-size: 18px;"><?php echo $row['slide_text']; ?></p>
	            <a href="<?php echo $row['youtube']; ?>" class="icon-wrap popup-vimeo d-flex align-items-center mt-4">
	            	<div class="icon d-flex align-items-center justify-content-center">
	            		<span class="ion-ios-play"></span>
	            	</div>
	            	<div class="heading-title ml-5">
		            	<span>Play Our Short Video</span>
	            	</div>
	            </a>
            </div>
          </div>
          <div class="col-lg-2 col"></div>
          <div class="col-lg-4 col-md-6 mt-0 mt-md-5 d-flex">
          	<form method="post" action="" role="form" class="request-form ftco-animate">
          	    <input type="hidden" name="new" value="1" />
          		<h2>Get A Quote</h2>
	    				<div class="d-flex">
	    					<div class="form-group mr-2">
	    					<label for="name" class="label">Name</label>
	    					<input class="form-control" type="text" id="name" name="name" placeholder="Your Name" />
	    				</div>
	              <div class="form-group ml-2">
	    					<label for="email" class="label">Email</label>
	    					<input class="form-control" type="email" id="email" name="email" placeholder="Your Email" />
	    				</div>
	    				</div>

	    				<div class="form-group">
	    					<label for="searchBox" class="label">Pick-Up Location</label>
	    					<input class="form-control" type="text" id="searchBox" name="pickup" placeholder="Start Typing..." />
	    				</div>
	    				<div class="form-group">
	    					<label for="searchBoxAlt" class="label">Drop-Off Location</label>
	    					<input type="text" class="form-control" id="searchBoxAlt" name="dropoff" placeholder="Start Typing..." />
	    				</div>
	    				<div class="d-flex">
	    					<div class="form-group mr-2">
	                <label for="" class="label">Departure Date</label>
	                <input type="text" class="form-control" id="book_pick_date" name="dep_date" placeholder="Date">
	              </div>
	              <div class="form-group ml-2">
	                <label for="" class="label">Return Date</label>
	                <input type="text" class="form-control" id="book_off_date" name="ret_date" placeholder="Date">
	              </div>
              </div>
              <div class="d-flex">
              <div class="form-group mr-2">
                <label for="" class="label">Pick-Up Time</label>
                <input type="text" class="form-control" id="time_pick" name="dep_time" placeholder="Time">
              </div>
              <div class="form-group ml-2">
                  <label for"" class="label">Passenger Numbers</label>
                  <input type="number" class="form-control" id="pax_numbers" name="pax_numbers" placeholder="Amount" />
              </div>
              </div>
	            <div class="form-group">
	              <button type="submit" class="btn btn-primary py-3 px-4">Request Quote</button>
	              <p><?php 
                      if($message = isset($message) ? $message : ''){
                      printf($message); 
                      }
                      ?></p>
	            </div>
	    			</form>
          </div>
        </div>
      </div>
    </div>
    <?php
}
}
?>
<script type="text/javascript" src="https://www.bing.com/api/maps/mapcontrol?key=AqIY0ivSCCdBIe3-EKGuox9cwBFw2wWRWIErZi1iy57EfD67PoiSra9wl_wu48de&callback=bingMapsReady" async defer></script>
<?php

if(isset($_GET['id'])){
$id = mysqli_real_escape_string($con, $_GET['id'] ?? DEFAULT_ID);
$sql = "SELECT * FROM pages WHERE id = $id";
$result = $con->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
?>
    <!-- HOW IT WORKS -->
		<section class="ftco-section ftco-no-pt ftco-no-pb">
			<div class="container">
				<div class="row no-gutters">

					<div class="col-md-12 wrap-about py-md-5 ftco-animate">
	          <div class="heading-section mb-5 pl-md-5">
	          	<span class="subheading"><?php echo $row['description']; ?>
	          	</span>
	            <h2 class="heading"><?php echo $row['name']; ?></h2>

	            <?php echo $row['body']; ?>
	          </div>
					</div>
				</div>
			</div>
		</section>
<?php
}
}
}
?>

<!-- FOOTER -->
<?php
include_once('includes/footer.php');
?>

Please note that this is just a project and will not be going live. It's for learning purposes and I am aware there are some vulnerabilities within parts of the code. Any assistance with the above issues though would really be appreciated.

Thanks and have a ripper evening.

Link to comment
Share on other sites

To answer the question itself, check your assumptions about those placeholders and the template file.

But this is all wrong. Creating files like this is definitely not the way to go about it. You say this is for learning purposes, right? Then you should definitely want to learn the right way to do it.

Given that the template stuff isn't working correctly (or rather, why it isn't working correctly) I can't quite say for sure exactly what it is you need to do. What I can tell you is that should be having one single PHP file handling every "page". A file that will probably look a lot like your template.php, in fact.
What you do is tell your web server that certain URLs it doesn't recognize should be routed to a PHP script. In this case, that URL would be something resembling the "name" you're currently templating. The PHP script takes that name, looks up the information in the database, and displays it.

The term you need to research is "URL rewriting". It's not hard to do.

Link to comment
Share on other sites

15 hours ago, requinix said:

To answer the question itself, check your assumptions about those placeholders and the template file.

But this is all wrong. Creating files like this is definitely not the way to go about it. You say this is for learning purposes, right? Then you should definitely want to learn the right way to do it.

Given that the template stuff isn't working correctly (or rather, why it isn't working correctly) I can't quite say for sure exactly what it is you need to do. What I can tell you is that should be having one single PHP file handling every "page". A file that will probably look a lot like your template.php, in fact.
What you do is tell your web server that certain URLs it doesn't recognize should be routed to a PHP script. In this case, that URL would be something resembling the "name" you're currently templating. The PHP script takes that name, looks up the information in the database, and displays it.

The term you need to research is "URL rewriting". It's not hard to do.

Hi mate,

You are spot on. It is a learning curve and I have taken your input on board and decided to go in the direction you suggested.

Cheers,

Dan

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.