Skip to content

Added option for adding timestamp to the url #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/UploadBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ class UploadBehavior extends Behavior
*/
public $deleteTempFile = true;

/**
* @var boolean whether to append a timestamp to the URL. Example: `/path/to/image.png?v=timestamp`
*/
public $appendTimeStamp = false;

/**
* @var UploadedFile the uploaded file instance.
*/
Expand Down Expand Up @@ -232,8 +237,9 @@ public function getUploadUrl($attribute)
$model = $this->owner;
$url = $this->resolvePath($this->url);
$fileName = $model->getOldAttribute($attribute);
$timestamp = $this->getTimestamp($attribute);

return $fileName ? Yii::getAlias($url . '/' . $fileName) : null;
return $fileName ? Yii::getAlias($url . '/' . $fileName) . $timestamp : null;
}

/**
Expand Down Expand Up @@ -335,4 +341,18 @@ protected function afterUpload()
{
$this->owner->trigger(self::EVENT_AFTER_UPLOAD);
}

/**
* Returns the timestamp of file by given attribute
* @param $attribute
* @return string|null
*/
protected function getTimestamp($attribute) {
if(!$this->appendTimeStamp) {
return null;
}
$file = $this->getUploadPath($attribute);
$timestamp = @filemtime($file);
return $timestamp > 0 ? "?v=$timestamp" : null;
}
}
5 changes: 3 additions & 2 deletions src/UploadImageBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public function getThumbUploadUrl($attribute, $profile = 'thumb')
/** @var BaseActiveRecord $model */
$model = $this->owner;
$path = $this->getUploadPath($attribute, true);
$timestamp = $this->getTimestamp($attribute);
if (is_file($path)) {
if ($this->createThumbsOnRequest) {
$this->createThumbs();
Expand All @@ -177,9 +178,9 @@ public function getThumbUploadUrl($attribute, $profile = 'thumb')
$fileName = $model->getOldAttribute($attribute);
$thumbName = $this->getThumbFileName($fileName, $profile);

return Yii::getAlias($url . '/' . $thumbName);
return Yii::getAlias($url . '/' . $thumbName) . $timestamp;
} elseif ($this->placeholder) {
return $this->getPlaceholderUrl($profile);
return $this->getPlaceholderUrl($profile) . $timestamp;
} else {
return null;
}
Expand Down