How to extract substrings with PHP - php

PHP beginner's question.
I need to keep image paths as following in the database for the admin backend.
../../../../assets/images/subfolder/myimage.jpg
However I need image paths as follows for the front-end.
assets/images/subfolder/myimage.jpg
What is the best way to change this by PHP?
I thought about substr(), but I am wondering if there is better ways.
Thanks in advance.

you should save your image path in an application variable and can access from both admin and frontend

If ../../../../ is fixed, then substr will work. If not, try something like this:
newpath=substr(strpos(path, "assets"));

It might seem like an odd choice at first but you could use ltrim. In the following example, all ../'s will be removed from the beginning of $path.
The dots in the second argument have to be escaped because PHP would treat them as a range otherwise.
$path = ltrim('../../../../assets/images/subfolder/myimage.jpg', '\\.\\./');
$path will then be:
assets/images/subfolder/myimage.jpg

I suggest this
$path = "../../../../assets/images/subfolder/myimage.jpg";
$root = "../../../../";
$root_len = strlen($root);
if(substr($path, 0, $root_len) == $root){
echo substr($path, $root_len);
} else {
//not comparable
}
In this way you have a sort of control on which directory to consider as root for your images

Related

php __FILE__ inside includes?

I have (maybe) an unusual issue with using __FILE__ in a file within a file.
I created a snippet of code (in the php 5 my server mandates) to take elements of the current filename and put it into a variable to use later. After some headache, I got it working totally fine. However, I realized I didn't want to have to write it every time and realized "oh no, if I include this it's only going to work on the literal filename of the include". If I wanted to grab the filename of the page the user is looking at, as opposed to the literal name of the included file, what's the best approach? Grab the URL from the address bar? Use a different magic variable?
EDIT1: Example
I probably should have provided an example in the first draft, pfft. Say I have numbered files, and the header where the include takes place in is 01header.php, but the file it's displayed in is Article0018.html. I used:
$bn = (int) filter_var(__FILE__, FILTER_SANITIZE_NUMBER_INT);
…to get the article number, but realized it would get the 1 in the header instead.
EDIT2: Temporary Solution
I've """solved""" the issue by creating a function to get the URL / URI and putting it into the variable $infile, and replaced all former appearances of __FILE__ with $infile, like so:
function getAddress() {
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];}
$infile = urlencode(getAddress());
$bn = (int) filter_var($infile, FILTER_SANITIZE_NUMBER_INT);
echo "$bn";
So if the file the user is looking at is called "005-extremelynormalfile.html", I can display the number 5 inside the page, e.g., to say it's article number five.
While it's not as bad as I initially thought based on your description your code is still very fragile, and really only works by accident. If you have any other digits or hyphens it's going to go wrong, as below.
$infile = 'https://example-123.com/foo/42/bar/005-extremelynormalfile.html?x=8&y=9';
var_dump(
filter_var($infile, FILTER_SANITIZE_NUMBER_INT),
(int)filter_var($infile, FILTER_SANITIZE_NUMBER_INT)
);
Output:
string(12) "-12342005-89"
int(-12342005)
Sanitize functions are a blunt instrument for destroying data, and should only ever be used as a last resort when all other good sense has failed.
You need to use a proper parsing function to parse the url into its component parts, and then a simple regular expression to get what you want out of the filename.
function getIdFromURL($url) {
$url_parts = parse_url($url);
$path = $url_parts['path'];
$path_parts = explode('/', $path);
$filename = end($path_parts);
if( preg_match('/^(\d+)/', $filename, $matches) ) {
return (int)$matches[1];
}
return null;
}
var_dump(
getIdFromURL($infile)
);
Lastly, a lot of people are tempted to cram as much logic as possible into a regular expression. If I wanted to the above could be a single regex, but it would also be rigid, unreadable, and unmaintainable. Use regular expressions sparingly, as there's nearly always a parser/library that already does what you want, or the majority of it.
Quickly threw together a function that gets the url from the page as a variable, and replaced all occurrences of __FILE__ with that variable, and it worked correctly. Assuming the user cannot edit the URL / URI in any way, this should work well enough.

Grabbing just the subfolder and filename from current page

I couldn't find another questions with the exact specs I'm needing here. So I'm posting this.
I need to use php to grab the url of the current page.
http//example.com/mysubfolder/filename.php
I need it to print out:
mysubfolder/filename
And if the filename.php has a get formula ?action=move or ?id=798 I would simply need to strip those portions off. The farthest I've seen in manuals will help to subtract only a specific portion of the .?action=doesntchangeathing
Most of what I have seen includes just the filename or a complete list of subfolders, not just one and would be using an absolute path rather than the url.
Anyone have any ideas?
You can use $_SERVER['PHP_SELF'] and cut filename extension and leading slash, so resulted expression may look something like this:
$path = implode('/', [trim(dirname($_SERVER['PHP_SELF']), '/'), pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME)]);

Delete files which has the same prefix

$prefix = 'something_prefix';
unlink($prefix.'.*');
the code above is not working, but I see some code like this below works just fine
unlink('*.jpg');
why? I am wonder is this going to work?
unlink('*.*');
how to delete the files which they begin with the same string? like this
same123.jpg
sametoo.png
samexxx.gif
they all begins with the string "same" but ends with different extension, how to do this?
I alread have a cheap way to do this, but I wonder if there is any better solution?
Try this code:
$mask = 'your_prefix_*.*';
array_map('unlink', glob($mask));
p.s. glob() requires PHP 4.3.0+
You can use glob for this. Something like this(didn't test it):
foreach (glob("something_prefix*.*") as $filename) {
unlink($filename);
}

How to add wildcard names to directory search in php

I've got a small php script that will gather all files in a directory. Futhermore, I'm cleaning through this array of names to skip over the ones I don't want:
$dirname = "./_images/border/";
$border_images = scandir($dirname);
$ignore = Array(".", "..");
foreach($border_images as $border){
if(!in_array($border, $ignore)) echo "TEST".$border;
}
This directory would contain images that I want to find. Amongst these images, there will be a thumbnail version and a full-size version of each image. I'm planning to have each image either labeled *-thumbnail or *-full to more easily sort through.
What I'm trying to find is a way to, preferably with the $ignore array, add a wildcard string that will be recognized by a check condition. For example, adding *-full in my $ignore array would make that files with this tag, anywhere in their filenames, would be ignored. I'm pretty sure the in_array wouldn't accept this. If this isn't possible, would using regular expressions be possible? If so, what would my expression be?
Thanks.
You're probably looking for php's function glob()
$files_full = glob('*-full.*');
There is a better way to do this known as glob().
Take a look at glob function.
glob — Find pathnames matching a pattern

PHP Parse INI File gives me error about equal sign

I'm trying to parse out an INI file that has a URL as one of the variables to parse. Problem is, the URL contains a '=' in it, and parse_ini_file spits out an error. I tried to escape the character, but to no avail. Does this happen to anybody else? And if so, has anybody fixed it?
Have you enclosed the value in quotes? It shouldn't be a problem to have = in the value as long as you have quotes around your value. Example:
key1="http://www.google.com?q=test";
much better would be use INI_SCANNER_RAW as 3rd parameter of parse_ini_file
parse_ini_file($file, true, INI_SCANNER_RAW);
I had the same problem and it drove me insane! The problem ended up being something silly ... I had created the .ini file in Windows, using a file that I renamed to .ini. Apparently there was some markup left which was seen by PHP, but not in my Notepad++.
I deleted the .ini and created one on my Linux host. This resolved the problem. If you're using WAMP or XAMPP on Windows, try to create a new file with just notepad, which disregards any markup.
I know this is an old topic, but I ended up here looking for the same problem, so it might help someone else.
Here is a quick solution to fix parse_ini_* problems with equality sign. You can use also regex, exploding arrays, etc.
function parseIniFile($file) {
if (!is_file($file)) return null;
$iniFileContent = file_get_contents($file);
return parseIniString($iniFileContent);
}
/* solves the equalitiy sign problem */
function parseIniString($iniFileContent==''){
$iniArray = array();
$iniFileContentArray = explode("\n", $iniFileContent);
foreach ($iniFileContentArray as $iniFileContentArrayRow){
$iniArrayKey = substr($iniFileContentArrayRow, 0, strpos($iniFileContentArrayRow, '='));
$iniArrayValue = substr($iniFileContentArrayRow, (strpos($iniFileContentArrayRow, '=')+1));
$iniArray[$iniArrayKey] = $iniArrayValue;
}
return $iniArray;
}

Categories