My entire PHP page only displays as text and no PHP code is executed. It's weird because when I test it using <? phpinfo(); ?> in a test.php file, I get a successful test and it works on my Apache server. However when I attempt to do anything else. It only shows as text.
Edit: Here is the link to the code. I couldn't figure out how to post it here. Pastebin
<?php
// create short variable names
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$find = $_POST['find'];
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
echo "<p>Order processed at ".date('H:i, jS F Y')."</p>";
echo "<p>Your order is as follows: </p>";
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo "Items ordered: ".$totalqty."<br />";
if ($totalqty == 0) {
echo "You did not order anything on the previous page!<br />";
} else {
if ($tireqty > 0) {
echo $tireqty." tires<br />";
}
if ($oilqty > 0) {
echo $oilqty." bottles of oil<br />";
}
if ($sparkqty > 0) {
echo $sparkqty." spark plugs<br />";
}
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
echo "Subtotal: $".number_format($totalamount,2)."<br />";
$taxrate = 0.10; // local sales tax is 10%
$totalamount = $totalamount * (1 + $taxrate);
echo "Total including tax: $".number_format($totalamount,2)."<br />";
if($find == "a") {
echo "<p>Regular customer.</p>";
} elseif($find == "b") {
echo "<p>Customer referred by TV advert.</p>";
} elseif($find == "c") {
echo "<p>Customer referred by phone directory.</p>";
} elseif($find == "d") {
echo "<p>Customer referred by word of mouth.</p>";
} else {
echo "<p>We do not know how this customer found us.</p>";
}
?>
</body>
</html>
I am willing to bet 10$ that test.php uses <?php, and the changed code uses <?, while the server does not understand it as an opening tag since short_open_tags is off in php.ini.
A lot of books use <? for open tags, while most servers only support the long version (<?php). If that's the case, then changing all the simple <? to <?php will do the trick.
PHP code is only exposed in 1 case: When PHP interpreter does not identify it as PHP code. That can be caused by only 2 problems:
Wrong configuration of Apache (or other http server) which doesn't handle php files at all.
Wrong open tags in PHP files, so PHP doesn't know when code begins.
If the file is a *.php, if Apache is turned on serving *.php files through PHP interpreter, if standard open tags are used or PHP is configured to use other types of used tags, and if you're accessing this PHP file through the browser, in no circumstances would PHP expose this code.
Related
Has anyone found a solution, how to display a message in the browser every second using PHP?
Until now, I've always used the following code, which worked fine on my server running IIS 6:
<html>
<body>
<?php
for ($counter = 0; $counter <= 10; $counter++) {
echo "Message after " . $counter . " second(s)<br>";
ob_flush();
flush();
sleep(1);
}
?>
</body>
</html>
I've seen several posts that ob_flush no longer works with the newer IIS versions.
I use IIS on Windows 10.
In some posts I read to add responseBufferLimit="0" into the section PHP_via_FastCGI of the file C:\Windows\System32\inetsrv\config\applicationHost.config.
But in this file I've only the following section about fastCgi so I've no idea how to add responseBufferLimit="0" into this section:
<fastCgi>
<application fullPath="C:\Program Files\PHP\php-cgi.exe" />
</fastCgi>
Any help is very appreciated.
I've done some tests. It's still a workaround, but a bit smarter and I think as long as there's no better solution, you can live with it.
You just have to add echo str_repeat(" ", 7500000); at the very beginning of your code and ob_flush() and flush() will do what they're supposed to do (also with the new IIS versions):
<html>
<body>
<?php
echo str_repeat(" ", 7500000);
for ($counter = 0; $counter <= 10; $counter++) {
echo "Message after " . $counter . " second(s)<br>";
ob_flush();
flush();
sleep(1);
}
?>
</body>
</html>
The following code is definitely not a smart and good solution, but maybe you can use it as a workaround until someone here shows us the smart solution, which I'm also very interested in.
<html>
<body>
<?php
for ($counter = 0; $counter <= 10; $counter++) {
echo "Message after " . $counter . " second(s)";
echo str_repeat(" ", 10000000) . "<br>";
sleep(1);
}
?>
</body>
</html>
I´m running a php code inside an HTML code so that depending of the value of a variable a specific CSS file is selected.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name = "viewport" content="width=device-width, initial-scale=1.0">
<title>Soluciones Elisar</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght#300;500;600&display=swap" rel="stylesheet">
<?php
$monitoreo = $_POST["actividad"];
$file='test.html';
$data = $monitoreo;
if ($data == 0) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles.css\";</style>";
}
if ($data == 1) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles2.css\";</style>";
}
if ($data == 2) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles3.css\";</style>";
}
if ($data == 3) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles4.css\";</style>";
}
if ($data == 4) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles5.css\";</style>";
}
if ($data == 5) {
echo "<style type=\"text\css\" media=\"screen\">#import \"/css/styles6.css\";</style>";
}
?>
</head>
<body>
However the HTML file on my server ignores the CSS file and just prints
#import \"/css/styles.css\";"; } if ($data == 1) { echo ""; } if ($data == 2) { echo ""; } if ($data == 3) { echo ""; } if ($data == 4) { echo ""; } if ($data == 5) { echo ""; } ?>
I dont know if it´s my code or if I´m misunderstanding how php and HTML work. Thank you
How are you viewing what the server is producing? If you're using the browser's inspector, bear in mind that this does not show the actual source code — it shows the browser's best interpretation of the source code, with invalid HTML tidied up. You can view the actual source code with the "View Source" option in the browser; the usual shortcut in most browsers is Ctrl+U.
If you do that, my guess (I could be wrong) is that you'll see that the PHP isn't running at all, and what's being served to the browser is the actual PHP code you've written. If I do not mistake my guess, your problem is not a coding issue, but a server configuration issue.
The PHP file should be run and parsed on the server, and the output of that PHP should be sent to the browser, to be parsed there. Exactly how you tell the server to run and parse PHP varies from server to server, but usually it starts with naming the file with the .php extension (if you have full control of the server config, you can tell it to treat .html or even .asp or .whatever files as PHP if you want, but this is unusual and confusing, so you probably shouldn't). You'll also need to ensure that PHP is installed on the server, and that the server's PHP module is enabled for the site. You know your server better than we do, and can search for appropriate tutorials.
Try writing your code with single and double quotes like:
echo '<div class="card">';
It worked for me earlier when I had issues with php.
I am debugging an open source PHP software (not a free one) for a client of mine.
It's a cashier software.
They have an issue with a document containing 748 lines.
When trying to display the document, PHP crashes and the user have to wait for the timeout.
It crashes on that echo (not the affichageUneLigne function, but really on the echo):
while ($r_sql = mysql_fetch_array($result)) {
echo affichageUneLigne($conn_mag, $r_sql, $typePRIX, $articleTEMPS, $clienDe, $caissier, $themeCAISSE, $provenance);
print '<div id="clearer"></div>';
$cptLIGNE++;
}
When I do that:
while ($r_sql = mysql_fetch_array($result)) {
if ($r_sql['DL_Ligne'] < 6360000){
echo affichageUneLigne($conn_mag, $r_sql, $typePRIX, $articleTEMPS, $clienDe, $caissier, $themeCAISSE, $provenance);
print '<div id="clearer"></div>';
$cptLIGNE++;
}
}
or that:
while ($r_sql = mysql_fetch_array($result)) {
if ($r_sql['DL_Ligne'] >= 6360000){
echo affichageUneLigne($conn_mag, $r_sql, $typePRIX, $articleTEMPS, $clienDe, $caissier, $themeCAISSE, $provenance);
print '<div id="clearer"></div>';
$cptLIGNE++;
}
}
It works. (Knowing that DL_Ligne is the line number with a step of 1000.)
I tought of a buffer length problem, but ob_flush before that line doesn't solve it, nor does it by increasing the memory_limit parameter.
PS: Do not ask me chy the developpers of this software have mixed echo and print, it's like that everywhere in the code...
What happens if you do something like this?
<?php
$outputArray = [];
while ($r_sql = mysql_fetch_array($result)) {
$outputArray[] = affichageUneLigne($conn_mag, $r_sql, $typePRIX, $articleTEMPS, $clienDe, $caissier, $themeCAISSE, $provenance);
$cptLIGNE++;
}
$outputString = implode('<div id="clearer"></div>', $outputArray);
echo $outputString . '<div id="clearer"></div>';
So I have a simple html page that looks like this.
<html>
<head>
<?php include("scripts/header.php"); ?>
<title>Directory</title>
</head>
<body>
<?php include("scripts/navbar.php"); ?>
<div id="phd">
<span id="ph">DIRECTORY</span>
<div id="dir">
<?php include("scripts/autodir.php"); ?>
</div>
</div>
<!--Footer Below-->
<?php include("scripts/footer.php"); ?>
<!--End Footer-->
</body>
</html>
Now, the problem is, when I load the page, it's all sorts of messed up. Viewing the page source code reveals that everything after <div id="dir"> is COMPLETELY GONE. The file ends there. There is no included script, no </div>'s, footer, or even </body>, </html>. But it's not spitting out any errors whatsoever. Just erasing the document from the include onward without any reason myself or my buddies can figure out. None of us have ever experienced this kind of strange behavior.
The script being called in question is a script that will fetch picture files from the server (that I've uploaded, not users) and spit out links to the appropriate page in the archive automatically upon page load because having to edit the Directory page every time I upload a new image is a real hassle.
The code in question is below:
<?php
//Define how many pages in each chapter.
//And define all the chapters like this.
//const CHAPTER_1 = 13; etc.
const CHAPTER_1 = 2; //2 for test purposes only.
//+-------------------------------------------------------+//
//| DON'T EDIT BELOW THIS LINE!!! |//
//+-------------------------------------------------------+//
//Defining this function for later. Thanks to an anon on php.net for this!
//This will allow me to get the constants with the $prefix prefix. In this
//case all the chapters will be defined with "CHAPTER_x" so using the prefix
//'CHAPTER' in the function will return all the chapter constants ONLY.
function returnConstants ($prefix) {
foreach (get_defined_constants() as $key=>$value) {
if (substr($key,0,strlen($prefix))==$prefix) {
$dump[$key] = $value;
}
}
if(empty($dump)) {
return "Error: No Constants found with prefix '" . $prefix . "'";
}
else {
return $dump;
}
}
//---------------------------------------------------------//
$archiveDir = "public_html/archive";
$files = array_diff(scandir($archiveDir), array("..", "."));
//This SHOULD populate the array in order, for example:
//$files[0]='20131125.png', $files[1]='20131126.png', etc.
//---------------------------------------------------------//
$pages = array();
foreach ($files as $file) {
//This parses through the files and takes only .png files to put in $pages.
$parts = pathinfo($file);
if ($parts['extension'] == "png") {
$pages[] = $file;
}
unset($parts);
}
//Now that we have our pages, let's assign the links to them.
$totalPages = count($pages);
$pageNums = array();
foreach ($pages as $page) {
//This will be used to populate the page numbers for the links.
//e.g. "<a href='archive.php?p=$pageNum'></a>"
for($i=1; $i<=$totalPages; $i++) {
$pageNums[] = $i;
}
//This SHOULD set the $pageNum array to be something like:
//$pageNum[0] = 1, $pageNum[1] = 2, etc.
}
$linkText = array();
$archiveLinks = array();
foreach ($pageNums as $pageNum) {
//This is going to cycle through each page number and
//check how to display them.
if ($totalPages < 10) {
$linkText[] = $pageNum;
}
elseif ($totalPages < 100) {
$linkText[] = "0" . $pageNum;
}
else {
$linkText[] = "00" . $pageNum;
}
}
//So, now we have the page numbers and the link text.
//Let's plug everything into a link array.
for ($i=0; $i<$totalPages; $i++) {
$archiveLinks[] = "<a href='archive.php?p=" . $pageNums[$i] . "'>" . $linkText[$i] . " " . "</a>";
//Should output: <a href= 'archive.php?p=1'>01 </a>
//as an example, of course.
}
//And now for the fun part. Let's take the links and display them.
//Making sure to automatically assign the pages to their respective chapters!
//I've tested the below using given values (instead of fetching stuff)
//and it worked fine. So I doubt this is causing it, but I kept it just in case.
$rawChapters = returnConstants('CHAPTER');
$chapters = array_values($rawChapters);
$totalChapters = count($chapters);
$chapterTitles = array();
for ($i=1; $i<=$totalChapters; $i++) {
$chapterTitles[] = "<h4>Chapter " . $i . ":</h4><p>";
echo $chapterTitles[($i-1)];
for ($j=1; $j<=$chapters[($i-1)]; $j++) {
echo array_shift($archiveLinks[($j-1)]);
}
echo "</p>"; //added to test if this was causing the deletion
}
?>
What is causing the remainder of the document to vanish like that? EDIT: Two silly syntax errors were causing this, and have been fixed in the above code! However, the links aren't being displayed at all? Please note that I am pretty new to php and I do not expect my code to be the most efficient (I just want the darn thing to work!).
Addendum: if you deem to rewrite the code (instead of simply fixing error(s)) to be the preferred course of action, please do explain what the code is doing, as I do not like using code I do not understand. Thanks!
Without having access to any of the rest of the code or data-structures I can see 2 syntax errors...
Line 45:
foreach ($pages = $page) {
Should be:
foreach ($pages as $page) {
Line 88:
echo array_shift($archiveLinks[($j-1)];
Is missing a bracket:
echo array_shift($archiveLinks[($j-1)]);
Important...
In order to ensure that you can find these kinds of errors yourself, you need to ensure that the error reporting is switched on to a level that means these get shown to you, or learn where your logs are and how to read them.
See the documentation on php.net here:
http://php.net/manual/en/function.error-reporting.php
IMO all development servers should have the highest level of error reporting switched on by default so that you never miss an error, warning or notice. It just makes your job a whole lot easier.
Documentation on setting up at runtime can be found here:
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
There is an error in scripts/autodir.php this file. Everything up to that point works fine, so this is where the problem starts.
Also you mostlikely have errors hidden as Chen Asraf mentioned, so turn on the errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Just put that at the top of the php file.
I have a simple image-looping script that changes the src of an image.
function cycleNext()
{
++imgIndex;
if(imgIndex>imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't know how to fetch this information. I imagine it's pretty simple, though.
How can I use PHP to supply this script with the number of images in the folder?
<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>
Repeat the 2nd line for each extension you wish to count.
function cycleNext()
{
++imgIndex;
if (imgIndex > <?php echo $filecount;?>)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
That should do it.
EDIT:
function cycleNext(imgCount)
{
++imgIndex;
if (imgIndex > imgCount)
{
imgIndex = 1;
}
setImgSrc(imgIndex);
}
Then when you call cycleNext, call it with the variable.
cycleNext(<?php echo $filecount; ?>);
if the .js file is a separate file. then you can do this:
change the .js for a .php
then you can add <?php ?> tags just like you do in your .php files.
just don't forget to add the header in the code, indicating that the file is a javascript file. like that:
<?php header("Content-type: text/javascript"); ?>
and you will call the file with it's actual name src="file.php"
You can do it in three ways:
Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
include the javascript to the <head> tag of your page
echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:
<script type="text/javascript">
var imgCount = <?php echo $imagecount ?>
</script>;
During the generation of the HTML code, simply insert a <script> line, for instance
echo '<script type="text/javascript">';
echo 'var imgCount=' . $NumberOfImages . ';';
echo '</script>';
Just ensure that line is provided before cycleNext() is called (or imgCount is used).