Latency problem on FF and safari and IE - php

so i've build a function to scan a dir based on a $_GET var, the code:
$dir="img/".$_GET["gal"];
$a=scandir($dir);
$b=array_slice($a,2);
for($i=1,$j=1;$i,$j<=count($b);$i++,$j++){
$marginRight=($i==6||$i==12||$i==18||$i==24||$i==30||$i==36)?"margin-right: 0":"margin-right: 13px";
if($i<10 && $j<10)
echo '<div class="GalThumbs" style="'.$marginRight.'"><img src="'.$dir.'/'.$_GET["gal"].'-0'.$i.'.jpg"/></div>';
else{
echo '<div class="GalThumbs" style="'.$marginRight.'"><img src="'.$dir.'/'.$_GET["gal"].'-'.$i.'.jpg"/></div>';
}
/* if($i==11)
break; */
}
if there are more than ten images to scan a latency occurs(redraw of the browser slowish)
i discover this using the commented:
if($i==11)
break;
if it's :
if($i==10)
break;
there will be no latency. don't understand what's going on here..

Let's take a look at your code, I think you are somehow lost in all that code and what it does. With a little bit of clean-up you should be able to debug your latency issue far easier.
Let's start with the for-loop:
for($i=1,$j=1;$i,$j<=count($b);$i++,$j++)
Both iterator variables are set in parallel. I'm sure you have thought about something when you wrote it, but this makes no sense. Try to reduce problems if you're unsure how to go on.
One variable does the job. Same here:
if($i<10 && $j<10)
And then I stumbled over this:
$marginRight=($i==6||$i==12||$i==18||$i==24||$i==30||$i==36)?"margin-right: 0":"margin-right: 13px";
You are actually looking for modulo: Get the remainder of $i divided by 6.
The if/else blocks both contain the same code. There is no need to use it at all.
Then I assume for debugging you want to quit the for-loop with break.
Next to that your code can benefit from indentation.
And the directory is actually only read to get the number of files, so the code can be reduced to get the count of files.
Let's try:
$gal = $_GET["gal"]; // FIXME sanitize the input
$dir = sprintf('img/%s', $gal);
$max = count(scandir($dir))-2;
for($i=1; $i<=$max; $i++)
{
$marginRight = ($i % 6 ? '13px' : '0');
$style = sprintf('margin-right: %s', $marginRight);
$src = sprintf('%s/%s-0%d.jpg', $dir, $gal, $i);
echo '<div class="GalThumbs" style="', htmlspecialchars($style), '">',
'<a href="', htmlspecialchars($src), '" rel="example3">',
'<img src="', htmlspecialchars($src),'"/>',
'</a>',
'</div>'
;
// FIXME debug
/* if($i==11) break; */
}

Related

How do I insert html code into a php regex?

So I am currently in the middle of making a forums software. Something that I wanted for that forums software was a custom template engine. For the most part I have created the template engine, but I am having a small issue with the regex that I use for my IF, ELSEIF, and FOREACH statements.
The issue that I am having is that when I put a chunk of html code in to my regex, nothing will work. Here is an example: https://regex101.com/r/jlawz3/1.
Here is the PHP code that checks for the regex.
$isMatchedAgain = preg_match_all('/{IF:(.*?)}[\s]*?(.*?)[\s]*?{ELSE}[\s]*?(.*?)[\s]*?{ENDIF}/', $this->template, $elseifmatches);
for ($i = 0; $i < count($elseifmatches[0]); $i++) {
$condition = $elseifmatches[1][$i];
$trueval = $elseifmatches[2][$i];
$falseval = (isset($elseifmatches[3][$i])) ? $elseifmatches[3][$i] : false;
$res = eval('return ('.$condition.');');
if ($res===true) {
$this->template = str_replace($elseifmatches[0][$i],$trueval,$this->template);
} else {
$this->template = str_replace($elseifmatches[0][$i],$falseval,$this->template);
}
}
You can do it like this:
function render($content) {
$match = preg_match_all('/{IF:\((.*?)\)}(.*?){ELSE}(.*?)({ENDIF})/s', $content, $matches, PREG_OFFSET_CAPTURE);
if (!$match) {
return $content;
}
$beforeIf = substr($content, 0, $matches[0][0][1]);
$afterIf = substr($content, $matches[4][0][1] + strlen('{ENDIF}'));
$evalCondition = eval('return (' . $matches[1][0][0] . ');');
if ($evalCondition) {
$ifResult = $matches[2][0][0];
} else {
$ifResult = $matches[3][0][0];
}
return
$beforeIf .
$ifResult .
render($afterIf);
}
Working example.
This is a first step. This wont work for example if you have an if within an if.
Talking about mentioned security risk. Since we are using eval (nickname EVIL - for a reason). You should never ever ever process user-input through eval - or use eval at all - there is always a better solution.
For me it looks like you want to give users the ability to write "code" in their posts. If this is the case you can have a look at something like bbcode.
Whatever you do be sure to provide the desired functionality. Taking your example:
!isset($_SESSION['loggedin'])
You could do something like this:
{IS_LOGGED_IN}
Output whatever you want :)
{/IS_LOGGED_IN}
Your renderer would look specificly for this tag and act accordingly.
So after a bit of research, I have figured out that the issue I was facing could be solved by adding /ims to the end of my regex statement. So now my regex statement looks like:
/{IF:(.*?)}[\s]*?(.*?)[\s]*?{ELSE}[\s]*?(.*?)[\s]*?{ENDIF}/ims

PHPExcel conditionally formatting a range with a formula

I have the following code:
$vOffset = 2;
$offset = 6;
$formatRows = 100;
$formatColumns = 100;
//set conditional formatting in place
for($row=$vOffset;$i<$formatRows;$row++){
for($col=$offset+1;$col<$formatColumns;$col+3){
//prepare conditional styles
//if verbal is bigger
$conditionalStyle_RED = new PHPExcel\Style_Conditional();
$conditionalStyle_RED->setConditionType(PHPExcel\Style_Conditional::CONDITION_CELLIS);
$conditionalStyle_RED->addCondition(
"=" . $this->coordinates($col, $row) . " > " . $this->coordinates($col+1,$row)
);
$conditionalStyle_RED->getStyle()->getFont()->getColor()->setARGB(PHPExcel\Style_Color::COLOR_RED);
array_push($conditionalStyles, $conditionalStyle_RED);
$this->getActiveSheet()
->getStyle($this->coordinates($col, $row) . ':' . $this->coordinates($col+1, $row))
->setConditionalStyles($conditionalStyles);
}
}
Where I attempt to set a conditional style with the formula akin to:
=A1 > A3
It isn't yet working. Anyone know how to accomplish this?
Quite a late response, but I have been looking through the internet for a similar issue. Eventually I solved it. Incase people in the future might come across this problem I will note down a few things.
I have been struggling with the same kind of issue and I managed to solve it. What you want is to insert a formula into the conditional formatting. This sounds trickier than it actually is.
For your specific piece of code this should most likely work.
$vOffset = 2;
$offset = 6;
$formatRows = 100;
$formatColumns = 100;
//set conditional formatting in place
for($row=$vOffset;$i<$formatRows;$row++){
for($col=$offset+1;$col<$formatColumns;$col+3){
//prepare conditional styles
//if verbal is bigger
$conditionalStyle_RED = new PHPExcel\Style_Conditional();
$conditionalStyle_RED->setConditionType(PHPExcel\Style_Conditional::CONDITION_EXPRESSION);
$conditionalStyle_RED->setConditions(array("(" . $this->coordinates($col, $row) . " > " . $this->coordinates($col+1,$row) . ")"));
$conditionalStyle_RED->getStyle()->getFont()->getColor()->setARGB(PHPExcel\Style_Color::COLOR_RED);
array_push($conditionalStyles, $conditionalStyle_RED);
$this->getActiveSheet()
->getStyle($this->coordinates($col, $row) . ':' . $this->coordinates($col+1, $row))
->setConditionalStyles($conditionalStyles);
}
}
The "condition_expression" is used in order to place a formula inside a conditional format. As far as I was able to figure out the only way to implement a formula is by using the "setConditions". With this you can give an array of strings, with each string being a formula.
In your code this would result in the color of red when the first coordinate is bigger than the second one.
Now back to your code, I haven't tested it so you might want to tweak a few values, but this should at least push you towards the right direction. Good luck mate!

Line Break in PHP for-loop

There have been a bunch of questions like this already, but none of the answers seem to help me. I would like to have a line-break after each output from a loop. I am using double-quoted strings, like I read here, as well as using HTML (because I want the browser to recognize the line-breaks too) as I read here.
It does create a line-break, however only below the complete output.
I cannot manage to create a line-break between the outputs of the loop. Basically I get a block of text and then a linebreak.
Here is the loop I am using:
<?php
include_once('simple_html_dom.php');
$target_url = "http://www.buzzfeed.com/trending?country=en-us";
$html = new simple_html_dom();
$html->load_file($target_url);
$posts = $html->find('ul[class=list--numbered trending-posts trending-posts- now]');
$limit = 10;
$limit = count($posts) < $limit ? count($posts) : $limit;
for($i=0; $i < $limit; $i++){
$post = $posts[$i];
$post->find('div[class=trending-post-text]',0)->outertext = "";
echo strip_tags($post, '<p><a>') . "<br/>\n";
}
I've also tried "\r\n" and a bunch of variations, as well as the nl2br() function. I believe the PHP_EOL command is meant only for the command line, from what I've researched.
I'm an absolute beginner with PHP, so I am probably missing something simple, but I can't figure it out.
EDIT:
Here is what it prints:
http://globalsocialnews.com/crawler/test8.php
I also included the complete code in case that helps.
You can do line break using css implementation ...
like:
.rcorners1 a {
display: block;
margin-bottom: 10px;//for show extra margin between each line...
}
Edit: Use margin css attribute for extra margin...
please try implementing this...
Better Use
echo "</br>";

Iterating variables in PHP not working

I've done hours of research on this now, so I believe I'm not repeating, even though this seems like it would have a simple solution.
I have an HTML form sending values to PHP, where it takes the value, and sets them all to a variable. When I submit the values and load the PHP, it completely breaks as if there is a syntax problem, but I can't find anything obvious.
I'm setting the variables from POST like so:
$ital1=$_POST['checkbox1'];
$bold1=$_POST['checkbox2'];
$ital2=$_POST['checkbox3'];
$bold2=$_POST['checkbox4'];
I'm then using these variables with simplexml to write to an xml document for databasing. Here's a snippet of that:
$xml = simplexml_load_file('settings.xml');
function loops()
{
$italvar = (eval('return $' . "ital{$string}"));
$boldvar = (eval('return $' . "bold{$string}"));
$alertvar = (eval('return $' . "alerttitle{$string}"));
$pagevar = (eval('return $' . "page{$string}n"));
$colorvar = (eval('return $' . "colorset{$string}"));
$string = strval($i);
for($i=1; $i<21; $i++)
{
if($xml->settings->checkbox->"ital{$string}" == $empty && $italvar == "on")//ITAL1
{
$xml->settings->checkbox->"ital{$string}" = $italvar;
}
else if($italvar == $empty && $xml->settings->checkbox->"ital{$string}" == "on")
{
$xml->settings->checkbox->"ital{$string}" = $empty;
}
else
{
continue;
}
}
$xml->asXML('settings.xml');
This is just a piece of the function, but the rest is basically this repeated for different types of variables. I know the issue is within the loops function as when I delete loops(), the PHP at least loads some echos at the top of the doc.
I'm not sure what in here is breaking. I'm guessing it's the syntax with how I'm combining and iterating variables, which explains the title.
So my questions is this. How do I combine strings and variables correctly?
$italvar = (eval('return $' . "ital{$string}"));
$string = strval($i);
In this instance I want the end result to be $ital#, # being the current iteration of the forloop, so I can correctly write to xml the value of the set variable from $_POST as shown at the top.
"ital{$string}"
$string = strval($i);
And here I just want it to be a string such as ital1, then ital2, as that's what the nodes are called in the xml. I'm sure what I'm doing wrong is very obvious, but I'm very new to PHP and I can't seem to figure it out. Thank you very much in advance for any input!
You have a $_POST array. Use it.
for( $i=1; $i<=20; $i++) {
$ital = $_POST['checkbox'.($i*2-1)];
$bold = $_POST['checkbox'.($i*2)];
// now do stuff with `$bold` and `$italic`
}

Removing last comma from out in PHP that is going into a javascript image pre-load script

Hi I have a javascript pre-load script that incorporates a php command to pre-load uploaded images for a future onClick action. Anyway I am having trouble removing the LAST comma from the last image the pre-load script pulls from.
Here is the script:
<div style="display:hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
<?php
for ($i = 0; $i < 6; $i++) {
if (!empty($imgs[$i])) {
echo "'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500',";
}
}
?>
)
//--><!]]>
</script>
</div>
Anyway, I need to find out how to remove the last comma from the last image that is uploaded. Not sure how to do this. Please help me! BTW... the images don't have an extension since they are linking to a php image script that resizes them and places them into a watermark. Hope you guys can help me figure!
Think the other way! the comma could be at the start and then you remove it from the first one :)
if (!empty($imgs[$i])) {
$comma = $i == 0? '' : ',';
echo $comma."'http://www.samplegallery.com/upload/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500'";
}
This way doesn't matter if $i is equal to 5, 8 or 139871!
The easiest way to do it is using the php build in implode() function
<?php echo implode(',', $imgs); ?>
And if you want just the first 6 images, you can make an array like so
$imgs = array_slice($imgs, 0, 6);
So the whole thing must look like that:
preload(
<?php
$imgs = array_slice($imgs, 0, 6);
echo implode(',', $imgs);
?>
)
to remove the last comma from a string, just use this:
$string = rtrim($string, ",");
May I suggest a slightly different approach to your problem? Whenever you want to pass data to JavaScript, JSON is probably the thing you want to generate. json_encode() helps you with that. Your script could look like:
var urls = <?php echo json_encode(array_values($imgs)); ?>;
var images = [];
function preload(urls) {
for (var i = 0; i < urls.length; i++) {
var url = 'http://www.samplegallery.com/upload/image.php?img_source_url='
+ encodeURIComponent(urls[i])
+ '&img_resize_to=500';
images[i] = new Image();
images[i].src = url;
}
}
preload(urls);
please note that I've taken the liberty of adding missing semicolons and var declarations to keep your variables local. I have added the array_values() call to make sure you're passing a numerically indexed array, rather than an associative array that would have resulted in an object literal { ... } rather than an array literl [ ... ].
I have also moved the URL building to JavaScript, as I didn't see a reason to keep it in PHP. If you need this to be in PHP and want to avoid the "manual" loop, look into array_map().
Please also note that I'm running your URL fragment through encodeURIComponent() to properly escape whatever it is you're passing in.
A note on security: should your script at /upload/image.php accept arbitrary URLs (and or "local file resources"), consider white-listing the allowed domains and paths.
You could use a foreach...
<?PHP
if ($count = count($imgs)) {
foreach ($imgs as $key=>$img) {
echo "http://www.samplegallery.com/upload/image.php?img_source_url="
. $img . "&img_resize_to=500";
if ($key < $count-1) echo ",";
}
}
?>

Categories