The Rock
The Rock

Reputation: 413

After download rename source file in php

I loop .jpg file from my uploads/document and show it in my page and then i click to download one by one file and after I download .jpg from source in folder uploads\document\ the real file from my folder will be rename to other name.

I try these:

<?php
foreach (glob('uploads/document/' . '/*.{jpg}', GLOB_BRACE) as $file) {
    echo '<a class="snapchat" download="' . basename($file)  . '" href="/uploads/document' . '/' . basename($file) . '">' . basename($file) .
        '</a><br/>';

        rename('/uploads/document' . '/' . basename($file) ,'Mynew' );

}
?>

Any solution for these?

Upvotes: 0

Views: 76

Answers (1)

Mohamed Sa&#39;ed
Mohamed Sa&#39;ed

Reputation: 801

First : you cannot rename the source file before download , so you need to rename it after download

You can do that by PHP header() Function all you need is another php script to handle the download and rename the file,
Like :

1- Main PHP

<?php
$dir = 'files/';//uploads/document/
foreach (glob("$dir*.{jpg}", GLOB_BRACE) as $file) {
    echo '<a class="snapchat" download="'.basename($file).'" href="download.php?fn='.basename($file).'">'.basename($file).'</a><br/>';
}
?>

2 - download.php

<?php
$dir = 'files/';//uploads/document/
$file = $dir.$_GET['fn'];
if (file_exists($file))
{
    $type = 'image/jpeg';
    header('Content-Type:'.$type);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    rename($file, $dir."mynewName");
    exit();
}
else // file not exists Or has been downloaded before
{
    header('HTTP/1.0 403 Forbidden');/* Retern Forbidden */
    /*OR*/ 
    //header("Location: 404.php?".$file); /* Redirect browser */
    exit();
}
?>

Upvotes: 1

Related Questions