(PHP) Creating HTML Files With Variable Content - php

I was trying to have a form create a page to display information. I was using fwrite() to create the page, but the way I set it up was very ugly and hard to manage, especially when I make the page more complex. I was wondering if there was a different way (I can't imagine that there isn't). Below is the code I have:
$student_name = $_POST["student_name"];
$text = "<!DOCTYPE html><head><title>" . $student_name . "'s Project</title></head><html><body><center><h1><u>" . $_POST["project_title"] . "</u></h1><i>By " . $student_name . "</i></center><br>" . $_POST["student_essay"] . "</body></html>";
$student_page = fopen('./projects/' . $file_count - 1 . '.html', 'w');
fwrite($student_page, $text);
Thanks!

You can do the following
Write a small blank html file and save it somewhere; e.g. "template.html"
1) in PHP you can read it with
$newcontent = file_get_contents("template.html");
2) Open a new file with fopen, write new content, close the file. Done.
if (!file_exists('newname.html')) {
$handle = fopen('path/to/new/file/newname.html', 'w+');
fwrite($handle, $newcontent);
fclose($handle);
}
However, what's the purpose of having a form create a new file everytime the form is submitted? Let me know what your objective is and I'll edit my answer accordingly.
You can see more answers and the original answer here: Create .html file with php

Related

How to grab specifc data from another website with PHP's fgetcsv and fopen

I'd like to be able to grab data such as list of articles from yahoo finance. At the moment I have a local hosted webpage that searched yahoo finance for stock symbols (E.g Nok), It then returns the opening price, current price, and how far up or down the price has gone.
What I'd like to do is actually grab related links that yahoo has on the page - These links have articles related to the share price...E.g https://au.finance.yahoo.com/q?s=nok&ql=1 Scroll down to headlines, I'd like to grab those links.
At the moment I'm working off a book (PHP Advanced for the world wide web, I know it's old but I found it laying around yesterday and it's quite interesting :) ) In the book it says 'It's important when accessing web pages to know exactly where the data is' - I would think by now there would be a way around this...Maybe the ability to search for links that have a particular keyword in it or something like that!
I'm wondering if theres a special trick I can use to grab particular bits of data on a webpage?? Like crawlers, they are able to grab links that are related to something.
It would be great to know how to do this, then i'd be able to apply it to other subjects in the future.
Ill add my code that I have at the moment. This is purely for practise as I'm learning PHP in my course :)
##getquote.php
<!DOCTYPE html PUBLIC "-//W3// DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Get Stock Quotes</title>
<link href='css/style.css' type="text/css" rel="stylesheet">
</head>
<h1>Stock Reader</h1>
<body>
<?php
//Read[1] = current price
//read[5] = opening price
//read[4] = down or up whatever percent from opening according to current price
//Step one
//Begin the PHP section my checking if the form has been submitted
if(isset($_POST['submit'])){
//Step two
//Check if a stock symbol was entered.
if(isset($_POST['symbol'])){
//Define the url to be opened
$url = 'http://quote.yahoo.com/d/quotes.csv?s=' . $_POST['symbol'] . '&f=sl1d1t1c1ohgv&e=.csv';
//Open the url, if can't SHUTDOWN script and write msg
$fp = fopen($url, 'r') or die('Cannot Access YAHOO!.');
//This will get the first 30 characters from the file located in $fp
$read = fgetcsv ($fp, 30);
//Close the file processsing.
fclose($fp);
include("php/displayDetails.php");
}
else{
echo "<div style='color:red'>Please enter a SYMBOL before submitting the form</div>";
}
}
?>
<form action='getquote.php' method='post'>
<p>Symbol: </p><input type='text' name='symbol'>
<br />
<input type="submit" value='Fetch Quote' name="submit">
</form>
<br />
<br />
##displayDetails.php
<div class='display-contents'>
<?php
echo "<div>Todays date: " . $read[2] . "</div>";
//Current price
echo "<div>The current value for " . $_POST["symbol"] . " is <strong>$ " . $read[1] . "</strong></div>";
//Opening Price
echo "<div>The opening value for " . $_POST["symbol"] . " is <strong>$ " . $read[5] . "</strong></div>";
if($read[1] < $read[5])
{
//Down or Up depending on opening.
echo "<div>" .strtoupper($_POST['symbol']) ."<span style='color:red'> <em>IS DOWN</em> </span><strong>$" . $read[4] . "</strong></div>";
}
else{
echo "<div>" . strtoupper($_POST['symbol']) ."<span style='color:green'> <em>IS UP</em> </span><strong>$" . $read[4] . "</strong></div>";
}
added code to displayDetails.php
function getLinks(){
$siteContent = file_get_contents($url);
$div = explode('class="yfi_headlines">',$siteContent);
// every thing inside is a content you want
$innerContent = explode('<div class="ft">',$div)[0]; //now you have inner content of your div;
$list = explode("<ul>",$innerConent)[1];
$list = explode("</ul>",$list)[0];
echo $list;
}
?>
</div>
I just the same code in - I didn't really know what I should do with it?!
Idk for fgetcsv but with file_get_contents you can grab whole content of a page into a string variable.
Then you can search for links in string (do not use regex for html content search: Link regex)
I briefly looked at yahoo's source code so you can do:
-yfi_headlines is a div class witch wrappes desired links
$siteContent = file_get_contents($url);
$div = explode('class="yfi_headlines">',$siteContent)[1]; // every thing inside is a content you want
-last class inside searched div is: ft
$innerContent = explode('<div class="ft">',$div)[0]; //now you have inner content of your div;
repeat for getting <ul> inner content
$list = explode("<ul>",$innerConent)[1];
$list = explode("</ul>",$list)[0];
now you have a list of links in format: <li>text</li>
There are more efficient ways to parse web page like using DOMDocument:
Example
For getting content of a page you can also look at this answer
https://stackoverflow.com/a/15706743/2656311
[ADITIONALY] IF it is a large website: at the beggining of a function do: ini_set("memory_limit","1024M"); so you can store more data to your memory!

Styling each result of an fgets($file) list differently, is it possible?

G'day, first post so here we go. Very open to suggestions as I'm not sure if it's possible to do what I want with the type of coding I am using. Kinda new/rusty to coding, been a LOOOONG time.
Purpose of current coding:
I have a .txt file with a list of file names (map names to be exact for my situation, each on it's own line) that is constantly being changed and modified as we add/remove maps. I am using a script on a .php page to parse the contents of that file and display the results on a webpage. The script outputs each map name to a variable that is wrapped in an href tag, which results in a link to download that particular map. This continues until all maps have been created in a list, each as a link to download that map.
Problem I am having:
I do not wish some maps/entries to be created as links, and only as text. Is there a way to filter the results of an fgets() and style them different based on value? So like map1-map4 all get turned into download links but map5 does not, then map6 and on continue to be download links.
Current script/code being used:
<?php
$file = fopen("maplists/dodgeball.ini", "r");
while (!feof($file)) {
$dbmapname[] = fgets($file);
}
fclose($file);
foreach ($dbmapname as $dbmap){
echo "<a href='http://www.mydownloadurl.com/fastdl/maps/" . $dbmap . ".bsp.bz2'>$dbmap</a><br />";
}
?>
Coding revised thanks to help below. Here is my current coding to produce what I was looking for:
foreach ($dbmapname as $dbmap){
if(!in_array($dbmap, $stockmaps)){
echo "<a href='http://www.mydownloadurl.com/fastdl/maps/" . $dbmap . ".bsp.bz2'>$dbmap</a><br />";
}
else echo $dbmap."<br />";
}
I am still having a slight issue though regarding the last entry of the array being forced to be a link regardless if it is in the $stockmaps array or not.
There are a ton of ways to implement this. Below I've presented a nice general way where you create an array of maps for which you don't want a link and then loop through and print either link or the plain text depending on whether each map is in the list.
<?php
$file = fopen("maplists/dodgeball.ini", "r");
while (!feof($file)) {
$dbmapname[] = trim(fgets($file));
}
fclose($file);
$nolink = array( $dbmapname[4] ); //fifth map
foreach ($dbmapname as $dbmap){
if(!in_array($dbmap, $nolink)){
echo "<a href='http://www.mydownloadurl.com/fastdl/maps/" . $dbmap . ".bsp.bz2'>$dbmap</a><br />";
}
else echo $dbmap."<br />";
}
}
?>
You can add item to the filter based on whatever criteria you want
//Add item 2 to the list
$nolink[] = $dbmapname[1];
//Add all items after item 20 to the list
$nolink = array_merge($nolink, array_slice($dbmapname, 20));
//Don't link a specific set of maps
$nolink = array('bad_map', 'another_map_not_to_show');

Updating HTML files using PHP from form input

Basically, I want to update static HTML files with code snippets input by users from a standard form. I understand how updating the files work, I'm just unsure as to how I go about including the code input from the form to my php file, which is shown below.
<?php
if($handle = opendir()) {
$search = '</body>';
replace = <<< EOF
<!-- I want to populate this with form field input.-->
EOF;
while(false !== ($entry = readdir($handle))) {
if(is_dir($entry)) continue;
$content = file_get_contents($entry);
$content = str_replace($search, $replace . '</body>', $content);
file_put_contents($entry, $content);
}
}
echo 'done';
?>
Any help greatly appreciated.
I would approach this a bit differently. I suggest having a template file aside from the one being modified. That way, you are always modifying a fresh copy instead of having to worry about what changed in the new version.
If your needs become more advanced beyond simply dropping in some markup, I might suggest using a DOM parser.
Finally, I'm sure you have a good reason for writing these static files... just remember the security implications of doing so. You're effectively letting someone do almost anything they want to your server.
Although I agreed it was in no way the best solution to the specific problem, for anyone that may find this useful in the future I used file_get and str_replace to achieve desired results. The code below will allow you to search a file for a specific term and replace with whatever you want based on form input.
<?php
//These are the variables the html file will post to the script.
$filename = $_POST['myFile'];;
$tofind = $_POST['myFind'];;
$toreplace = $_POST['myReplace'];;
$file = file_get_contents($filename);
$end = str_replace($tofind, $toreplace, $file);
$fp = fopen($filename, "w"); //Open the filename and set the mode to Write
if(fwrite($fp, $end)) ; //Write the New data to the opened file
fclose($fp); //Close the File
echo(" File name is $filename ... Finding $tofind .... Replacing with $toreplace ..... Done !");
?>
Though it's a horrible solution, mixed with your code this will do
$replace = array_key_exists('input',$_REQUEST) ? $_REQUEST['input'] : '';
//$replace = sanitize($replace); // there's so much bad with this string
//do the needfull
?>
<form method='GET' action='#'>
<input type='text' name='input' />
<input type='submit' />
</form>

Overwrite text in a specific div in a file (PHP HTML)

I am creating a slideshow editor. I have been able to parse a file and present it to the user in a form. Now I need to figure out how to write the saved information to the file. I want the user to be able to edit the information before and after the slideshow, so there is no specific set of information to be able to overwrite the whole file.
If there is a way to get all of the text before the div and copy it to the variable, add the new information, then get the rest of the information after the div and add that to the variable and then write all that information to the file, then that would work. Otherwise, here is what I have put together.
/* Set Variables */
$x = $_POST['x'];
$file = $_POST['file'];
$path = '../../yardworks/content_pages/' . $file;
$z=0;
while ($z<$x){
$title[$z] = $_POST['image-title'.$z];
$description[$z] = $_POST['image-desc'.$z];
$z++;
}
for ($y=0; $y<$x; $y++){
$contents .= '<li>
<a class="thumb" href="images/garages/'.$file[$y].'">
<img src="images/garages/'.$file[$y].'" alt="'.$title[$y].'" height="100px" width="130px" class="slideshow-img" />
</a>
<div class="caption">
<div class="image-title">'.$file[$y].'</div>
<div class="image-desc">'.$description[$y].'</div>
</div>
</li>';
}
/* Create string of contents */
$mydoc = new DOMDocument('1.0', 'UTF-8');
$mydoc->loadHTMLFile($path);
$mydoc->getElementById("replace")->nodeValue = $contents;
$mydoc->saveHTMLFile($path);
$file = file_get_contents($path);
$file = str_replace("<", "<", $file);
$file = str_replace(">", ">", $file);
file_put_contents($path, $file);
?>
Nothing throws out an error, but the file also remains unchanged. Is there anything I can change or fix to make it write to the file? This is all I have been able to find regarding this specific problem.
I would like to stick to one language, but if I find a way to write to the file using javascript, do the php variables pass on to the javascript section or do I have to stick with one language?
**Edit
Everything is working. ONE problem: is there a way to keep the special characters without converting them? I need the < and > to stay as they are and not convert to a string
I have decided to save the file as it is and use a separate code set to replace the string. I have edited my question above.

Using PHP to send photo URLs to JavaScript

I am helping my friend with his photo website oneonethousand.org. He wants the photo gallery to be generated automatically from the photos he places in a directory. I am not experienced with Ajax and think it might be too complex to use for this.
What I think would be best is to use PHP to identify the URLs of the photos in a directory and somehow send those URLs to JavaScript so that JavaScript can pre-load them and then display them when the corresponding photo button is selected on the site.
I know PHP and JavaScript (JQuery) relatively well, but I'm just not quite sure what the Best Practice is for what I need to do.
Just to reiterate: What he wants to do is place the photos in the directory, PHP searches that directory for the photo names, and passes those URLs to JavaScript so it can pre-load them.
How do you recommend going about this?
I would probably use AJAX to do this, but you certainly don't have to. In your page that is loaded by the browser, you can make PHP print Javascript, like so:
$HTML = '<script type="text/javascript">' . "\n";
$HTML .= 'var ImageCache = [];' . "\n";
foreach (glob('Path/To/Images/*.jpg') as $Image))
{
$HTML .= 'ImageCache.push("' . $Image . '");' . "\n";
}
$HTML .= 'for (var i in ImageCache) {' . "\n";
$HTML .= "\t" . 'var Source = ImageCache[i]; ' . "\n";
$HTML .= "\t" . 'ImageCache[i] = new Image(100, 100);' . "\n";
$HTML .= "\t" . 'ImageCache[i].src = Source;' . "\n";
$HTML .= '}';
$HTML .= '</script>';
You'd generally use a function like glob to get a list of all of the image files, then embed links to them in the page either directly, or using javascript as you suggested.
Something like this ...
$files = glob("/image/dir/*.{jpg,jpeg,gif,png}", GLOB_BRACE);
$js = "var images = new Array();\n";
foreach( $files as $i => $file ) {
$fileName = basename($file);
$js .= "images[$i] = '$fileName';\n";
}
Adding the $js as Javascript to your page will get you a list of the image names, client-side, which you can use as you see fit.
To transer data from PHP to javascript you can use XMLor JSON.
PHP provides functions and classes for both.
Using JSON is very simple
For more details about PHP and JSON see http://www.php.net/manual/en/book.json.php
For information about decoding the data in JavaScript read this http://json.org/js.html
EDIT:
If you generate your javascript in php you can encode a an array in JSON and use the generated code to declare a JavaScript array.
echo <<<END
<script>
...
var images = {$JSONEncodedArray};
...
</script
END;
Just dynamically generate a part of your JavaScript file with PHP, like so:
var slideshowImages = [<?php
$files_in_folder = /* get the files somehow */;
foreach($files_in_folder as $file) {
echo "\"$file\",";
}
?>null]; // Make sure to skip the last element
You might need to give your .js file a .php extension, if it is in fact a separate file.

Categories