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>';
Related
I get images from a specific url. with this script im able to display them on my website without any problems. the website i get the images from has more than one (about 200) pages that i need the images from.
I dont want to copy the block of PHP code manually and fill in the page number every time from 1 to 200. Is it possible to do it in one block?
Like: $html = file_get_html('http://example.com/page/1...to...200');
<?php
require_once('simple_html_dom.php');
$html = file_get_html('http://example.com/page/1');
foreach($html->find('img') as $element) {
echo '<img src="'.$element->src.'"/>';
}
$html = file_get_html('http://example.com/page/2');
foreach($html->find('img') as $element) {
echo '<img src="'.$element->src.'"/>';
}
$html = file_get_html('http://example.com/page/3');
foreach($html->find('img') as $element) {
echo '<img src="'.$element->src.'"/>';
}
?>
You can use a for loop like so:
require_once('simple_html_dom.php');
for($i = 1; $i <= 200; $i++){
$html = file_get_html('http://example.com/page/'.$i);
foreach($html->find('img') as $element) {
echo '<img src="'.$element->src.'"/>';
}
}
So now you have one block of code, that will execute 200 times.
It changes the page number by appending the value of $i to the url, and every time the loop completes a round, the value of $i becomes $i + 1.
if you wish to start on a higher page number, you can just change the value of $i = 1 to $i = 2 or any other number, and you can change the 200 to whatever the max is for your case.
There are many good solutions, on of them: try to make a loop from 1 to 200
for($i = 1; $i <= 200; $i++){
$html = file_get_html('http://example.com/page/'.$i);
foreach($html->find('img') as $element) {
echo '<img src="'.$element->src.'"/>';
}
}
<?php
function SendHtml($httpline) {
$html = file_get_html($httpline);
foreach($html->find('img') as $element) {
echo '<img src="'.$element->src.'"/>';
}
}
for ($x = 1; $x <= 200; $x++) {
$httpline="http://example.com/page/";
$httpline.=$x;
SendHtml($httpline);
}
?>
Just loop. Create a sending function and loop to make the calls.
I recommend you to read all php docu in https://www.w3schools.com/php/default.asp
First, store them in a database. You can(/should) download the images to your own server, or also store the uri to the image. You can use code like FMashiro's for that, or something similar, but opening 200 pages and parsing their HTML takes forever. Every pageview.
And then you simply use the LIMIT functionallity in queries to create pages yourself.
I recommend this method anyways, as this will be MUCH faster than parsing html every time someone opens this page. And you'll have sorting options and other pro's a database gives you.
This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>
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 this issue with my jquery code:
<?php
//I oppen a text document, read the text inside of it and write it inside my html page.
//When someone clicks on a line, I want to take that very same line and send it via select(String) function.
$handle = fopen($_POST['lien'], 'r');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
echo "<div onclick='select(\" ".$buffer." \");'>".$buffer."</div><br/>";
//It works when I put a simple string within the select param:
//echo "<div onclick='select(\" text \");'>".$buffer."</div><br/>";
}
fclose($handle);
}
?>
The jquery code :
function select(text){
alert(text);
//$("#selected").html();
}
where do you guys think is the problem ?
Thanks :)
Maybe Your $buffer contains some double-quotes, which then interfere with surrounding double-quotes. Look at produced HTML code if this is the case, maybe You'll see something like this:
<div onclick='select("He said: "Freeze!"")'>
... which Javascript can't parse correctly. If this is the case, consider using:
echo "<div onclick='select(".json_encode($buffer).")'>";
Try to change line:
echo "<div onclick='select(\" ".$buffer." \");'>".$buffer."</div><br/>";
to
echo "<div onclick='select(\" ".rtrim($buffer)." \");'>".$buffer."</div><br/>";
or to:
echo "<div onclick='select($(this).text());'>".$buffer."</div><br/>";
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.