Avatar of peter-cooper
peter-cooper
 asked on

Link referencing wrong location

I am using the opendir to read certain files into a loop and print them in a table. This works well apart from the fact that when it comes to downloading them, they are referencing the wrong location. Instead of referencing them from the folder i set in the $dir var, they are pointing to the parent folder where my page is loaded. For example, my structure is:

users
-->destcerts

Why is it not referencing the location set in the $dir var. Thanks

<?php
   //$directory = chdir('destcerts');
   $dir = opendir('destcerts');
   echo getcwd() . "\n"; [b] --> POINTS TO USERS FOLDER WHERE MY PHP FILE IS CALLED FROM[/b]
   
   $table = '<table border="1" width="90%" cellspacing="3" cellpadding="5" align="center">
   <tr>
   <th colspan="3">Results</th>
   </tr>
   <th>File</th>
   <th>File</th>
   <th>File</th>';
   
   //List files in pdf dir
   while (($file = readdir($dir)) !== false)
   {		
   if(substr( $file, -3 ) == "pdf" )
   
   {
   //echo '<br />' . "<a href=\"" . $file . "\">" . $file . "</a>";
   
   $table .= '<tr>
   <td align="center"><img src="destcerts/PDF_icon_100.png"><br /><a href="'.$file.'" style="font-size:12px; color:blue; text-decoration:none;">'.$file.'</a></td>
   <td align="center"><img src="destcerts/PDF_icon_100.png"><br /><a href="'.$file.'" style="font-size:12px; color:blue; text-decoration:none;">'.$file.'</a></td>
   <td align="center"><img src="destcerts/PDF_icon_100.png"><br /><a href="'.$file.'" style="font-size:12px; color:blue; text-decoration:none;">'.$file.'</a></td>
   </tr>';
   
   }
   }
   
   $table .= '</table>';
   echo $table;
   
   closedir($dir);
   
   
   ?>

Open in new window

PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
Ray Paseur

Directory addresses in PHP and URL link addresses need separate consideration to work correctly.  I'll see if I can show you an example in a few moments, but in a nutshell, getcwd() will give you information that works on your server and with your PHP scripts, but you also need to know the directory structure that an internet link will use, following the cascade from your web home page through the directory list.
Ray Paseur

Here's the general use case, using relative addressing for the links.  Please look it over and post back with any questions.
http://iconoun.com/demo/temp_petercooper.php

<?php // demo/temp_petercooper.php
error_reporting(E_ALL);
echo '<pre>';

// See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28553444.html

/**
 * URL PATHS LOOK LIKE THIS:
 * home
 * |__demo            <-- THIS SCRIPT IS LOCATED HERE
 *    |__storage      <-- IT LISTS FILES LOCATED HERE
 *       |__file1
 *       |__file2
 *       |__etc...
 */

// WHAT IS MY CURRENT DIRECTORY?
$dir = getcwd();
echo PHP_EOL . "WEB DIRECTORY: $dir";

// WHAT IS IN THE STORAGE DIRECTORY
$sub = 'storage';

// READ THE NAMES OF FILES IN THE SUB-DIRECTORY
$fff = new DirectoryIterator($sub);
foreach ($fff as $filedata)
{
    // SKIP THE "DOT" FILES
    if (!$filedata->isDot())
    {
        // CREATE LINKS TO THESE FILES
        $nom = $filedata->getFilename();
        $lnk
        = '<a target="_blank" href="'
        . $sub
        . DIRECTORY_SEPARATOR
        . $nom
        . '">'
        . $nom
        . '</a>'
        ;
        echo PHP_EOL . $lnk;
    }
}

Open in new window

Ray Paseur

Here's how to restrict it to PDF files only.  Man page here:
http://php.net/manual/en/class.directoryiterator.php

<?php // demo/temp_petercooper.php
error_reporting(E_ALL);
echo '<pre>';

// See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28553444.html

/**
 * URL PATHS LOOK LIKE THIS:
 * home
 * |__demo            <-- THIS SCRIPT IS LOCATED HERE
 *    |__storage      <-- IT LISTS FILES LOCATED HERE
 *       |__file1
 *       |__file2
 *       |__etc...
 */

// WHAT IS MY CURRENT DIRECTORY?
$dir = getcwd();
echo PHP_EOL . "WEB DIRECTORY: $dir";

// WHAT IS IN THE STORAGE DIRECTORY
$sub = 'storage';

// READ THE NAMES OF FILES IN THE SUB-DIRECTORY
$fff = new DirectoryIterator($sub);
foreach ($fff as $filedata)
{
    // SKIP THE "DOT" FILES
    if (!$filedata->isDot())
    {
        // RESTRICT IT TO PDF FILES ONLY
        if ($filedata->getExtension() != 'pdf') continue;

        // CREATE LINKS TO THESE FILES
        $nom = $filedata->getFilename();
        $lnk
        = '<a target="_blank" href="'
        . $sub
        . DIRECTORY_SEPARATOR
        . $nom
        . '">'
        . $nom
        . '</a>'
        ;
        echo PHP_EOL . $lnk;
    }
}

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
peter-cooper

ASKER
@Ray

Thank you very much. All I had to change was the . DIRECTORY_SEPARATOR into .'/' and it worked. How can I incorporate this into my posted code? I need to show in a table as I have posted. Many thanks
Ray Paseur

Why did you change DIRECTORY_SEPARATOR?  It's a built-in PHP constant!  Different systems use different directory separator characters, and PHP is sufficiently self-aware that it will choose the right character if you use the built-in.
http://php.net/manual/en/dir.constants.php
peter-cooper

ASKER
Because it defaulted for some reason to \ instead of /. If it helps, I am using php 5.3.13. Thanks
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Ray Paseur

Sorry, I don't really understand the code posted here.  It looks to me like it would be producing three identical data elements for each PDF file.  Is that what you want?  Or can you just describe the needs in plain language - perhaps we can come up with something that would make sense for a tabular display.
Ray Paseur

Interesting.  PHP 5.3 is obsolete, so there would be no value in filing a bug report.  What OS is your server using?
Ray Paseur

Or maybe not... Let me look at it again with fresh eyes.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Ray Paseur

No, I guess I'm confused.  The program logic is much easier to follow if you adopt a coding standard that includes indenting the control structures so that the logic acquires a visible quality.  Example here (with comments)

   // EACH FILE WILL BE LOCATED ONCE
   while (($file = readdir($dir)) !== false)
   {
      // IF THE FILE IS A PDF
      if(substr( $file, -3 ) == "pdf" )   
      {
         // THIS WILL CREATE THREE LINKS TO THE SAME FILE
         $table .= '<tr>
         <td align="center"><img src="destcerts/PDF_icon_100.png"><br /><a href="'.$file.'" style="font-size:12px; color:blue; text-decoration:none;">'.$file.'</a></td>
         <td align="center"><img src="destcerts/PDF_icon_100.png"><br /><a href="'.$file.'" style="font-size:12px; color:blue; text-decoration:none;">'.$file.'</a></td>
         <td align="center"><img src="destcerts/PDF_icon_100.png"><br /><a href="'.$file.'" style="font-size:12px; color:blue; text-decoration:none;">'.$file.'</a></td>
         </tr>';   
      } // END IF
   } // END WHILE

Open in new window

peter-cooper

ASKER
@Ray

I am using wamp on localhost on win7 but I will be porting site to centOS + Plesk. What I am trying to achieve Ray, is if there are say 10 different files in a directory, then  display those files in a 3 column table layout. I don't wish to out put the same file. This is where I am struggling.

I take your point ray regarding formatting. Thanks
Ray Paseur

Ahh, that is a different question entirely!  I'll try to show you a general design.  We usually use arrays of data for this purpose.  Back in a few minutes...
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
peter-cooper

ASKER
Thx Ray. Just gonna have dinner. Be back about an hour.
Ray Paseur

There are many ways to do this, but I think this is one of the easiest to understand and get right.  It uses the amazingly useful HEREDOC notation to insert the PHP variables into the HTML.  Please post back if you have any questions.
<?php // demo/temp_petercooper.php
error_reporting(E_ALL);


// See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28553444.html


// ALLOCATE AN ARRAY OF DATA ELEMENTS INTO A THREE-COLUMN TABLE
$datas = array( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H');

// ACCUMULATE THE TABLE ROWS HERE
$trs   = NULL;

// COLLECT GROUPS OF THREE
while (!empty($datas))
{
    $td1 = array_shift($datas) or NULL;
    $td2 = array_shift($datas) or NULL;
    $td3 = array_shift($datas) or NULL;

    // USE HEREDOC TO INSERT THESE INTO A TABLE ROW
    $tr  = <<<EOD
<tr>
<td>$td1</td>
<td>$td2</td>
<td>$td3</td>
</tr>
EOD;

    // APPEND THE TABLE ROW TO THE OTHER ROWS
    $trs .= $tr;
}

// USE HEREDOC TO INSERT THE TABLE ROWS INTO THE TABLE
$tab = <<<EOD
<table>
<tr colspan="3">Results</tr>
<tr>
<th>File</th>
<th>File</th>
<th>File</th>
</tr>
$trs
</table>
EOD;

// SHOW THE WORK PRODUCT
echo $tab;

Open in new window

ASKER CERTIFIED SOLUTION
Ray Paseur

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
peter-cooper

ASKER
@Ray

Thanks very much. However, some of this is quire new to me. Firstly, in my original code, I had an image above the link in the td tag. How do I incorporate that into your code? Lastly, is there a way to capture the size and date of the files. Thanks very much
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
peter-cooper

ASKER
@Ray

Sorted out the image in link. However, can you help with size and date? Thanks
Ray Paseur

See near lines 46-50.
<?php // demo/temp_petercooper_old.php
error_reporting(E_ALL);


// See http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28553444.html


/**
 * URL PATHS LOOK LIKE THIS:
 * home
 * |__demo            <-- THIS SCRIPT IS LOCATED HERE
 *    |__storage      <-- IT LISTS FILES LOCATED HERE
 *       |__file1
 *       |__file2
 *       |__etc...
 */

// WHAT IS MY CURRENT DIRECTORY?
$dir = getcwd();
echo PHP_EOL . "WEB DIRECTORY: $dir<br>";

// WHAT IS IN THE STORAGE DIRECTORY
$sub = 'storage';

// READ THE NAMES OF FILES IN THE SUB-DIRECTORY
$fff = new DirectoryIterator($sub);
$sss = array();
foreach ($fff as $filedata)
{
    // SKIP THE "DOT" FILES
    if ($filedata->isDot()) continue;

    // ACTIVATE THIS LINE TO RESTRICT IT TO PDF FILES ONLY
    // if ($filedata->getExtension() != 'pdf') continue;

    // CREATE LINKS TO THESE FILES
    $nom = $filedata->getFilename();
    $lnk
    = '<a target="_blank" href="'
    . $sub
    . DIRECTORY_SEPARATOR
    . $nom
    . '">'
    . $nom
    . '</a>'
    . '<br>'
    . number_format( $filedata->getSize() )
    . ' bytes'
    . '<br>'
    . date('Y-m-d g:ia', $filedata->getMtime())
    . PHP_EOL
    ;

    // COLLECT THE LINKS HERE
    $sss[] = $lnk;
}

// ACCUMULATE THE TABLE ROWS HERE
$trs   = NULL;

// COLLECT GROUPS OF THREE
while (!empty($sss))
{
    $td1 = array_shift($sss) or NULL;
    $td2 = array_shift($sss) or NULL;
    $td3 = array_shift($sss) or NULL;

    // USE HEREDOC TO INSERT THESE INTO A TABLE ROW
    $tr  = <<<EOD
<tr>
<td>$td1</td>
<td>$td2</td>
<td>$td3</td>
</tr>
EOD;

    // APPEND THE TABLE ROW TO THE OTHER ROWS
    $trs .= $tr;
}

// USE HEREDOC TO INSERT THE TABLE ROWS INTO THE TABLE
$tab = <<<EOD
<table>
<tr colspan="3">Results</tr>
<tr>
<th>File</th>
<th>File</th>
<th>File</th>
</tr>
$trs
</table>
EOD;

// SHOW THE WORK PRODUCT
echo $tab;

Open in new window

peter-cooper

ASKER
@Ray

Thanks Ray. Points well deserved.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
peter-cooper

ASKER
Thanks once again ray for your time and patience.
Ray Paseur

Glad you've got it pointed in the right direction!  Thanks for the points and thanks for using E-E, ~Ray