exploding a string with variable - php

I'm trying to manipulate a path to an image using php.
The path has a variable userdirectory in it, so i'm struggling with how to write this.
Ive used to do :
$texthtml = $content;
if (preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $texthtml, $image) ) {
$promopic = $image['src'];
}
to find if there is an image in my content and make a variable out of it. that works, but i need to alter my code to load image from a thumbnail directory for pageload reasons.
an image src looks like this : "/uploads/userdirs/admin(variable)/image.jpg"
But i want it to be this :
"/uploads/userdirs/admin(variable)/mcith/mcith_image.jpg"
adding a /mcith/ and a mcith_prefix to the image.
I'm thinking exploding it, but i dont know how to do that with a variable path. Any pointers greatly appreciated!

You can do this many different ways, but I would probably use pathinfo() for this:
$path = pathinfo($promopic);
$thumb = $path['dirname'] . '/mcith/mcith_' . $path['basename'];

very simple version, could use improvement
preg_replace('/\/([a-zA-Z0-9]+\.[a-zA-Z0-9]{3,4})$/', '/mcith/mcith_$1', '/uploads/userdirs/admin(variable)/image.jpg');

Related

Set img src without knowing extension

So I have a few images in the server (public_html/img/profile_pictures/).
This is how I currently set the image:
echo "<img src='img/profile_pictures/main_photo.png'/>";
The main_photo can change each day, but if it changes to main_photo.jpg insted, it wont show (because the extension is hardcoded on that line(.png)). Is it possible to display the photo without knowing the extension for the image file?
If you want a PHP code, then try this. This code will look for main_photo.* inside your folder and automatically set the extension upon finding one.
Remember to set the path properly
<?php
$yourPhotoPath = "img/profile_pictures/";
foreach (glob($yourPhotoPath.'main_photo.*') as $filename) {
$pathInfo = pathinfo($filename);
$extension = $pathInfo['extension'];
$fileName = chop($pathInfo['basename'], $extension);
echo "<img src='".$yourPhotoPath.$fileName.$extension."'/>";
}
?>
if a Photo isn't loaded, it's width and size is null.
Although I would advise you to write a class that checks and loads images, I get a feeling you want a simple solution. so, given by the premise that the photo is either
<img src='img/profile_pictures/main_photo.png'/>
or
<img src='img/profile_pictures/main_photo.jpg'/>
and that neither this path nor this filename ever changes and in the folder is only one picture,
you could simply echo both.
The img of the one that is empty will not be shown.
A better way was to write a class that loads your photo and checks if the photo is really there, like
$path = 'img/profile_pictures/main_photo.png';
if(!file_exists('img/profile_pictures/main_photo.png'))
{
//use the jpg path
$path = 'img/profile_pictures/main_photo.jpg';
}
You can ofc just inline this if case, but it's bad practise to intermix buisinesslogic and format logic, so I advice you to write a class for it.

Saving image file name exactly as URL image file into folder in PHP

I have visited this article previously and found it useful, but i would like to add more functionality to it by having it save an image file name according to the URL name.
This is what I've done so far and it works.
$contents=file_get_contents('http://www.domain.com/logo.png');
$save_path="C:/xampp/htdocs/proj1/download/[logo.png]";
file_put_contents($save_path,$contents);
Basically, where I have put square brackets around I want to have that dynamic based on the URL file name. For example, if i have an image url such as this: https://cf.dropboxstatic.com/static/images/brand/glyph-vflK-Wlfk.png, I would like it to save the image into the directory with that exact image name which in this case is glyph-vflK-Wlfk.png.
Is this possible to do?
I would do this way
$url = "http://www.domain.com/logo.png";
$file = file_get_contents($url);
$path = "C:/xampp/htdocs/proj1/download/". basename($url);
return !file_exists($path) ? file_put_contents($path, $file) : false;
From what I understand, what you're trying to do is the following :
$url = 'http://www.domain.com/logo.png';
$contents=file_get_contents($url);
$posSlash = strrpos($url,'/')+1);
$fileName = substr($url,$posSlash);
$save_path="C:/xampp/htdocs/proj1/download/".$fileName;
file_put_contents($save_path,$contents);
There is a function for that, basename():
$url="http://www.domain.com/logo.png";
$contents=file_get_contents($url);
$save_path="C:/xampp/htdocs/proj1/download/".basename($url);
file_put_contents($save_path,$contents);
You might want to check if it already exists with file_exists().

Pull Images & Thumbnails from a Folder Through PHP

I'm trying to generate images on my website by pulling a thumbnail from one folder and the actual image from another. I have no idea what I am doing. This is what I have so far:
<?php
$thumbdirname = "images/thumbs/";
$imgdirname = "images/";
$mainimages = glob($imgdirname."*.{jpg,png,gif}", GLOB_BRACE);
$imagethumbs = glob($thumbdirname."*.{jpg,png,gif}", GLOB_BRACE);
foreach($imagethumbs as $image) {
echo '<a class="imageLink" href="$mainimages" data-lightbox="logo" data-title="Vivid Logo"><img src="'.$image.'"</a> ';
}
?>
I know that it will not work with just "$mainimages" for href, but I haven't been able to figure out what to put there. As is, it will pull up the right thumbnail, but not link to the full associated image.
I tried to put another foreach statement in, but I get four results from my two pictures (and their thumbnails). Which makes sense sense it is showing one of each combination:
(img1,thumb1),(img1,thumb2),(img2,thumb1),(img2,thumb2)
How should I change this to get it playing nicely?
You don't seem to be outputting from $mainimages so I'm going to ignore this for now.
You PHP code seems to be OK from initial glance. Only thing that is a bit iffy is that you are not closing you image tag.
If that does not help try counting the image array/object.
If that returns 0 try the below code.
// Find all files in that folder
$files = glob('images/gallery1/*');
// Display images
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}
Hope that helps

Delete specific filenames in an array using PHP

I have a list of PDFs and I would like to delete them. Can someone please explain to a beginner how this is done? At this point, I can do this in Excel a number of different ways but how can I simply do this in PHP?
Most simple solution:
<?php
$dir = '/files_directory/';
$files_to_delete = array('file1.pdf', 'file3.pdf', 'file4.pdf');
foreach($files_to_delete as $file)
{
$file_path = $dir . $file;
if(is_file($file_path))
{
unlink($file_path);
}
}
Use PHP to search for the folder, do a loop through the files there and add some conditional statements to the loop. If they are true or false, act on those results.
As you have not typed any code for us, I am not going to type any code back to you.
The most simple way I could think of doing it:
array_map('unlink', $array_with_files_to_delete);
$array_with_files_to_keep = array_diff($list_with_pdfs, $array_with_files_to_delete);

TCPDF cant image because it is using a wrong directory path

I get my images in my pdf document on my localhost but on the production site i get the error TCPDF ERROR: [Image] Unable to get image i am using an html img tag to get the images and the src is the directory path to this image not a url, but i found out that TCPDF is adding the path i give it with the path to my www folder like:
path to picture i give to tcpdf: home/inc_dir/img/pic.jpg
tcpdf looks for it here: home/www/home/inc_dir/pic.jpg
can someone please help me find out tcpdf is concatenating the directories?
You can also change only the image path instead of main path use:
define('K_PATH_IMAGES', '/path/to/images/');
require_once('tcpdf.php');
This won't break fonts/ and other tcpdf paths.
TCPDF is using $_SERVER['DOCUMENT_ROOT'] as a root directory of all your images, and builds their absolute paths in relation to it. You can change it either in $_SERVER or with this PHP constant: K_PATH_MAIN:
define('K_PATH_MAIN', '/path/to/my-images/');
require_once 'tcpdf.php';
I use image data instead of paths. It can be passed to TCPDF using an # in the image's src-attribute, like so:
<img src="#<?php echo base64_encode('/path/to/image.png')?>" />
An img-tag in HTML takes a BASE64 encoded string, unlike the Image() function, which takes unencoded data.
I don't know if this is even documented, I found this by reading the code (tcpdf.php, line 18824 pp):
if ($imgsrc[0] === '#') {
// data stream
$imgsrc = '#'.base64_decode(substr($imgsrc, 1));
$type = '';
}
I have got the same problem. But it is now resolved.
I have change the code of TCPDF.php from
Old Code
if ($tag['attribute']['src'][0] == '/') {
$tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
}
$tag['attribute']['src'] = urldecode($tag['attribute']['src']);
$tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
New Code
if ($tag['attribute']['src'][0] == '/') {
$tag['attribute']['src'] = $_SERVER['DOCUMENT_ROOT'].$tag['attribute']['src'];
$tag['attribute']['src'] = urldecode($tag['attribute']['src']);
$tag['attribute']['src'] = str_replace(K_PATH_URL, K_PATH_MAIN, $tag['attribute']['src']);
}
Please try this.

Categories