Using PHP to send photo URLs to JavaScript - php

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.

Related

Change html code depending on the size of the array in php

Hi i have an array with some Urls and Html code for open this webs in others tabs.
But the array dynamically changes the amount of Urls it contains. How can I change the Html code depending on the number of Urls that my array contains?
Code:
<?php
//$myarray can change dinamicaly the amount of urls contains
$myarray=array('www.google.com','www.piza.com','www.5.com');
?>
Now in my HTML code I have the code for open a tab, but i need open the array numbers of urls. In this case I need window.open('') three times.
<p><a href='#'
onclick='window.open('');
>Click to open webs</a></p>
<?php
//$myarray can change dinamicaly the amount of urls contains
$myarray=array('www.google.com','www.piza.com','www.5.com');
$windowsOpen = '';
foreach ($myarray as $value) {
$windowsOpen .= "window.open('$value', '_blank');";
}
?>
//now in my HTML code I have the code for open a tab, but i need open the array numbers of urls. In this case I need 'window.open('')' three times.
<p>Click to open webs</p>
Few things you should know, the URLs need to start with 'http://' or 'https://' in order to be an external link, if not it be considered as an internal link.
Moreover, most of the browsers will block the window.open if it is more than one as spam.
You could do something like this (although I'd advise against it without careful sanitzation if the urls are originating from inputs entered by users)
<?php
$arr = array("https://www.google.com", "https://www.pizza.com");
?>
<script>
function openWindows() {
var urlsArray = <?php echo '["' . implode($arr, '","') . '"]'; ?>;
for(i=0; i<urlsArray.length; i++) {
window.open(urlsArray[i]);
}
}
</script>
Open Windows

(PHP) Creating HTML Files With Variable Content

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

Open XML elements in PHP

Good, I created an XML document with the name and title of songs and artists within that document come also the corresponding cover. Now the link of my XML file is: http://inlivefm.96.lt/nw.xml .
I also have another XML document that gives me the name and artist title that this amounts to the moment (ADELE - HELLO) Now the link of my XML file is: http://inlivefm.96.lt/NowOnAir.xml .
Well, what I'm trying to make is that with document I created give me the cover of this song to give right now. I tried to make a code but to no avail in PHP, so I came to ask your help to get success.
Here I leave the code I am using to try to get what I want.
<?php
$xml = simplexml_load_file('http://inlivefm.6te.net/agora.xml');
$artist = urlencode($xml->Event->Song->Artist['name']);
$track = urlencode($xml->Event->Song['title']);
$url = simplexml_load_file("http://inlivefm.96.lt/nw.xml");
$largeImage = $url->xpath('/ilm/$artist- $track/image[#size="cover"]')[0];
echo '<img src="'.$largeImage.'" />';
?>
Can you please help me doing this?
Thank you all in advance.
correct xpath to take image is
(/ilm/artist/image[#size="cover"])[count(/ilm/artist/name[.="ADELE-HELLO"]/preceding-sibling::name)+1]
because you need to get image with the same position as artist's name.
In php code it should be something like this:
$XML = simplexml_load_file('http://inlivefm.6te.net/agora.xml');
$artist = $XML->Event->Song->Artist['name'];
$track = $XML->Event->Song['title'];
$URL = simplexml_load_file("http://inlivefm.96.lt/nw.xml");
$largeImage = $URL->xpath('(/ilm/artist/image[#size="cover"])[count(/ilm/artist/name[.="'. $artist .' - '. $track.'"]/preceding-sibling::name)+1]');
echo '<img src = "'. $largeImage[0]. '" />';

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');

Categories