PHP Check filenames - php

I've created a simple PHP script which reads .txt files (1.txt, 2.txt etc which each contain dummy text: "Test~Test test test test test test") and produces a html output of each file's content with a little html formatting.
<html>
<head>
<style type="text/css">
body {background-color: #80B2FF; font-family: arial,sans-serif;}
.content {background-color: #ffffff; margin: 35px auto; max-width: 75%; padding: 35px;}
</style>
</head>
<body>
<?php
for ($number = 3; $number>=1; $number--){
$article = $number.".txt";
$data = file_get_contents($article); //read the file
$convert = explode("~", $data); //create array separate by new line
echo '<div class="content">'.$convert[0].'<br/><br/>'; //write value by index 0
echo $convert[1].'<br/><br/>'.'</div>'; //write value by index 0
}
?>
</body>
</html>
This currently works just fine. The problem is that if I was to create the file 4.txt, I would have to hard code the $number variable to 4.
I have tried to automatically initialise $number to the highest number.txt. I need help creating a loop which would use the file_exists() function to test if a file x.txt exists, if it does then increment x and test again. If it doesn't exist, the loop should instead break out and hence I could just say $number=x.
I hope this explanation is clear enough, thank you for your time.

Use glob(), your method is pretty bad:
http://php.net/glob or http://www.w3schools.com/Php/func_filesystem_glob.asp
What you want to do is $arr = glob("*.txt"); and then loop through that array.

Related

PHP How to Echo Across the Whole Page

I have created a skin switcher and it is working great, but the code is messy.
I save a cookie and then for some defined css classes, I append '-userDelectedColourFromTheCookie' to the end of the css class to apply it on the page.
So far, I am adding a short php line to the end of every instance of these classes in the html code and as I have said, it is working.
I would prefer to run the php code just once across the whole page and update all occurrences of an array containing the required classes to append the class as above.
I have this at the top of my page:
<?php
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], array("Blue","Red","Grey","Ochre","Mauve"))) echo $classList."-".strtolower($_COOKIE["Theme"]);
?>
<!DOCTYPE html>
... etc
I am defining an array of css classes, then reading the user colour from the cookie and appending it to the css class.
As and example, the default class might be 'theme-3' but of the user selects the blue skin, then this class becomes 'theme-3-blue' and so on.
But it's not working.
Any help would be appreciated.
Don't mess with the element class lists. Use CSS files to apply the colours you want.
Start with a basic CSS design file:
p {
margin-left:10px
font-size: 12pt;
}
h1 {
font-size: 24pt;
}
div {
margin: 10px;
padding 20px;
}
Then create CSS colour files with different colour selections:
blue.css
p {
color:blue;
}
h1 {
color: darkblue;
background-color: lightblue;
}
red.css
p {
color:red;
}
h1 {
color: maroon;
background-color: pink;
}
default.css
p {
color:black;
}
h1 {
color:white;
background-color:black;
}
Then load the colour theme you want
<?php
if (isset($_COOKIE['theme'] && in_array($_COOKIE['theme'], ['red','blue'])) {
$themeCSS = '<link rel="stylesheet" href="'.$_COOKIE['theme'].'.css">';
} else {
$themeCSS = '<link rel="stylesheet" href="default.css">';
}
Then echo $themeCSS in your <head> just like any other <head> element
** I've used standard HTML elements here to illustrate, but any CSS selectors should work.
I believe you want to change the class names inside the $classList variable by appending the selected color theme from the cookies.
You may use the array_map function to modify all elements of your $classList array.
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
$themeColor = $_COOKIE["Theme"]; // blue
$classList = array_map(function($val) use ($themeColor) { return $val.'-'.$themeColor; }, $classList);
Once you use the array_map function, all elements of the $classList array will be appended with the "-blue".
You can execute and see the output here
http://sandbox.onlinephpfunctions.com/code/6051282e00be1eb7bb7e6a086de20bbcfe9bcc9f
Several good ways to do it. It's a little more complicated with the array of classes but you should be able to adjust this if you need it (not sure why the syntax highlighting is wonky).
Use output buffering and replace at the end:
<?php
ob_start();
?>
<html>
<head></head>
<body>
<div class="theme-1"></div>
</body>
</html>
<?php
$themes = array("Blue","Red","Grey","Ochre","Mauve");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], $themes)) {
echo preg_replace('/class="(theme-[^"]+)"/', 'class="$1-' . $_COOKIE['Theme'] . '"', ob_get_clean());
}
With the array of classes, just do it the same way with output buffering but replace like so:
$replace = array_map(function($v) { return "{$v}-{$_COOKIE['Theme']}"; }, $classList);
echo str_replace($classList, $replace, ob_get_clean());

Render excel worksheet in html, using php, including rich text and hyperlinks

I'm looking for a way to read an excel file (xls format, but could probably use xlsx if necessary), and convert that file into an html table, preserving the rich text in the cells, cell borders, as well as the hyperlinks.
I've looked at https://code.google.com/p/php-excel-reader2/, which looks pretty good except some borders are missed and hyperlink targets have missing letter at end of filename (weird). I could probably debug these if I have to, but another problem with this is that this code base isn't supported any more. See http://www.steeplechasers.org/racecalendar-php-excel.php for example (spreadsheet is at http://www.steeplechasers.org/racecalendar.xls ).
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once 'excel_reader2.php';
$data = new Spreadsheet_Excel_Reader("racecalendar.xls");
?>
<html>
<head>
<style>
table.excel {
border-style:ridge;
border-width:1;
border-collapse:collapse;
font-family:sans-serif;
font-size:12px;
}
table.excel thead th, table.excel tbody th {
background:#CCCCCC;
border-style:ridge;
border-width:1;
text-align: center;
vertical-align:bottom;
}
table.excel tbody th {
text-align:center;
width:20px;
}
table.excel tbody td {
vertical-align:bottom;
}
table.excel tbody td {
padding: 0 3px;
border: 1px solid #EEEEEE;
}
</style>
</head>
<body>
<?php echo $data->dump(true,true); ?>
</body>
</html>
I also looked at https://github.com/PHPOffice/PHPExcel, which seems like it should be able to do this somehow, but using simple generateSheetData, borders rich text and hyperlinks don't seem to be preserved, and I'm having trouble groking the docs to see how to copy these attributes into html. See http://www.steeplechasers.org/racecalendar-PHPExcel.php for example (same input file).
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once 'PHPExcel/Classes/PHPExcel.php';
$filename = 'racecalendar.xls';
//$filetype = PHPExcel_IOFactory::identify($filename);
$reader = PHPExcel_IOFactory::createReaderForFile($filename);
$reader->setReadDataOnly(true);
$excel = $reader->load($filename);
$writer = PHPExcel_IOFactory::createWriter($excel, "HTML");
?>
<html>
<head>
</head>
<style>
<?php
echo $writer->generateStyles(false);
?>
</style>
<body>
<?php
echo $writer->generateSheetData();
?>
</body>
</html>
Convert HTML to Excel Rich Text and vice versa seems to indicate this isn't a feature of PHPExcel yet.
PHPExcel - Preserve rich text format on import didn't answer the question at all, as far as I could tell.
Is there another way to do this directly, or some way to do this with PHPExcel?
NOTE: I would actually like to iterate through the cells because I want to add a column to the html table as I go -- I used code to dump the whole spreadsheet as simple examples of the package behaviors, and this is as far as I have gotten in my investigation.
You're setting
$reader->setReadDataOnly(true);
when you read the spreadsheet file
This tells PHPExcel to ignore any formatting information in the spreadsheet file, and only to read the raw data in the cells. It means that all formatting (borders, number formatting styles, font colours, etc) will be ignored
The solution is not to set $reader->setReadDataOnly(true);
EDIT
As a quick hack for the URLs, you can modify /Classes/PHPExcel/Reader/Excel5.php
Lines 4564 and 4565
$url = self::_encodeUTF16(substr($recordData, $offset, $us - 2), false);
$url .= $hasText ? '#' : '';
change to
$url = self::_encodeUTF16(substr($recordData, $offset, $us - 2), false);
$nullOffset = strpos($url, 0x00);
if ($nullOffset)
$url = substr($url,0,$nullOffset);
$url .= $hasText ? '#' : '';
It fixes the URLs (note that php-excel-reader2 loses the last character of the URL) by testing for a null string terminator; and doesn't appear to have any adverse effects though it isn't adjusting the offset to allow for the adjustment. I need to check the BIFF specs and run a few more tests against both BIFF 5 and BIFF8 files with different link types before I'll commit anything back to the github repo)
Here is a link that might help: link.
Also, you can get the XML version of Excel (Excel is stored as XML I believe) and then just analyze the XML with PHP and put in a table on your website. Hope this helps.

PHP File renaming gone wrong

I have 12 css files in my system, and I rename them whenever users want to change style. I store current style in the database, and rename style.css to style$Color.css, renaming Style$Requestedcolor.css to style.css right after that. Here's the code:
if ($_POST['blue'] == "Blue")
{
if(file_exists('./css/styleblue.css'))
{
$old = './css/style.css';
$new = './css/style'.$Color.'.css';
$old1 = './css/styleblue.css';
$new1 = './css/style.css';
rename($old, $new);
rename($old1, $new1);
$newcolor = "blue";
$idnum = "1";
mysql_query("UPDATE company SET Color = '$newcolor' WHERE ID = '$idnum'");
}
}
Problem is, I sometimes (not always, finding it very hard to diagnose when and why) end up loosing a file, while system grabs a completely random .css file, renames it to style.css and writes the correct $newcolor to the database. Maybe the renaming goes too fast? Or should I grab for each of these ifs (there's 12) info for $Color value?
I have a sneaking suspicion that $Color occasionally doesn't get set before you start renaming files, are you verifying that your query completes and returns a result before running the block of code you've posted?
A better idea would be instead of constantly renaming the files you just change the filename in the <link> tag that you output on the page? That way you don't have to worry about the renaming process going sideways, or the new style.css not overwriting the old style.css in the client's cache.
I have a second sneaking suspicion that you're not making full use of CSS inheritance either, given that you're using a generic filename of 'style.css'. A somewhat better approach would be:
PHP/HTML
<? $color = 'blue'; ?>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="theme.<?= $color ?>.css">
</head>
style.css
Contains layout-related directives and default colors, eg:
body {
font-family: Sans;
background-color: grey;
}
#container {
width: 900px;
margin: 0px 20px;
background-color: white;
}
theme.blue.css
Contains just color-related directives to override those previously defined, eg:
body {
background-color: blue;
}
#container {
background-color: purple;
}

Replacing a CSS class using PHP?

I'm building the backend to a web application, where it is possible to change the design of a page. Once the user has setup the design the way they like it, they should be able to save it and the new design would be written to the specific file.
For this reason, I will need to replace all the characters between { and } after a certain string, which would be the name of the class.
So a very simple concept, say the following class was in a seperate file which I load as a view, style.php. I would need to go from:
from
<style>
.bonus {
bottom: 6px;
left: 247px;
}
</style>
to
<style>
.bonus {
bottom: 20px;
left: 450px;
}
</style>
Could someone recommend me on the best way to
a) find a string in a file,
b) when that is found, replace everything between two strings right after the first string.
Thank you.
I don't like the concept of the user making changes to the actual file very much. There are a lot of safer methods by which a user could create and maintain a custom template without them actually making changes to a PHP file.
What about storing the user's CSS in a field in a database? Then you'd simply need to do something like:
<?php
$css = getCSSByUserId($userId); //function runs query on DB to get user-specific CSS
/* $css = ".bonus {
bottom: 20px;
left: 450px;
}" */
?>
<style>
<?php echo $css; ?>
</style>
If you really want to edit the actual file, you'd do it something like this:
<?
$file = "/path/to/file.php";
//The user's replacement CSS
$replace = '.bonus {
bottom: 20px;
left: 450px;
}';
$str = file_get_contents($file);
$str = preg_replace('/\.bonus \{.*\}/U', $replace, $str);
$res = fopen($file, 'w');
fwrite($res, $str);
fclose($res);
?>
I checked the regex here http://www.quanetic.com/Regex and it works.

php array getting placeholder from database

i have this designing my table:
<style type="text/css">
tr {
background: <?php echo $colors[$status];?>;
color:white;
}
</style>
and
$status = $row[4];//value is 0
$colors = array("lime", "red");
The value in the database is 0.
The $status variable defines what color the table row should be. However the row is never lime. Is my array wrong or something else?
make sure the order is correct.
the order should be something like this:
<?php
$status = $row[4];//value is 0
$colors = array("lime", "red");
?>
<style type="text/css">
tr {
background: <?php echo $colors[$status];?>;
color:white;
}
</style>
your issue could be due to the fact that $colors was never declared before you started using it
If your css is defined in a separate file like "style.css", then your server won't know to parse php code inside. To do that you'll need to use the ".php" extension on your style file and include <?php header('content-type:css);?> at the top so the browser knows to interpret the css declarations.
Read more about using php in your css files here: http://www.barelyfitz.com/projects/csscolor/

Categories