Stuck on placing Html code within some PHP Code - php

Hello there stack members,
I currently have a error report I wish to show - And Id like a static piece of html to be available for my GET errors.
Currently the way I have it
apicheck.php?key=dfdf - Displays a nice footer
apicheck.php?url=dfdf - Does not display footer as its currently referenced within the $_GET['url'] section.
What my ultimate goal is to have the html code somewhere around where the die function is as id like to have all 3 get error messages be able to display the HTML footer
Ive added the die function in so that I can keep the code separate from whats underneath
Im still quite new and this is my first type of adventure into anything like this
I wasnt too sure how to add the html anywhere else as it wouldnt be within one of the IF sections - id be grateful if someone could explain how to add it in other areas
<?php
echo "<html><head><title>Error Report</title><style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}.style1 {font-size: 9px}
-->
</style> </head><body>
<h1>API Authentication System 1.0.1 GPX</h1>
<HR size='1' noshade='noshade'>";
if(empty($_GET)){
echo "<p><b>Error Name:</b> <u>VAR_M</u><br>";
echo "<p><b>Description:</b> <u>No Variables Sent</u><br><br>";
}
if(empty($_GET['key'])){
echo "<p><b>Error Name:</b> <u>API_KEY</u><br>";
echo "<p><b>Description:</b> <u>Missing API-Key</u><br><br>";
}
if(empty($_GET['url'])){
echo "<p><b>Error Name:</b> <u>URL_M</u><br>";
echo "<p><b>Description:</b> <u>Missing URL</u><br>";
echo "</u></p><HR size='1' noshade='noshade'>
<h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>
</body>
</html>";
die();
}
else
?>

If you want to make reusing the same html structure easy, you could use a function to echo it.
function echoError($name, $description) {
echo "<p><b>Error Name:</b> <u>$name</u><br>";
echo "<p><b>Description:</b> <u>$description</u><br><br>";
}
Making your entire code look something like this:
<html>
<head>
<title>Error Report</title>
<style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}.style1 {font-size: 9px}
-->
</style>
</head>
<body>
<h1>API Authentication System 1.0.1 GPX</h1>
<HR size='1' noshade='noshade'>";
<?php
$error_found = false;
if(empty($_GET)){
echoError("VAR_M", "No Variables Sent");
$error_found = true;
}
if(empty($_GET['key'])){
echoError("API_KEY", "Missing API-Key");
$error_found = true;
}
if(empty($_GET['url'])){
echoError("URL_M", "Missing URL");
$error_found = true;
}
if ($error_found) {
echo "<HR size='1' noshade='noshade'><h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>";
}
?>
</body>
</html>

Is the footer you're referring to this text?
echo "</u></p><HR size='1' noshade='noshade'>
<h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>
</body>
</html>";
If so, just put it in a separate if statement that evaluates to true if any error condition is applicable:
if(empty($_GET) or empty($_GET['key']) or empty($_GET['url']) {
echo "</u></p><HR size='1' noshade='noshade'>
<h3 align='center' class='style1'>X Auth /1.0.1.GPX</h3>
</body>
</html>"
die();
}
Better yet, you could include a line like $error_found = 1; inside each of your other error message conditional blocks, and then just test for $error_found when printing the footer and the die() statement. That way, if you add additional error checks you don't have to remember to also add that conditional to the final if statement.

You could build a string (start with an empty string and concatenate the error messages to it as you get them) and then print the string wherever you want.
$errorString = "";
if(empty($_GET)) {
$errorString .= "<p><b>Error Name:</b> <u>VAR_M</u><br>";
...
And at the end, or wherever you want,
echo $errorString;

You could clean this up by putting the html sections in their own files and then including them using include "file.html"; You could alternativly simplify those echo statements by using Heredoc

Related

Set backgroung image in .php file

I downloaded this code:
$image = ImageClass::getImage('bg.jpeg','myTitle');
$bg_img = explode(" ",$image);
$src = substr(strpos('"',$bg_img),strlen($bg_image)-1);
echo "<div style='background-image: url(".$src.");' ></div>
<?php
/*
*** OPTIONS ***/
// TITLE OF PAGE
$title = "ARQUIVOS PROPAR";
// STYLING (light or dark)
$color = "dark";
// ADD SPECIFIC FILES YOU WANT TO IGNORE HERE
$ignore_file_list = array( ".htaccess", "Thumbs.db", ".DS_Store", "index.php", "flat.png", "error_log" );
// ADD SPECIFIC FILE EXTENSIONS YOU WANT TO IGNORE HERE, EXAMPLE: array('psd','jpg','jpeg')
$ignore_ext_list = array( );
// SORT BY
$sort_by = "name_asc"; // options: name_asc, name_desc, date_asc, date_desc
// ICON URL
//$icon_url = "https://www.dropbox.com/s/lzxi5abx2gaj84q/flat.png?dl=0"; // DIRECT LINK
$icon_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAAyCAYAAADP7vEwAAAgAElEQVR4nOy9d5hdV3nv";
// TOGGLE SUB FOLDERS, SET TO false IF YOU WANT OFF
$toggle_sub_folders = true;
// FORCE DOWNLOAD ATTRIBUTE
$force_download = true;
// IGNORE EMPTY FOLDERS
$ignore_empty_folders = false;
// SET TITLE BASED ON FOLDER NAME, IF NOT SET ABOVE
if( !$title ) { $title = clean_title(basename(dirname(__FILE__))); }
?>
Th full code can be download here: https://github.com/halgatewood/file-directory-list/blob/master/index.php
I'm having problem with the start:
$image = ImageClass::getImage('bg.jpeg','myTitle');
$bg_img = explode(" ",$image);
$src = substr(strpos('"',$bg_img),strlen($bg_image)-1);
echo "<div style='background-image: url(".$src.");' ></div>
I want to put a picture as background, but it isn't happening. What's wrong?
Changed with the answer:
<?php
echo "<div style='background-image: url('/bg.jpeg');' ></div>";
?>
<?php
/*
*** OPTIONS ***/
// TITLE OF PAGE
$title = "ARQUIVOS PROPAR";
// STYLING (light or dark)
$color = "dark";
etc..
No need for all that,
What you desire to achieve is much simpler.
Assuming this code is inside index.php and your server's directory structure:
/some-folder/
/index.php
/bg.jpeg
Simply link it as its done in plain html —
<?php
echo "<div style=\"background-image: url('/bg.jpeg');\" ></div>";
?>
If you wan't it do be dynamic, i.e, image files's name is inside a variable then,
<?php
$my_image = 'bg.jpeg';
echo "<div style='background-image: url($my_image);' ></div>";
?>
Update:
Important Tip: All programming languages are executed line-by-line, this tip applies not only to PHP, but also HTML Learn More
Assume for example, your page's html structure returned to the browser is as provide below and you want to apply background to body tag
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
Simply copying and pasting my code to the top of page will result in
<div style="background-image: url('bg.jpeg');" ></div>
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
But that created a empty div tag at the top of html output, i wanted it to apply background to by body tag instead !!!?
— This happened because echo is used to send output to the browser as soon as it is executed. So since you copied my code to the top of your script the html output is also at the top.
But why did it echo <div style="background-image: url('bg.jpeg');" ></div> when i wanted it to apply to my page's body?
— Because the echo statements reads "<div style=\"background-image: url('bg.jpeg');\" ></div>"; as its output.
Ok, but how to apply the background-image to body then??
As mentioned earlier code is executed line-by-line, so in order to apply the style to pages's body tag you'll need to call it near your body tag and also modify it to not output the div it currently does.
So assuming your index.php is:
<?php
$my_image = 'bg.jpeg';
echo "<div style='background-image: url($my_image);' ></div>";
?>
<html>
<head><head>
<body>
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
You'll need to change it to —
<?php
$my_image = 'bg.jpeg';
// don't echo any thing here
?>
<html>
<head><head>
<body style="background-image: url('<?php echo $my_image; ?>')">
<!-- apply the style to body -->
<nav>Some dummy navigation</nav>
<div>welcome to my website</div>
<footer>Copyright</footer>
</body>
</html>
Hopefully i explained it well :)

php how to reload "require" include file after submit in self submitting form

I am making a self processing php form. I have a header.inc and footer.inc both called with a require statement. My problem lies in my header uses a $title variable which I would like to update after post. Currently my variable is changing and I can echo it in my response (thank you) page, but the header does not reload to reflect the change.
I understand I could call the title in my main PHP file, but I was hoping to find a way to reload the require(header.inc) file and continue processing the form.
<?php
$title = "XX";
$title2 = "Form";
$thisScript = htmlspecialchars($_SERVER['PHP_SELF']);
require("htmlHead.inc");
function changeTitle()
{
$GLOBALS['title2'] = "Results";
}
changeTitle();
if (!isset($_POST['submit']))
{
echo <<<FORMDOC1
<form action="$thisScript" method="post" action=" "
onSubmit="window.location.reload()">
FORMDOC1;
else
{
//random code
}
require("htmlFoot.inc");
?>
header.inc file in question:
<?php
echo "<!doctype html> <!-- Author: $author -->\n";
echo "<html lang=\"en\"><!-- Date Written: $dateWritten -->\n";
echo "<head> <!-- Description: $description -->\n";
echo "\t<title>$title</title>\n";
echo "\t<title>$title2</title>\n";
echo "\t<meta charset=\"utf-8\" />\n";
echo "\t<link rel=\"stylesheet\" href=\"css.css\" />\n";
echo "</head>\n";
echo "<body>\n";
echo "<div id=\"wrapper\">\n";
echo "<h1>$title</h1>\n";
echo "<h2>$title2</h2>\n";
?>
You are setting the title after including the header. Therefore, the value hasn't changed yet at the time php has output the header content.
Try following this general structure
if(isset($_POST['submit')) {
//process the form
include('header.inc');
//display confirmation
}
else {
include('header.inc');
//display the form
}
include('footer.inc');

php - How to use jquery correctly in .php files? WP-Admin only showing html

I have a wordpress installation where I am currently trying to create a formular where after sending the formular I process the data and save it into a mysql DB.
To achieve this I have created a new .php file which I included in the "function.php" of my theme because i want to add the whole formular/process with a shortcode.
The .php file currently contains this (Simplified):
function FNC_Add_New_Record ()
{
$options = "<option value='unselected'>- Select one -</option>"
. "<option value='option1'>Option 1</option>"
. "<option value='option2'>Option 2</option>";
echo "<br>";
echo "<form id='form1' method='post'>";
echo "<div style='text-align: center;'>";
echo "<font size=5>Selection 1</font><br>";
echo "<input type='text' name='textfield1' placeholder='Insert caption here'><br>";
echo "<select id='selection1'>" . $options . "</select>";
echo "<select id='selection2'><option value='unselected'>- No option1 selected -</option></select>";
echo "<br><br>";
echo "</div>";
echo "</form>";
echo "<br>";
}
add_shortcode('FNC_Add_New_Record','FNC_Add_New_Record');
Because the selection 2 depends on what is selected with the selection 1 I added jquery to the end of the .php file:
?><!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function () {
$("#selection1").change(function () {
var val = $(this).val();
if (val == "option1") {
$("#selection2").html("<option value='none'>None</option><option value='option2'>Option 2</option>");
} else if (val == "option2") {
$("#selection2").html("<option value='none'>None</option><option value='option2'>Option 2</option>");
} else if (val == "unselected") {
$("#selection2").html("<option value='unselected'>- No option1 selected -</option>");
}
});
});
</script>
So, there is probably a lot I have done wrong but this was the only way I was able to get it working. Yes I have searched here and on a lot other sides for proper solutions which tell me to add it to the function.php of the theme and do it with "enqueue". I have tried all of the possible suggest functions and code snippets but nothing worked.
The issue what I have with this solution is that it renders the wp-admin of my wordpress installation useless because it just shows the code which I have added to the .php file as html.
what I get on my site accessing wp-admin:
Also i'd like to note that using the tag "<!DOCTYPE html>" is a solution to another problem I have when adding jquery but i have no idea if it's the correct solution. If I remove this tag the main navigation of my website, instead of being like 15px in height suddenly has a height of almost a whole full HD screen.
Wordpress function.php also includes all JS files, make use of wp_enqueue_scripts to queue up your scripts.
function my_scripts_loader() {
wp_enqueue_script('myjquerylib-js', get_template_directory_uri() . '/assets/js/myjquerylib.js');
}
add_action('wp_enqueue_scripts', 'my_scripts_loader');

PHP script tags

Why does this if statement have each of its conditionals wrapped in PHP tags?
<?php if(!is_null($sel_subject)) { //subject selected? ?>
<h2><?php echo $sel_subject["menu_name"]; ?></h2>
<?php } elseif (!is_null($sel_page)) { //page selected? ?>
<h2><?php echo $sel_page["menu_name"]; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or a page to edit</h2>
<?php } ?>
Because there is html used. Jumping between PHP and HTML is called escaping.
But I recommend you not to use PHP and HTML like this. May have a look to some template-systems e.g. Smarty or Frameworks with build-in template-systems like e.g. Symfony using twig.
Sometimes its ok if you have a file with much HTML and need to pass a PHP variable.
Sample
<?php $title="sample"; ?>
<html>
<title><?php echo $title; ?></title>
<body>
</body>
</html>
This is not much html but a sample how it could look like.
That sample you provided us should more look like....
<?php
if(!is_null($sel_subject))
{ //subject selected?
$content = $sel_subject["menu_name"];
}
else if (!is_null($sel_page))
{ //page selected?
$content = $sel_page["menu_name"];
}
else
{ // nothing selected
$content = "Select a subject or a page to edit";
}
echo "<h2>{$content}</h2>";
?>
You could echo each line of course. I prefer to store this in a variable so I can easy prevent the output by editing one line in the end and not each line where I have added a echo.
According to some comments i did a approvement to the source :)
Because the <h2> tags are not PHP and will display an error if the PHP Tags are removed.
This code will display one line of text wrapped in <h2> tags.
This is called escaping.
Because you cannot just type html between your php tags.
However, I would rather use the following syntax because it is easier to read. But that depends on the programmers opinion.
<?php
if(!is_null($sel_subject))
{ //subject selected?
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
}
elseif (!is_null($sel_page))
{ //page selected?
ehco "<h2>" . $sel_page["menu_name"] . "</h2>";
}
else
{ // nothing selected
echo "<h2>Select a subject or a page to edit</h2>";
}
Because inside the if-statement there is an HTML code, which you can put it by closing PHP tags and open it again like this:
<?php if(/*condition*/){ ?> <html></html> <?php } ?>
or:
<?php if(/*condition*/){ echo '<html></html>' ; }
That is because in this snippet we see html and php code. The code <?php changes from html-mode to php-mode and the code ?> changes back to html-mode.
There are several possibilites to rewrite this code to make it more readable. I'd suggest the following:
<?php
//subject selected?
if (!is_null($sel_subject)) {
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
//page selected?
} elseif (!is_null($sel_page)) {
echo "<h2>" . $sel_page["menu_name"] . "</h2>";
// nothing selected
} else {
echo "<h2>Select a subject or a page to edit</h2>";
}
?>
using the echo-command to output html, you don't need to change from php-mode to html-mode and you can reduce the php-tag down to only one.

PHP $_server name and uri

Hi I'm trying to get a piece of html to only show on the main page which is http://www.domain.com/ ... I wrote the code below but it doesn't work the HTML is showing regardless of the page, am I missing something
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
?>
<div style="margin:0 auto;">
<div style="float:left">
<?php endif; ?>
First of all - please change
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
into
$hweb = 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$hweb may be initialized somewhere before.
Second:
As long as you request 'http://www.domain.com/somename.php' your if condition will never get executed. REQUEST_URI will always hold '/somename.php' except you use some url rewriting.
Third:
Make sure all calls go to 'http://www.domain.com' and not to 'http://domain.com'. Subdomain configurtaions sometimes are very complicated.
At the risk of getting it wrong again..
Why not initialize a variable in the main file before including the header
<?php
$mainfile = true;
?>
then in the header
<?php
if ($mainfile===true)
....
This way the main file can be called anything and be placed anywhere.
Solution 1:
If the above code is written inside 'http://www.domain.com/index.php' file then it may work fine.
Solution 2:
else make sure that $hewb is set with null value earlier b4 this code so that ".=" would not add extra value b4 'http...'.
Now
$hweb = '';
echo $hweb .= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
That is because the the HTML is inline in the php file but outside of the PHP tags. You can simply echo the HTML inside the if.
if ($hweb == 'http://www.domain.com/')
{
echo '<div style="margin:0 auto;">';
echo '<div style="float:left">';
}
or if you have lots of HTML you could do it like this
<?php
ob_start();
?>
<html>
<body>
<p>This HTML only be echoed </p>
</body>
</html>
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
{
ob_end_flush();
}
else
{
ob_end_clean(); // Probably not needed
}
?>

Categories