Php script for site navigation?

software development

#1

I was wondering if it would be possible to make my site a little more automated …
I run this site for a friend of mine who makes web comics, and currently I have the site organized in folders and such … one of which contains all of the the image files and separate .php files for each one (giving each its own page). I have noticed that on some sites instead of have a ton of different pages, you stay on the same page and they php scripts to change the displayed image. Right now I have the homepage displaying the newest comic and then in the comic folder there are all of the comics (a jpeg file and a php file each) and an archive.php file with drop-down menus linking to each one of them. Also … below the images on each page there are navigation links to go to the Previous and Next comic, and to the First and Newest comics.
I was wondering if there was a better way … with less work involved? Each time I have to change the image on the front page, add the comic’s page to the comic folder, update the links for the navigation buttons, and add the new comic to the archive.
I have a general idea of what to do but I’m not sure what all is involved in implementing it.
If you want to get a visual of what I have right now you can visit my site at thespiffylife.com.

I greatly appreciate any advice that you may be able to provide!
This site has been made on a “learn it as you go” basis …

Thanks!


#2

One thing you can do is use php to read the directory and put all the filenames in an array. The array can then be sorted if needed. But your next and previous buttons would just get the filename from the array then you don’t have to update the page each time you upload files.
Silk

My website


#3

i tried to use the scandir() function just as a test, but it seems that DreamHost hasn’t enabled that for “security reasons,” and they said I could install php5 myself if I wanted that function. Is there another way to do what I want without having to install my own version of php?


#4

Do you happen to already have a SQL database setup for that site? I personally would probably put all of the IDs for the files in a table.

I’d include the Current ID, Next ID, Previous ID, and a flag for starting point.

The page could:

  1. Take the ID as a parameter
  2. look up the data based on that ID.
  3. Grab the starting point values if no ID was passed, or the data for given ID wasn’t found.
  4. Include the comic file using the ID value for the tag
  5. Create the Next and Previous links using the values pulled from the DB in step 2 or 3 above. (The Next and Previous links would just link back to the same page passing the new IDs)

If you don’t have a db already, I’m sure this data can be put in a file instead, but I don’t really use file based data for my sites except for configuration settings.


find/offer services free
http://www.TheHelpfulNeighbor.com
Codes:THNMax ($97) THNMaxHDD (+100%) THNMaxBW (+100% txfr) THNMaxDomains (5 free) THNBalance (20% HD&BW, 1 Domain+IP +$16)


#5

Yes I do have MySQL already setup for this domain … but I’ve only really used it for things like Wordpress or phpbb, so I’m not a hundred percent sure how to set all that up. I under stand how to make tables in it and stuff but I don’t know how to pull those in to other pages and use IDs?
And if I created the MySQL database, would I need to update it everytime I added a new comic to the site? If so, I would have no trouble doing that … but my friend who draws them knows very little about web developing and would probably mess things up on accident.
This does sound along the lines of what I wanted, but I just need some more help getting there if you could.
THANKS!


#6

Maybe the following can point you in the right direction
Silk

<?php $pagetitle='CG Stills'; include ('header.inc'); print <<<HEAD

{$pagetitle}

Click on image for full size. Click on back button to return.

# of Columns: HEAD; if ($_POST['columns']==2) { print "2"; } else { print "2"; } if ($_POST['columns']==3) { print "3"; } else { print "3"; } if (($_POST['columns']==4) || ($_POST['columns']==null)) { print "4"; } else { print "4"; } if ($_POST['columns']==5) { print "5"; } else { print "5"; } print <<< HEAD2

HEAD2; include ('menu.inc'); $max = $_POST['columns']; if (($_POST['columns'] < 2) || ($_POST['columns'] > 5)) { $max=4; } $dir = './Gallery'; $thumbnails = 'Thumbnails'; $tr = ''; $td = "\n\n"; $grid = "\n\n
\n\n\n\n$tr"; $i=0; print $grid; $d=opendir($dir); while (false !== ($file = readdir($d))) { $files[]=$file; } sort ($files); foreach ($files as $file) { if (preg_match('/(jpg|gif|png)$/', $file)) { $strip=rtrim($file, '.jpg|.gif|.png'); $dirfile = $dir . "/" . $file; $thumb = $dir . "/" . $thumbnails . '/' . $file; $size = intval(filesize($dir . "/" . $file)/ 1024); print $td . "\"$file\" $strip $size KB"; $i++; if ($i==$max) { print "\n\n$tr"; $i=0; } } } print "\n\n" . '
' . "\n\n"; print "
\n\n"; include ('footer.inc'); ?>

My website


#7

I’m really not sure I understand what all that is doing. If you wouldn’t mind, I would greatly appreciate at least an overview of what that code is supposed to do, and I could manage to look up and figure out the rest. Right now I would have no idea how to properly implement even part of that correctly …

On another note, does anyone know if DreamHost allows creating mysql tables from a php script? Because I was just messing around earlier today, trying to figure out a way to do this and I get getting an error saying I don’t have permission to that database or something along that line. It feels like you have to create it either from within the panel or the myPHPadmin site.

I appreciate the help!


#8

There are three includes, one for a header, one for a menu and one for a footer. These can be removed if you don’t need them. These were put in place to handle my web site, so I did not have to repeat code for each page.
$pagetitle is in place to allow you to add a title to your header, by putting the same string in the header.inc file.
The next portion is a small drop down form to control the number of images across the table. I added this to help with different screen sizes. I did not implement sessions or cookies in this code.
below is the true meat of the code:

$dir = ‘./Gallery’; /This is the directory where your images are stored/
$thumbnails = ‘Thumbnails’; /*This is the subdirectory below $dir to store thumbnails. I felt it would be easier to keep the two seperate */
$tr = ‘

’; /*Style for the table row /
$td = “\n\n<td style=“border: 1px solid”>”;/Style for the table cell and includes two newlines /
$grid = “\n\n<div class=“grid”>\n\n<table style=“border: 2px ridge”>\n\n$tr”;/
This is the beginning of the table that includes both a div class and a table style feel free to alter this format your table
/
$i=0;/
This string is for counting the number of images before going to next row */
print $grid;/Start of the table/
$d=opendir($dir);/Assigns a pointer to the directory/
while (false !== ($file = readdir($d))) { /Reads the directory and puts it in a string/
$files[]=$file;/Takes string and assigns it to the array/
}
sort ($files);/Put directory in alphabetical order/
foreach ($files as $file) {/Takes the array and places it in a string/
if (preg_match(’/(jpg|gif|png)$/’, $file)) {/finds all files that end with .jpg, .gif, or .png/
$strip=rtrim($file, ‘.jpg|.gif|.png’);/Removes the extention from the filename/
$dirfile = $dir . “/” . $file;/combines the two strings/
$thumb = $dir . “/” . $thumbnails . ‘/’ . $file;/combining two directories with the file name/
$size = intval(filesize($dir . “/” . $file)/ 1024);/Converting the filesize to KB/
print $td . “<a href=”$dirfile"><img style=“border: none” src="$thumb" alt="$file">< br >$strip< br >$size KB";/displays the image with filename and filesize in a table cell/

$i++;/Increment the table cell/
if ($i==$max) {
print “

\n\n$tr”;
$i=0;
}/If cell count has reach maximum value go to new row/
}
}
print “\n\n” . ‘’ . “\n\n”;

Lastly double check any code from a forum as code can be dropped.
Silk

My website


#9

You can certainly create tables from a PHP script. What code are you using?

:cool: [color=#6600CC]Atropos[/color] | openvein.org


#10
<?php $con = mysql_connect("mysql hostname","username","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); mysql_query("INSERT INTO test (FirstName, LastName, Age) VALUES ('Peter', 'Griffin', '35')"); mysql_query("INSERT INTO test (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', '33')"); mysql_close($con); ?>

of course the hostname, username, and password values i fill in … this is obviously just a test script … which wonderfully enough didn’t work for me lol
so yeah … any ideas?


#11

[quote]of course the hostname, username, and password values i fill in … this is obviously just a test script … which wonderfully enough didn’t work for me lol
so yeah … any ideas?[/quote]
Where was the error, and what was the message? Of course assuming you received an error message. I don’t exactly use my sql calls that way anymore, but that looks correct to me. Your SQL is ok. I created a test table with those 3 field names right on my local server and ran one of your insert lines directly. It works fine.

One thing to keep in mind and be very careful about. MySQL on *nix systems is picky about case. It must match exactly. Make sure the case for the table name and the field names match exactly.


find/offer services free
http://www.TheHelpfulNeighbor.com
Codes:THNMax ($97) THNMaxHDD (+100%) THNMaxBW (+100% txfr) THNMaxDomains (5 free) THNBalance (20% HD&BW, 1 Domain+IP +$16)


#12

[quote]of course the hostname, username, and password values i fill in … this is obviously just a test script … which wonderfully enough didn’t work for me lol
so yeah … any ideas?[/quote]
Alright, I threw your code in a page and ran it. Obviously I substituted my server and user info. It worked fine. Other than possible case issues on the fields above, I noticed your first field in the mysql_connect has the value “mysql hostname”. It isn’t 2 words when you run it right? It is just the hostname. It should be just 1 word as the host name.

Again, if you are getting any errors back, post them here. But your example works fine.


find/offer services free
http://www.TheHelpfulNeighbor.com
Codes:THNMax ($97) THNMaxHDD (+100%) THNMaxBW (+100% txfr) THNMaxDomains (5 free) THNBalance (20% HD&BW, 1 Domain+IP +$16)


#13

Okay, so I can’t get it to allow me to create a database or table from a php file, but that’s okay. I went into the phpmyadmin and did it manually. But I was able to update the table from a php script, so all is well I suppose.
I made a few columns relating to each comic: Link, Image, Date, and comicID. the comicID is an auto-increment variable which i hope to be able to use to my advantage once I figure out how to manipulate the mysql and php scripts. What I’d like to have is the navigation below each comic (back, first, last, next) use the mysql database (and I think the auto-increment variables) instead of manually updating the links each time. I think it would also be neat if their was a php function that read the file name that it was currently in (which would be the same value for the Link variable in the mysql database) and use that to automatically bring in the image as well. My main problem with doing this is I don’t really know how to do this properly. I know I need to query the values in the page but I’m not sure how to grab the comicID value using the Link value … and other things like that.
I really do appreciate the help, because MySQL is definitely over my head!


#14

Using the auto-increment value could be handy. My only concern with using that as the key for determining which comic is next or previous would be that you would limit yourself to only ever being able to add comics to the beginning or end of the series, whichever direction the natural flow is and I’d presume that is beginning to end.

As long as you can work within these contraints, it is fine. But there won’t be any inserting a comic in the middle of the series as the autoincrement number will wind up the highest.

If however you use some other notation in each record, then it could be possible to add one into the series at any point.

Now, there are various ways to do what you need. You could make your page retrieve the IDs for the First, Last, Previous, and Next with each page load. Or you could just pass the ID for the current comic to your db calls to retrieve whatever direction the user wants to go.

You would only need to pass the ID when trying to move forward or back one as first and last are not really based on the ID.

Here are basic queries that can be used to find the appropriate record for your navigation.

– Earliest record still in the table (First)
SELECT *
FROM comic
ORDER BY comicID ASC
LIMIT 1;

– Last record still in the table (Last)
SELECT *
FROM comic
ORDER BY comicID DESC
LIMIT 1;

– Next comic still in the table (Next based on current comicID)
SELECT *
FROM comic
WHERE comicID > 5 – Would be variable
ORDER BY comicID ASC
LIMIT 1;

– Previous comic still in the table (Previous based on current comicID)
SELECT *
FROM comics
WHERE comicID < 5 – Would be variable
ORDER BY comicID DESC
LIMIT 1;

The down side of trying to navigate based on the current ID instead of by finding the appropriate values to build the navigation at page load time is that unless you add another set of checks, you don’t know if there should be a next and previous button.

There are multiple ways to do any piece of this. Feel free to ask specific questions and I’d be happy to answer them here. If you would prefer, I can help you more out of this forum.

I personally would put the current ID in a hidden input field and read it back in to determine the current comic. You could put it in session, or put it in the URL, or there are other options available.


find/offer services free
http://www.TheHelpfulNeighbor.com
Codes:THNMax ($97) THNMaxHDD (+100%) THNMaxBW (+100% txfr) THNMaxDomains (5 free) THNBalance (20% HD&BW, 1 Domain+IP +$16)


#15

would i be saving the results from the select queries as a variable so i could call them in the links to the next and previous comics?
i was wondering how the url of the site would end up looking. i’ve seen a lot that look like http://site.com/comic.php?id=###

and in my archive file would i be able to refer to each of the comics by their comicID (that would be best i suppose). Would I need to save select query as a variable there too? any ideas on how i would go about doing this? i’ve got a basic idea but i’m sure it would end up being wrong. i appreciate the help and i’ve on my summer break so now i can focus on this a lot more :slight_smile:

-edit-

I just did this to grab the first and last comic links from the db for the navigation buttons/links.

[quote]<?php
$con = mysql_connect(“mysql.thespiffylife.com”,“username”,“password”);
if (!$con)
{
die('Could not connect: ’ . mysql_error());
}

mysql_select_db(“comiclist”, $con);

$result = mysql_query(“SELECT * FROM comics ORDER BY comicID ASC LIMIT 1;”);

$info = mysql_fetch_array($result);

echo $info[“Link”];

mysql_close($con);
?>[/quote]

I know I need to grab the current comicID for each page (somehow) before I can be able to implement something like this for the previous and next links to work, but I’m not really sure how to do that without defining it on each page (which would defeat the purpose of this).


#16

I’m not sure I follow exactly what you want to do yet. What is ‘Link’ ? Is it a title of a comic, or is it a URL ? Will each comic have its own .php or .html file or do you want a single PHP script to show all the comics?

Given what I understand so far I came up with a PHP script that I have documented for you. It is just a starting point meant to demonstrate breaking down processes into functions to make the code more manageable and easier to follow. It will show a list of links to comics in reverse chronological order.

[code]<?php

// database parameters

define(‘DB_HOSTNAME’, ‘localhost’);
define(‘DB_NAME’, ‘comiclist’);
define(‘DB_USERNAME’, ‘duh’);
define(‘DB_PASSWORD’, 'duh);

// connect to database server

$db_link = mysql_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD);

// check connection

if (! $db_link) {

// connection failed

die('Could not connect: ’ . mysql_error());
}
else {

// connection successful

// select database

if (mysql_select_db(DB_NAME, $db_link)) {

// database selected

// get all comic rows

$comics = get_comics($db_link);

// output an HTML list of links

echo comic_list($comics);

}
else {

// could not select database

die('Could not select database: ’ . mysql_error());
}
}

function get_comics($db_link) {

// fetch all comics from database
// comics sorted reverse chronological order (newest first)
// returns an array of rows

// initialize array

$comics = array();

// perform database query

$result = mysql_query(‘SELECT * FROM comics ORDER BY Date DESC’, $db_link);

// fetch each row as a hash

while($comic = mysql_fetch_assoc($result)) {

// append hash to array

$comics[] = $comic;
}

// return array

return $comics;
}

function comic_list($comics) {

// make an HTML unordered list
// iterate over array getting an HTML anchor for each comic
// returns a string

if (count($comics) == 0) {

// Empty list, return empty string

return ‘’;
}

// start element code

$list = ‘

    ’;

    // iterate over comics array

    foreach ($comics as $comic) {

    // make a list item from anchor

    $list .= ‘

  • ’ . comic_anchor($comic) . ‘
  • ’;
    }

    // end element code

    $list .= ‘

’;

// return element code

return $list;
}

function comic_anchor($comic) {

// make an HTML anchor from comic
// returns a string

$anchor =
’ .
$comic[‘comicID’] . ’ – ’ . $comic[‘Date’] . ’ – ’ . $comic[‘Link’] .
’;

return $anchor;
}

?>[/code] :cool: openvein.org -//- One-time [color=#6600CC]$50.00 discount[/color] on [color=#0000CC]DreamHost[/color] plans: Use ATROPOS7


#17

I’ve managed to figure a lot of stuff out from all the (specific) examples everyone has shown me as well as from other tutorial sites, but my main concern right now is about security. If I implement a mysql database query on my main page, what would stop someone from downloading that file and just looking at my username and password for my database? is there a way to mask these?


#18

Normally you can’t just “download” a PHP file over the Web because the Web server must “execute” it instead of “reading” it. Just in case the Web server thinks it should read PHP files though there are at least two things you want to do. First of all make sure all PHP files that should not be “read” or “executed” have those permissions disabled. That is to say instead of a chmod 755 or chmod 644 you should use 750 or 640 instead. The web server will not “read” files it for which it does not have permission.

Second is to separate sensitive code (such as database details) to a PHP file that is not accessible by the Web. In other words don’t stick it in your Web Directory or a Re-mapped subdirectory. Make sure no Web applications (like Wordpress) with file editors can access it. Then you just need to use the include() function in your CGI script to have PHP parse the file.

:cool: openvein.org -//- One-time [color=#6600CC]$50.00 discount[/color] on [color=#0000CC]DreamHost[/color] plans: Use ATROPOS7