Jump to content
neophron

How to remove a file extension?

Recommended Posts

Hi,

I was searching in the forum about a method how to remove a file extension, like .jpg, but couldn't find anything.
There are some php methods out in the wild, but I wanted first to get sure, that Processwire is offering a solution.

The background is, that a clients website has a lot of images, packed in different galleries. All image files contain the name, dimensions and other stuff about the image (painting). I want to echo the image name in the image tag.

 

thanks 

Share this post


Link to post
Share on other sites

That's so trivial, that you hardly need a function for that.

$filename = '/path/to/image.jpg';
echo pathinfo($filename)['filename'];

Or am I missing something? 

Share this post


Link to post
Share on other sites
34 minutes ago, neophron said:

The background is, that a clients website has a lot of images, packed in different galleries. All image files contain the name, dimensions and other stuff about the image (painting). I want to echo the image name in the image tag.

Are these images saved in ProcessWire image fields?

Share this post


Link to post
Share on other sites

The image field is »array of items« with 0=no limit. And this is the code the template:

<?php
        foreach($page->images_slider as $slide_image) {
          $slide = $slide_image->size(0,700);
            echo "
              <li class='uk-width-3-4'>
                <img class='photo' src='{$slide->url}' alt='{$slide_image->basename}' height='700' />
              </li>

              ";
            }
        ?>

 

Share this post


Link to post
Share on other sites

Maybe rtrim can work as well? or that and mb_string?

E.g.

 

foreach($page->images_slider as $slide_image) {
   echo rtrim($slide_image->name,"{$slide_image->ext},.");
}

I haven't tested this much. I also cannot remember if ProcessWire allows dots in file names.

Share this post


Link to post
Share on other sites
1 hour ago, neophron said:

The image field is »array of items« with 0=no limit. And this is the code the template:


<?php
        foreach($page->images_slider as $slide_image) {
          $slide = $slide_image->size(0,700);
            echo "
              <li class='uk-width-3-4'>
                <img class='photo' src='{$slide->url}' alt='{$slide_image->basename}' height='700' />
              </li>

              ";
            }
        ?>

 

@neophron A solution about using filename as image alt info. You can try code below :

<?php
foreach($page->images_slider as $image) {
	$slide = $image->size(0,700);
	$alt = $image->description ?: str_replace('.' . $image->ext, '', $image->basename);

	echo "<li class='uk-width-3-4'>";
	echo "<img class='photo' src='{$slide->url}' alt='{$alt}' width='{$slide->width}' height='{$slide->height}' />";
	echo "</li>";
}
?>

 

  • Like 3
  • Thanks 1

Share this post


Link to post
Share on other sites

@neophron Always using this method may cause headache for you. What about add this method as property for each image field and use it like $imageField->alt. We need to add a hook method.

Add hook method to existing /site/ready.php or create new /site/ready.php, copy below code and paste it in to /site/ready.php :

/site/ready.php

<?php

namespace ProcessWire;

wire()->addHookProperty('Pageimage::alt', function(HookEvent $event) {
    /* @var $image Pageimage */
    $image = $event->object;
    $event->return = $image->description ?: str_replace('.' . $image->ext, '', $image->basename);
});

Usage ($imageField->alt) :

<?php
foreach($page->images_slider as $image) {
	$slide = $image->size(0,700);

	echo "<li class='uk-width-3-4'>";
	echo "<img class='photo' src='{$slide->url}' alt='{$image->alt}' width='{$slide->width}' height='{$slide->height}' />";
	echo "</li>";
}
?>

 

  • Like 2
  • Thanks 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By gregory
      Hi everyone.
      I can't see the PDF uploaded via a field called "pdf".
      I get a url like this: http://localhost:8888/mywebsite/site/assets/files/1129/test.pdf%EF%BB%BF%EF%BB%BF
      Could anyone help me? Thank you.
      <?php foreach($page->case_studies as $item) { if($item->type == 'contenuto') { echo " <a class='btn btn-primary btn-sm' target='blank' href='{$item->pdf->first()->url}' role='button'>Download</a> "; } } ?>  
    • By Robin S
      File Info
      A textformatter module for ProcessWire. The module can add information to local Pagefile links in two ways:
      As extra markup before, within or after the link As data attributes on the link (handy if you want to use a Javascript tooltip library, for instance) Screenshots
      Module config

      Example of output

      Installation
      Install the File Info module.
      Add the textformatter to one or more CKEditor fields.
      Configuration
      Add markup action (and general)
      Select "Add markup to links" Select the Pagefile attributes that will be retrieved. The attribute "filesizeStrCustom" is similar to the core "filesizeStr" attribute but allows for setting a custom number of decimal places. If you select the "modified" or "created" attributes then you can define a date format for the value. Enter a class string to add to the links if needed. Define the markup that will be added to the links. Surround Pagefile attribute names in {brackets}. Attributes must be selected in the "Pagefile attributes" section in order to be available in the added markup. If you want include a space character at the start or end of the markup then you'll need >= PW 3.0.128. Select where the markup should be added: prepended or appended within the link, before the link, or after the link. Add data attributes action
      Select "Add data attributes to links" Select the Pagefile attributes that will be retrieved. These attributes will be added to the file links as data attributes. Attributes with camelcase names will be converted to data attribute names that are all lowercase, i.e. filesizeStrCustom becomes data-filesizestrcustom. Hook
      If you want to customise or add to the attributes that are retrieved from the Pagefile you can hook TextformatterFileInfo::getFileAttributes(). For example:
      $wire->addHookAfter('TextformatterFileInfo::getFileAttributes', function(HookEvent $event) { $pagefile = $event->arguments(0); $page = $event->arguments(1); $field = $event->arguments(2); $attributes = $event->return; // Add a new attribute $attributes['sizeNote'] = $pagefile->filesize > 10000000 ? 'This file is pretty big' : 'This file is not so big'; $event->return = $attributes; });  
      https://github.com/Toutouwai/TextformatterFileInfo
      https://modules.processwire.com/modules/textformatter-file-info/
    • By Sergio
      Hi everyone,
      Yesterday I began working on a module to create a filesystem abstraction for files and images using the Flysytem library (http://flysystem.thephpleague.com), out of the necessity of having the images copied (and probably linked) on Amazon S3 and other places like Dropbox. There two reasons why I decided to tackle this:
      1 - When I work on the project in my machine, I need a way to automatically sync the images from the server and/or the external storage.
      When an image is added on the server and the database is imported on my local env, PW shows a blank thumbnail of it. The idea for the module if to check if the page image has a width == 0 and if it exists on the server, add it to the local filesystem.
      2 - In the past, I had to move a large website to a different server in a hurry and a lot of images were left behind (it was a mess). So I'm planning for a possible future worst-case scenario of the server exploding 🙂 
      The code I quickly wrote is below (please bear with me that it's pretty raw at the moment). One thing I had to figure it out is why PW fires the Pageimage::size hook wherever a page is loaded in the admin, even though the thumbnails are already created. I was planning to save the image variations on S3 as well. Can someone clarify?
      I know that @LostKobrakai was working on a similar project, and so I would like to ask him and everyone else if you think I (and who may help) should evolve this idea into a full-featured module where the user can select which server (adapter) to use (AWS, Digital Ocean spaces, Dropbox etc.)
      <?php namespace ProcessWire; use Aws\S3\S3Client; use League\Flysystem\AwsS3v3\AwsS3Adapter; use League\Flysystem\Filesystem; use League\Flysystem\Adapter\Local; use Spatie\Dropbox\Client; use Spatie\FlysystemDropbox\DropboxAdapter; class ProcessFly extends WireData implements Module, ConfigurableModule { public static function getModuleInfo() { return array( 'title' => 'ProcessWire Flysystem Integration', 'version' => 001, 'summary' => 'Synchronize all the page assets uploaded through PW to a specified bucket in Amazon S3 and...', 'author' => 'Sérgio Jardim', 'singular' => true, 'autoload' => true, 'icon' => 'image' ); } public function init() { $this->client = S3Client::factory([ 'credentials' => [ 'key' => '', 'secret' => '', ], 'region' => 'sa-east-1', 'version' => 'latest', ]); $this->bucket_name = ""; $this->dir_name = "images"; $this->s3_adapter = new AwsS3Adapter($this->client, $this->bucket_name, $this->dir_name); $this->s3_filesystem = new Filesystem($this->s3_adapter); // DROPBOX $this->authorizationToken = ""; $this->dropbox_client = new Client($this->authorizationToken); $this->adapter_dropbox = new DropboxAdapter($this->dropbox_client); $this->dropbox_filesystem = new Filesystem($this->adapter_dropbox); $this->addHookAfter('Pages::saved', $this, 'checkImageS3'); // Download images that are not in local filesystem for whatever reason but are available in the remove one. $this->addHookAfter('InputfieldFile::fileAdded', $this, 'uploadImageS3'); // Fired when a file/image is added to a page in the admin // $this->addHookAfter('Pageimage::size', $this, 'uploadImageS3'); // Fired when a file is resized via API. Note: this hook is also called when the page is loaded in Admin. Need to know why. $this->addHookAfter('Pageimage::url', $this, 'redirectImageURL'); //Replace image URL for the S3 path } public function redirectImageURL($event){ if($event->page->template == 'admin') return; else $event->return = "https://s3-sa-east-1.amazonaws.com/[bucket name]/images/" . $event->object->page . "/" . $event->object->name; } // UPLOAD public function uploadImageS3($event){ if(count($event->return)) { //if it is a image resize event get image variation data $file = $event->return; } else { $file = $event->arguments(0); } $filename = $file->name; $filename_original = $file->url; $pathToFile = $file->page . "/" . $filename; $system_path = $file->filename(); try{ $file_on_s3 = $this->s3_filesystem->has($pathToFile); //check if file exists on AWS if(!$file_on_s3) { $contents = file_get_contents($system_path); $this->s3_filesystem->put($pathToFile, $contents, array( 'visibility' => 'public', )); //upload file with the same folder structure as in assets/files: page_id/file_name //Also add a copy to Dropbox (OPTIONAL) $this->dropbox_filesystem->put($pathToFile, $contents); } } catch (Exception $e){ throw new WireException("Error: Image not Added to S3: {$e->getMessage()}"); } } public function checkImageS3($event){ $page = $event->arguments(0); if(count($page->images)) { foreach($page->images as $file) { if($file->width == 0) { return $this->downloadImageS3($page, $file); }; } } } public function downloadImageS3($page, $file){ $pathToFile = $page->id . "/" . $file->name; $file_on_s3 = $this->s3_filesystem->has($pathToFile); //check if file exists on AWS if($file_on_s3) { $image = "https://s3-sa-east-1.amazonaws.com/[bucket name]/images/" . $pathToFile; // $page->images->remove($image); $page->images->add($image); $page->save(); } else { throw new WireException("Error: Image not found on S3: {$file->name}"); } } }  
    • By rgaikema
      Hi all,
      Hopefully there's somebody who can help me with an issue while unzipping files.
      My goal is to show banners in a portfolio.
      In ProcessWire I have created a field, type 'Files', where I can upload the .zip files, one at a time.
      I've selected the option Decompress ZIP files, but any subfolder in the .zip somehow disappears.
      For example the 'assets' folder is gone after I uploaded the .zip file (see the attachment for the file structure).
      I'm curious, is there a way to preserve the file structure inside a .zip file after unzipping it?
       
      Kind regards,
      Remco

    • By Guy Incognito
      Hi all. We've created a private log-in area for a client on their site that is restricted on a roles basis. Is there a simple solution available to let them upload files to a file field and then choose individual users that can access individual files?
      Does that make sense?!... it's hard to search for answers to this as all results pertain to server file permissions.
       
×
×
  • Create New...