Luigi
Luigi

Reputation: 251

Upload an image or a txt and add it into a web page automatically

I have an uploader that make me upload files to the server.

I would like that when I upload an image, this image is automatically visible in a page of the site. Eg, if I have a site of a music band, if I upload from an administrator password protected page the poster of the next concert, and automatically in the page "events" I can see that poster.

In the same way if I upload (from another uploader) the text for that concert, this text appears in the event page in a "description of the concert" div.

Is it possible? thank you!

Upvotes: 1

Views: 141

Answers (1)

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11310

If you need to do that, then using the database and store the uploaded items in its coloumn is the better way..

But to answer your question

You can do something like this.

Step 1 :

Read all the files in your directory

$dir    = 'up/';
$files = scandir($dir);

Step 2 :

Do a foreach and print it in your file (If you need to display an image it can be possible and you can have links over there )

$i = 1;
foreach ($files as $key) 
{
    echo $i.' - '.$key.'<hr>';
    echo "<a href='up/".$key."'><img src ='up/".$key."'>".$key."</a>";
    $i++;
}

So you can have something like this..

<?php
$dir    = 'up/';
$files = scandir($dir);
echo '<h1>List of Uploaded Files</h1> <br><hr>';
$i = 1;
foreach ($files as $key) 
{
    echo $i.' - '.$key.'<hr>';
    echo "<a href='up/".$key."'><img src ='up/".$key."'>".$key."</a>";
    $i++;
}
echo 'End of Files';

?>

Note :

I am using the directory name as up you can have it any name of your own.

If you have this file as list.php then it should have a sub folder named as up and you should have files inside it.. You can have image or text file as you need.

Update :

If you just want to list the files, then you just need to echo it

<?php
$dir    = 'up/';
$files = scandir($dir);
echo '<h1>List of Uploaded Files</h1> <br><hr>';
$i = 1;
foreach ($files as $key) 
{
    echo $i.' - '.$key.'<hr>';
    $i++;
}
echo 'End of Files';

?>

Here's the eval link

Update 2 :

As the OP needs to have an anchor tag and wants to remove the directory level Here's the updated code

<?php
$dir    = 'up/';
$files = scandir($dir);
echo '<h1>List of Uploaded Files</h1> <br><hr>';
$i = 1;
foreach ($files as $key) 
{
    if ($i>3) 
    {
    $j = $i-3;
    echo $j."<a href='up/".$key."'>".$key."</a><hr>";
    }
    $i++;

}
echo 'End of Files';

?>

Here's the Eval

Upvotes: 1

Related Questions