adding a new function has created an undefined variable - php

I'm working on adapting a bit of PHP for a styleguide generator to pull in the .scss file and display it, but at line 56 I'm getting a notice: undefined variable.
The line in question is
$sass = 'sass'.strstr($path, "/");
and the whole functions.php is
<?php
// Display title of each markup samples as a list item
function listMarkupAsListItems ($type) {
$files = array();
$handle=opendir('markup/'.$type);
while (false !== ($file = readdir($handle))):
if(stristr($file,'.html')):
$files[] = $file;
endif;
endwhile;
sort($files);
foreach ($files as $file):
$filename = preg_replace("/\.html$/i", "", $file);
$title = preg_replace("/\-/i", " ", $filename);
$title = ucwords($title);
echo '<li>'.$title.'</li>';
endforeach;
}
// Display markup view and source
function showMarkup($type) {
$files = array();
$handle=opendir('markup/'.$type);
while (false !== ($file = readdir($handle))):
if(stristr($file,'.html')):
$files[] = $file;
endif;
endwhile;
sort($files);
foreach ($files as $file):
$filename = preg_replace("/\.html$/i", "", $file);
$title = preg_replace("/\-/i", " ", $filename);
$documentation = 'doc/'.$type.'/'.$file;
echo '<div class="sg-markup sg-section">';
echo '<div class="sg-display">';
echo '<h2 id="sg-'.$filename.'" class="sg-h2">'.$title.'</h2>';
if (file_exists($documentation)) {
echo '<div class="sg-doc">';
include($documentation);
echo '</div>';
}
include('markup/'.$type.'/'.$file);
echo '</div>';
echo '<div class="sg-markup-controls"><button type="button" class="sg-btn sg-btn--source">View Source</button> <a class="sg-btn--top" href="#top">Back to Top</a></div>';
echo '<div class="sg-source sg-animated">';
echo '<button type="button" class="sg-btn sg-btn--select">Copy Source</button>';
echo '<pre class="line-numbers"><code class="language-markup">';
echo htmlspecialchars(file_get_contents('markup/'.$type.'/'.$file));
echo '</code></pre>';
echo '</div>';
echo '</div>';
$sass = 'sass'.strstr($path, "/");
$sass = str_replace(".html",".scss",$sass);
if (file_exists($sass)) {
echo '<div class="sg-sub-section">';
echo '<div class="sg-markup-controls">';
echo '<button type="button" class="sg-btn sg-btn--source">View Sass</button>';
echo '</div>';
echo '<div class="sg-source">';
echo '<button type="button" class="sg-btn sg-btn--select">Copy Sass</button>';
echo '<pre class="line-numbers"><code class="language-scss">';
echo file_get_contents($sass);
echo '</code></pre>';
echo '</div>';
echo '</div>';
}
endforeach;
}
?>
I'm sure this is some simple PHP issue I'm getting wrong. Any help would be greatly appreciated.
Update:
The code for the $sass was taken from another snippet, looking at two comments (thank you) it seems the $path variable is the problem? I guess I need to define that to the folder path of where I'm looking?

You need to define $path first. You could do that elsewhere and call in the $path variable to your function with a line at the beginning of the function like:
function showMarkup($type) {
global $path;
// ... etc.
Or define a default for it when you define the function:
function showMarkup($type, $path="my-default-path/") {

Related

Creating pages from a csv file

I've created a page that grabs data from a CSV (http://liamjken.com/aim-parse/aim-websites-new.csv) and displays it on this page http://www.liamjken.com/aim-parse/parse.php?17
?17 references the row in the csv file. so if I change that to ?10 it pulls the info from a different row.
What I would like to do instead of using the row number is use the $vin_num value. so if I put ?1FMCU9GD9KUC40413 at the end of the URL it would display the row that contains that Number.
here is the code I have currently, its basically cobbled together from multiple different trends I found so if you notice other potential problems id be happy to hear about them.
<?php
$qstring = $_SERVER['QUERY_STRING'];
$row = $qstring; // The row that will be returned.
$data = get_row('aim-websites-new.csv', $row);
'<pre>'.print_r($data).'</pre>';
function get_row($csv, $row) {
$handle = fopen("$csv", 'r');
$counter = 0;
$result = '';
while ( ($data = fgetcsv($handle)) !== FALSE ) {
$counter++;
if ( $row == $counter ) {
$vin_num="$data[12]";
$model="$data[10]";
$make="$data[9]";
$year="$data[8]";
ob_start();
?>
<h1>VIN: <?php echo $vin_num; ?></h1>
<h1>Year: <?php echo $year; ?></h1>
<h1>Make: <?php echo $make; ?></h1>
<h1>Model: <?php echo $model; ?></h1>
<?php
$output = ob_get_clean();
ob_flush();
return $output;
}
}
}
?>
<?php
function extract_data($file)
{
$raw = file($file); // file() puts each line of file as string in array
$keys = str_getcsv(array_shift($raw)); // extract the first line and convert into an array
// Look through the rest of the lines and combine them with the header
$data = [];
foreach ($raw as $line) {
$row = str_getcsv($line);
$data[] = array_combine($keys, $row);
}
return $data;
}
function get_record($data, $vin)
{
foreach ($data as $record) {
if ($record['VIN'] === $vin)
return $record;
}
return null;
}
$data = extract_data('aim-websites-new.csv');
$vin = $_SERVER['QUERY_STRING'];
if (empty($vin)) {
echo '<h1>No VIN provided</h1>';
exit;
}
$record = get_record($data, $vin);
if ($record === null) {
echo '<h1>No record found</h1>';
exit;
}
echo '<h1>' . $record['VIN'] . '</h1>';
echo '<h1>' . $record['Year'] . '</h1>';
echo '<h1>' . $record['Make'] . '</h1>';
echo '<h1>' . $record['Model'] . '</h1>';
echo '<pre>' . print_r($record, true) . '</pre>';
If you don't trust that the records will have valid VINs, you can use the code posted here to validate: How to validate a VIN number?

DIV not closing in foreach

I'm having this problem. I wrote this PHP to output the content of sub-folders in a specified folder. The code works great, it shows all the images in the sub-folders. The problem that I'm having is that on echo $underfolder, it prints out just the first sub-folder without closing the DIV class=image.
What's wrong? I'm going crazy
 <div class="folders">
<?php
global $current_user;
$current_user = wp_get_current_user();
$current_user_nambre = $current_user->user_login;
$subFolders = glob("wp-content/uploads/$current_user_nambre/*", GLOB_ONLYDIR);
foreach ($subFolders as $value) {
echo "<div class='products'>";
$content = scandir($value);
echo $value;
foreach ($content as $value) {
echo "<div class='image;' style=\"display:inline-block;\">";
echo "<a href='/$underfolder/$value'>download</a>";
echo "<img src='/$underfolder/$value' height=\"100\height=\"100\" width=\"100\>";
echo '</div>';
}
echo '</div>';
}
?>
</div>
Check your quotes in img tag and $value you reassign $value. Set different name in second foreach()
<div class="folders">
<?php
global $current_user;
$current_user = wp_get_current_user();
$current_user_nambre = $current_user->user_login;
$sottocartelle = glob( "wp-content/uploads/$current_user_nambre/*", GLOB_ONLYDIR );
foreach ( $sottocartelle as $value ) {
echo "<div class='products'>";
$contenuto = scandir( $value );
echo $value;
foreach ( $contenuto as $value1 ) {
echo '<div class="image;" style="display:inline-block;">';
echo "<a href='/$value/$value1'>download</a>";
echo "<img src='/$value/$value1' height='100' height='100' width='100'>";
echo '</div>';
}
echo '</div>';
}
?>
</div>
This code should work fine.

PHP how to echo an image and text file from each subfolders as a table

I'm totally new to PHP and not an Advanced web developper but I really like to learn. My problem is the following: I want to make a projects page which would show every projects located in subfolders. In clear, that page would include a thumbnail and a two lines description (in a text file) from each folder to display it as a table and on which a user could click to reach the right project page. Here is the code I am presently stuck with:
<?php
$dir = "*/";
$images = glob($dir."main.jpg" );
$myFiles = glob($dir."description.txt");
$fh = fopen($myFiles, 'r');
$theData = fread($fh, 5);
fclose($fh);
foreach( $images as $image ):
echo '<div class="projects"><div class="projects-img-container">';
echo" <img class='projet-img' src='". '/projects/' . $image . "'/>";
echo '</div><div class="project-description">';
foreach( $myfiles as $myfile ):
echo $theData;
endforeach;
echo '</div>';
endforeach;
echo '</div>';
?>
description.txt as follow:
Gold Collection
Deck 1
Any help would be appreciated, as for the moment the images are showing fine, but no text is displayed. Then would also come the link to the respective folder...
Should look something like this image:
http://i.stack.imgur.com/yjwX7.jpg
Thank you for your help!
Check out the comments & code within the modified script below for suggestions along with the ways I've implemented those suggestions...
<?php
$dir = "*/";
$images = glob($dir."main.jpg" );
/* This doesn't work because fopen() can't take an array
* $myFiles = glob($dir."description.txt");
* $fh = fopen($myFiles, 'r');
* $theData = fread($fh, 5);
* fclose($fh);
*/
echo '<div class="projects">'; // I think you meant to put this outside the loop
foreach( $images as $image ) {
echo '<div class="projects-img-container">';
echo" <img class='projet-img' src='". '/projects/' . $image . "'/>";
echo '</div><div class="project-description">';
$dn = dirname($image);
# $myFiles = glob($dn."/description.txt"); // don't think we need to glob() this
$fh = fopen($dn."/description.txt", 'r');
$theData = fread($fh, 5);
echo $theData;
fclose($fh);
/* Not sure it makes sense to loop $myfiles - only 1 description.txt can
* exist in any one directory, right?
* foreach( $myfiles as $myfile ):
* echo $theData;
*}
*/
# Whatever you want to do with the directory link would be done with $dn here.
echo '</div>';
}
echo '</div>';
?>
After review this seems to work well for me. thanks to you Peter!
<?php
$dir = "*/";
$images = glob($dir."main.jpg" );
echo '<div class="projects-container">';
foreach( $images as $image ) {
$dn = dirname($image);
echo '<div class="projects">';
echo '<div class="projects-img-container">';
echo" <a href='".$dn."'><img class='projet-img' src='". '/projects/' . $image . "'/></a>";
echo '</div><div class="project-description">';
$fh = fopen($dn."/description.txt", 'r');
$theData = fread($fh, 5);
echo" <a href='".$dn."'>".$theData."</a>";
fclose($fh);
echo '</div>';
echo '<div style="clear: both"></div>';
echo "</a>";
echo '</div>';
}
echo '</div>';
?>

foreach inside foreach issue

I have two directories : one has images and the other has ZIP files.
The files in both directories have the same names e.g : 1.zip , 1.png
I scanned each folder like this :
$images = 'screenshots/';
$scanned_images = array_diff(scandir($images), array('..', '.'));
$zips = 'download/';
$scanned_zips = array_diff(scandir($zips), array('..', '.'));
then :
foreach ($scanned_images as $value)
{
echo '<div class="portfolioItem">';
echo '<a href="screenshots/'.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="screenshots/'.$value.'" class="portfolio-image" alt="'.$value.'" /> </a>';
foreach ($scanned_zips as $val)
{
echo '<div class="portfolioDescription">';
echo'<h4>Download:'.$val.'</h4>';
echo'<p>Click here to download</p>';
echo'</div></div>';
}
}
This does not work. Each image in first directory will have the whole zip files of second directory in its description!
I have also tried to combine the two arrays into one array and use foreach ($result as list ($a, $b)) but as list always gives an error.
How to overcome this ?
no need to have nested foreach.
use this:
<?php
$images = 'screenshots/';
$scanned_images = array_diff(scandir($images), array('..', '.'));
$zips = 'download/';
$scanned_zips = array_diff(scandir($zips), array('..', '.'));
foreach ($scanned_images as $value)
{
$name = substr($value, 0, strrpos($value, '.'));
$pos = array_search($name.'.zip', $scanned_zips);
if($pos != null){
echo '<div class="portfolioItem">';
echo '<a href="'.$images.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="'.$images.$value.'" class="portfolio-image" alt="'.$value.'" />';
echo '</a>';
echo '<div class="portfolioDescription">';
echo '<h4>Download:'.$scanned_zips[$pos].'</h4>';
echo '<p>Click here to download</p>';
echo '</div>';
echo '</div>';
}
}
Add a break; statement at the end of your inner foreach loop and that should fix it. You have two foreach loops and hence the downloads are listed multiple times. To fix this issue,
Change your code to:
<?php
foreach ($scanned_images as $value)
{
echo '<div class="portfolioItem">';
echo '<a href="screenshots/'.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="screenshots/'.$value.'" class="portfolio-image" alt="'.$value.'" /> </a>';
foreach ($scanned_zips as $val)
{
echo '<div class="portfolioDescription">';
echo'<h4>Download:'.$val.'</h4>';
echo'<p>Click here to download</p>';
echo'</div></div>';
break; //exiting
}
}
?>
One way is to hash your files by name without extension. Then use same key to retrieve image data and zip data. Example:
$scanned_images = array('1.png', '2.png');
$scanned_zips = array('1.zip', '2.zip');
//Should be like that after hashing
$scanned_images = array('1' => '1.png', '2' => '2.png');
$scanned_zips = array('1' => '1.zip', '2' => '2.zip');
So the code could be:
function get_file_name($path) {
$name = basename($path);
$name = substr($name, 0, strrpos($name, '.'));
return $name;
}
function hash_files_by_name($items) {
$hashed = array();
foreach($items as $item) {
$name = get_file_name($item);
$hashed[$name] = $item;
}
return $hashed;
}
$scanned_images = array('1.png', '2.png'); // get images directory filesnames
$scanned_zips = array('1.zip', '2.zip'); // get zips directory filenames.
$imgs = hash_files_by_name($scanned_images);
$zips = hash_files_by_name($scanned_zips);
foreach ($imgs as $key=>$value)
{
echo '<div class="portfolioItem">';
echo '<a href="screenshots/'.$value.'" class="zoom img" title="'.$value.'" rel="portfolio">';
echo '<img src="screenshots/'.$value.'" class="portfolio-image" alt="'.$value.'" /> </a>';
if(isset($zips[$key])) {
echo '<div class="portfolioDescription">';
echo'<h4>Download:'.$zips[$key].'</h4>';
echo'<p>Click here to download</p>';
echo'</div></div>';
}
}

foreach in foreach only echos last item?

I am trying to extract download links from a site. However i only get the last item in my array.
<?php
require 'functions/simple_html_dom.php';
$html = new simple_html_dom();
$html->load_file('http://www.nyaa.eu/?page=torrents&user=64513');
$page_title = $html->find('title',0);
?>
Title:<?php echo $page_title->plaintext; ?><br><br>
Links:<br>
<?php
foreach($html->find('td.tlistdownload a') as $links){
$dllinks[] = $links->href;
}
foreach($html->find('td.tlistname a') as $names){
echo '<a href="';
foreach ($dllinks as $value)
{
echo $value;
}
echo '">' . $names->innertext . '</a><br>';
}
foreach ($dllinks as $value)
{
echo $value . '<br>';
}
?>
When I use var_dump it shows all the download links in my array. But for some strange reason it only shows the last item in the second foreach loop.
EDIT:
Sorry it was supposed to be like this
<?php
require 'functions/simple_html_dom.php';
$html = new simple_html_dom();
$html->load_file('http://www.nyaa.eu/?page=torrents&user=64513');
$page_title = $html->find('title',0);
?>
Title:<?php echo $page_title->plaintext; ?><br><br>
Links:<br>
<?php
foreach($html->find('td.tlistdownload a') as $links){
$dllinks[] = $links->href;
}
foreach($html->find('td.tlistname a') as $names){
echo '<a href="';
foreach ($dllinks as $value)
{
echo $value;
}
echo '">' . $names->innertext . '</a><br>';
}
?>
I kept this verbose so its easier to see whats going on... Basically, grab each row.. Find the name and the link from the row. spit it out..
<?php
require 'functions/simple_html_dom.php';
$html = new simple_html_dom();
$html->load_file('http://www.nyaa.eu/?page=torrents&user=64513');
$page_title = $html->find('title',0);
?>
Title:<?php echo $page_title->plaintext; ?><br><br>
Links:<br>
<?php
foreach($html->find('.tlistrow') as $row){
$link_nodes = $row->find('td.tlistdownload a');
$name_nodes = $row->find('td.tlistname a');
if (count($link_nodes) > 0 && count($name_nodes) > 0) {
$link = $link_nodes[0]->href;
$name = htmlentities($name_nodes[0]->innertext);
echo "<a href='{$link}'>{$name}</a>\n";
}
}

Categories