PHP prints variable to screen and code stops running - php

I am trying to use Parsedown Extra with Parsedown (Have never used either before). I have the code $_GET the selected category (?cat=0) and set it's path & filename to a var. It $_GETs the page number just fine, however when I set the file var, it just prints to the screen and doesn't load my page.
//sets the page (category) number for use with array
//also sets the path to the category's pages
if (isset($_GET['cat'])) {
$catNum = $_GET['cat'];
$catPath = 'content/' . $pageList[$catNum]['path'];
echo '<div class="center pageNav">';
//lists out subpages of catagory
$pageAmt = count($pageList[$catNum]['pages']);
for ($i = 0; $i < $pageAmt; $i++) {
echo '' . $pageList[$catNum]['pages'][$i]['title'] . '';
};
echo '</div>';
//sets path & filename var to selected page: this is the part where it prints the var and doesn't run the rest. The var is pointing to the right file, I checked.
$page = $catPath . $pageList[$catNum]['mainPage'];
} else {
$page = 'content/home.md';
};
//parsedown
require 'parsedown/parsedown.php';
require 'parsedown/parsedownextra.php';
echo ParsedownExtra::instance()
->setBreaksEnabled(true)
->setMarkupEscaped(true)
->text($page);

you have a semi colon at the end of your if statement.
} else {
$page = 'content/home.md';
}; <--

Parsedown takes marked up text and renders it. In your example, you pass $page (which holds a string, a filename) to ->text($page). This parses the string as marked up text, and renders it. So, in your example you are seeing exactly what it is doing. If you are trying to run the text of the file through ->text, you need to load the file contents first and pass to Parsedown.

Related

How to properly paginate a foreach loop

I have a project I am working on, where I scan a directory and pull all of the images from the directory that will display the gallery images. Problem is, some galleries have 300+ images and this is causing a lag. I have looked around, but have not found a proper way of getting my code to paginate. Here is my code snippet of where I am running the foreach loop and getting each image source from the directory:
/** get the model's gallery
===================================================== **/
if(isset($_GET['count'])){
$photo_count = $_GET['count'];
}
if(isset($_GET['model_dir'])){
$model_dir = $_GET['model_dir'];
/** get the higres gallery images
===================================================== **/
$root_directory = $_SERVER['DOCUMENT_ROOT'];
$photo_directory = "{$root_directory}/members/content/model_gallery/{$model_dir}";
$gallery_list = scandir($photo_directory);
$gallery_list = array_diff($gallery_list, array('.', '..'));
foreach($gallery_list as $gallery){
echo "
<a href='{$index_url}join.php'>
<img alt='' src='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-image='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-description=''>
</a>
";
}
}
Any ideas on how I could go about paginating this code would be greatly appreciated.
I solved the problem myself. For those who had something tangible to respond with, thanks for your help. For others who just wanted to critique code, not knowing what the full purpose of the code is and whether or not it is the final piece of code, should probably keep your input to yourself.
/** get the model's gallery
===================================================== **/
if(isset($_GET['count'])){
$photo_count = mysqli_real_escape_string($_GET['count']);
}
if(isset($_GET['model_dir'])){
$model_dir = mysqli_real_escape_string($_GET['model_dir']);
/** get the higres gallery images
===================================================== **/
$root_directory = $_SERVER['DOCUMENT_ROOT'];
$photo_directory = "{$root_directory}/members/content/model_gallery/{$model_dir}";
$gallery_list = scandir($photo_directory);
$gallery_list = array_diff($gallery_list, array('.', '..'));
$photo_count = $photo_count;
$gallery_limit = 35;
$qty_pages = ceil($photo_count / $gallery_limit);
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; }
$start_from = $page * $gallery_limit - $gallery_limit ;
$gallery_list = array_slice($gallery_list,$start_from,$gallery_limit);
echo "<div id='gallery'>";
foreach($gallery_list as $gallery){
echo "
<a href='{$index_url}join.php'>
<img alt='' src='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-image='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
data-description=''>
</a>
";
}
echo "</div>";
echo "<div class='contain_pagination'>";
if($photo_count != 0){
echo "<nav class='contain_model_nav'><ul class='pagination'>";
for ($i = 1; $i <= $qty_pages; $i++){
echo "<li><a href='{$index_url}pages.php?id=gallerytour&model_dir={$model_dir}&count={$photo_count}&total={$total_photo_count}&page={$i}'></a>";
echo "</ul></nav>";
}
}
echo "</div>";
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $photo_count;?>,
itemsOnPage: <?php echo $gallery_limit;?>,
cssStyle: 'light-theme',
currentPage: <?php echo $page;?>,
hrefTextPrefix: '<?php echo $index_url ?>pages.php?id=gallerytour&model_dir=<?php echo $model_dir; ?>&count=<?php echo $photo_count; ?>&total=<?php echo $total_photo_count; ?>&page='
});
});
</script>
That is how I was able to paginate the foreach loop. I used nogad's idea for the array_slice function and then I used this open source for the pagination functionality:
http://flaviusmatis.github.io/simplePagination.js/
From there I made sure I had the $photo_count, which contains the count of all images within the directory and essentially what I would be paginating through.
I then set my $gallery_limit per page, which was 35. From there, I determined the number of pages with $qty_pages and dividing by the total $photo_count / and the set $gallery_limit
Next I check if the page isset if it is, then $page is == to the $_GET[page] else it is $page is == 1.
Next I get the $start_from value by multiplying $page * $gallery_limit and then subtracting by $gallery_limit
Next I make the value for the $gallery_list which is an array = to array_slice($gallery_list,$start_from,$gallery_limit);
So my parameters within the function are the entire array of src images for the $gallery_list, the integer of where to start from, and the integer of the $gallery_limit, in this case I set it to a default of 35.
Next I check if $photo_count is != to 0 and then run my normal for loop. the parameters within the url for the anchor will be dependent obviously on your site. One thing to note, is to simply add the &page={$i} parameter to the end of your url.
Finally you use the pagination plugin to write a small jQuery script for the pagination functionality. You should be able to decipher what I did within the jQuery script. I hope this helps someone out, because I have looked at other answers, and none delivered a satisfied result. They were almost as moronic as people like OlegLoginov replying to your question.

Pass links as variable in php and echo it on html

i must pass multiple link as variables on php
ex: www.mysite.com/dl.php?link=www.google.com&link2=yahoo.com&link3=youtube.com and so on, there is a variable number of links, and then i want to put them on and html page generated dynamically based on the number of links i inputed, in the example i did, the links was 3, so it must be:
<html><center>
Click to download part 1
Click to download part 2
Click to download part 3
</center></html>
can someone help me with this problem?
Parameters you append on your URL can be accessed through $_GET in php.
Take a look at this page: http://php.net/manual/en/reserved.variables.get.php
Update: If you have a variable number of get parameters and you want to get them all just use a foreach loop:
foreach($_GET as $key => $url) {
echo $url;
}
Instead of using different parameter names for all urls, use an array:
www.mysite.com/dl.php?link[]=www.google.com&link[]=yahoo.com&link[]=youtube.com
Then, in dl.php, $_GET['link'] is an array. You can iterate like this:
for ($i = 0; $i < count($_GET['link']); ++$i) {
echo 'Click to download part ' . ($i + 1) . '';
}
If URL = www.mysite.com/dl.php?link1=www.google.com&link2=yahoo.com&link3=youtube.com
<?php
for($i = 0; $i < count($_GET); $i++)
{
?>
Click to download part <?php echo ($i+1);?>
<?php
}
?>
If the only get value that is the URLs then just loop through...
foreach ($_GET as $url)
{
echo $url
}

Generating Javascript variables using php

I was trying to generate a Javascript varialbe using php. I am getting the desired result on the source page but it looks like that result is not being processed into the array. Is there any way of doing it using javascript? Here, I'm generating URLs for images that need to be displayed on my website carousel and though a for loop would save me the time of entering every url. The images are also number serially. Since I'm not well versed in javascript can you suggest me a javascript alternative?
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
You can do it using javascript only. No reason for using PHP here.
var leftrightslide = new Array()
var finalslide = ''; // this line is not really relevant to the question
for (var i = 0; i < 34; i++){
var j = i + 1;
leftrightslide[i] = '<img src="../images/'+ j +'.jpg" border="0">';
}
echo "leftrightslide[".$i."]='<img src=\"../images/".$j.".jpg\" border=0>';";
Here's a snippet of code that I use to move data from PHP To JS
if (isset($javascriptData)) {
echo "<script>";
foreach(array_keys($javascriptData) as $jsData) {
echo "var " . $jsData . " = " . json_encode($javascriptData[$jsData]) . ";\n";
}
echo "</script>";
}
I pass in $javascriptData to my view which is an array with the structure array('JS_VAR_NAME' => 'JS_VALUE')
You can then use those variables in any scripts you've added below that
Since your example code contains no script tags, or other HTML elements for that matter, one might assume that this PHP snippet is intended to generate some JavaScript source "file" external to the page in which it is being used.
If that is the case, consider that the following additional line may just fix it:
<?php header( 'Content-Type: text/javascript' ); ?>
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>

<div title="Can I somehow put PHP code in this attribute?"></div> or is there another route I can take?

I want to:
Read in text line from "textfile.txt".
'echo' that line to the page in a <div> element.
Read in a text line from "namefile.txt".
Make this line become some sort of pop-up-text for that <div> element.
My script:
<? PHP
$fhtext = fopen("textfile.txt","a+") or exit("Error 1");
$fhname = fopen("namefile.txt","a+") or exit("Error 2");
while(!feof($fhtext))
{
echo "<div title="HERE IS WHERE I AM STUCK">".fgets($fhtext)."<div/><br />";
}
Could I perhaps go:
echo "<div title="<? fgets($fhname) ?>".fgets($fhtext)."<div/><br />";
?
<?php
$fhtext = fopen("textfile.txt","a+") or exit("Error 1");
$fhname = fopen("namefile.txt","a+") or exit("Error 2");
while(!feof($fhtext) && !feof($fhname))
{
echo "<div title=\"", fgets($fhname), "\">", fgets($fhtext), "<div/><br />";
}
?>
I haven't used PHP in a long time, but this should work:
echo "<div title='" . fgets($fhname) ."'>" .fgets($fhtext). "<div/><br />";
Regarding:
Make this line become some sort of pop-up-text for that '' element.
If you mean 'popup' text, as in tooltips of the type you get when you hover over links/images, this is only available on some elements when their title attribute has been set, not DIVs.
As such you can either change the DIV to a A (link) element. Or use Javascript to detect a hover over the DIV and display a popup.
If you are sure both files have the same number of lines you could use the „file“-function of PHP. This will read the file into an array and you can loop over it with a for-loop:
<?php
$file1 = file('file1');
$file2 = file('file2');
for ($i = 0, $max = count($file1); $i < $max; $i++) {
echo $file1[$i].' '.$file2[$i];
}
Before you dump your fgets() data to the browser, you really ought to HTML encode it first. That will prevent accidental (or not so accidental) problems caused by HTML fragments that might be in your text files, or if the file name can be entered by the user (either as part of the URL or as part of a form).
As a rule of thumb, always HTML encode anything coming from a data source you don't control before spitting it out to the browser. That includes form fields, etc.

Get dynamically given div id's from document

I'm not a developer but I've been dabbling around with this for a while. Hope you can help
I have several div's with ID:s that are given to them dynamically through php. I have a function that is called through a checkbox which hides and shows the divs. What I want to do now is to get the div ids from the document and put them into the function.
I've kind of copied codes from different forums and it works if I'm hard coding the div names. Not sure what I'm doing now though, any help would be appreciated.
Here's what I have
Assigns id's to the divs:
$a .= "<div id='$go[media_caption]" . $i . "'>";
The function:
var editorial = [id^='editorial']);
function visiblox(arrDiv, hs) {
var disp = (hs) ? 'none' : 'block';
for(var x = 0; x < arrDiv.length; x++) {
document.getElementById(arrDiv[x]).style.display = disp;
}
}
function chk(what, item) {
if(item) {
visiblox(what, false);
} else {
visiblox(what, true);
}
}
Calls the function:
<input type='checkbox' onclick='chk(editorial, this.checked);' checked> Editorial</p>
Can you have your PHP output an array for your Javascript to use? As PHP outputs the IDs, it would also add them to a string that is in the syntax of a Javascript array. Something like this:
$a .= "<div id='$go[media_caption]" . $i . "'>";
$jsIDs .= "'$go[media_caption]',";
Then at the end of the file, just before you the PHP file closes the </body> and </html> tags, output the array as a script:
$jsIDs = substr($jsIDs, 0, strlen($jdIDs)-1); // strip off the last comma
$jsIDs = "<script type='text/javascript'>var idArr = [" . $jsIDs . "];</script>";
echo($jsIDs);
Then inside the javascript, you don't need to look up the IDs in the DOM. You can just use the array (in my example, I called it idArr).
UPDATE: Martin says the IDs output by PHP sometimes start with "editorial", some start with something else. To collect only the ones that start with "editorial", change the line above that starts with $jsIDs .= to these two lines:
if ( substr($go[media_caption], 9) == "editorial" )
$jsIDs .= "'$go[media_caption]',";
That should do the trick.

Categories