file_put_contents and image url whitespaces - php

I have a problem with getting image from url. I'm using file_put_contents and I found that problem is white spaces in image url because images without any whitespace working.
The URL I'm getting image looks that:
/support/member_profile/16-New%20Image%20(With%20Logo)%20(Medium).jpg
I tried with urlencode() but it's still not working. If I echo encoded url I get:
%2Fsupport%2Fmember_profile%2F16-New+Image+%28With+Logo%29+%28Medium%29.jpg
How can I solve that problem? Thanks in advance
EDIT:
I figured out that I would need to replace ONLY whitespaces with %20. When using urlencode it encode entire URL so that's why it's not working.
Any tip how to do it? Thanks

Use urldecode to convert %20 into real spaces.
Then you can call file_put_contents.

You should only URL-encode the filename, not the entire path including the slashes:
$path = '/support/member_profile/16-New Image (With Logo) (Medium).jpg';
$p = pathinfo($path, PATHINFO_DIRNAME);
$f = pathinfo($path, PATHINFO_FILENAME);
$e = pathinfo($path, PATHINFO_EXTENSION);
echo sprintf('%s/%s.%s', $p, urlencode($f), urlencode($e));
And, actually, you need to urlencode each path-part as well.
$path = '/support/member profile/16-New Image (With Logo) (Medium).jpg';
$p = explode('/', $path);
foreach ($p as $pp)
$pathparts[] = urlencode($pp);
echo implode('/', $pathparts);

Related

PHP: How to explode string

I have a variable that stores the location of a temp file:
$file = 'C:\xampp\htdocs\temp\filename.tmp';
How can I explode all this to get filename (without the path and extension)?
Thanks.
Is not the best code but if you confident that this path will be similar and just file name will be different you can use this code:
$str = 'C:\xampp\htdocs\temp\filename.tmp';
$arrayExplode = explode("\\", $str);
$file = $arrayExplode[count($arrayExplode)-1];
$filename = explode('.', $file);
$filename = $filename[0];
echo $filename;
Advice: Watch out on the path contain "n" like the first letter after the backslash. It could destroy your array.
You should use the basename function, it's meant specifically for that.

str_replace not working in my php string

I want to remove a special character from a string in my php page, for that I use str_replace() function. But it does't work for my script. The string is getting from server. I am using the following php code to replace that string.
$path= "catalog\/demo\/samsung_tab_1.jpg";
$newPath = str_replace("\/","/",$path);
But the above str_replace() function is not working properly in my script.
I want to get the output like,
catalog/demo/samsung_tab_1.jpg
Please help.
Instead of \/ you can remove forward slash by using double backslashes:
<?php
$path= "catalog\/demo\/samsung_tab_1.jpg";
$newPath = str_replace("\\","",$path); // replace with empty string ""
echo $newPath; // catalog/demo/samsung_tab_1.jpg
?>
<?php
$path= "catalog\/demo\/samsung_tab_1.jpg";
if (preg_match('/\//', $path)){
echo $newPath = str_replace("\/","/",$path);
}else{
echo $newPath = $path;
}
?>
I hope this will work for you.

PHP urlencode - encode only the filename and dont touch the slashes

http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip
urlencode($myurl);
The problem is that urlencode will also encode the slashes which makes the URL unusable. How can i encode just the last filename ?
Try this:
$str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$pos = strrpos($str, '/') + 1;
$result = substr($str, 0, $pos) . urlencode(substr($str, $pos));
You're looking for the last occurrence of the slash sign. The part before it is ok so just copy that. And urlencode the rest.
First of all, here's why you should be using rawurlencode instead of urlencode.
To answer your question, instead of searching for a needle in a haystack and risking not encoding other possible special characters in your URL, just encode the whole thing and then fix the slashes (and colon).
<?php
$myurl = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$myurl = rawurlencode($myurl);
$myurl = str_replace('%3A',':',str_replace('%2F','/',$myurl));
Results in this:
http://www.example.com/some_folder/some%20file%20%5Bthat%5D%20needs%20%22to%22%20be%20%28encoded%29.zip
Pull the filename off and escape it.
$temp = explode('/', $myurl);
$filename = array_pop($temp);
$newFileName = urlencode($filename);
$myNewUrl = implode('/', array_push($newFileName));
Similar to #Jeff Puckett's answer but as a function with arrays as replacements:
function urlencode_url($url) {
return str_replace(['%3A','%2F'], [':', '/'], rawurlencode($url));
}

get filename with pure extension

I'm coding a script to get image from a site. All is good, but then I notice there are some sites which have images in format like this:
http://site-name/images/dude-i-m-batman.jpg?1414151413
http://site-name/images/dude-i-m-batman.jpg?w=300
right now I'm dealing with it by doing
$file = substr($media,0, strrpos($image, '.') + 4);
I'm just wondering whether it's a good practice or there's a better way.
I've tried pathinfo and a couple other methods, but all return extension with the query string.
Thanks
Parse the URL with parse_url, retrieve the path part:
$datum = parse_url($url);
$parts = pathinfo($datum['path']);
$ext = $parts['extension'];
You may also use getImageInfo($full_url), if fopen_wrappers allow it, and retrieve image info such as width, height, and most importantly, mime_type.
This because you will find several files without extension or with the wrong one, put there to trick browsers into downloading as image and trusting that the browser will recognize the image format nonetheless (been there, done that :-( )
I'm unsure whether you mean you want the extension or (judging from your current code) the full path (minus any query string).
Here's both:
$file = "http://site-name/images/dude-i-m-batman.jpg?1414151413";
preg_match('/^([^\?]+)(?:\?.*)?/', $file, $path_noQS);
preg_match('/(?<=\.)(\w{2,5})(?:\?.*)?/', $file, $extension);
echo $path_noQS[1]; //path, without QS
echo $extension[1]; //extension
Obviously what you do now has some shortcomings. One of them you already noticed your own:
Not all URLs end with the file-extension.
Not all file-extensions are of three letters (e.g. .jpeg)
So what you want is to get the path from a URL:
$imagePath = parse_url($imageUrl, PHP_URL_PATH);
And then you want to get the extension from that path:
$imageName = pathinfo($imagePath, PATHINFO_EXTENSION);
And done. You're not the first who needs that, so functions already exist for the job.
Your solution only works with 3 character extensions. If you know all the extensions will be 3 characters than yours is a perfectly viable solution. Otherwise:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
This should definitely work if you have the correct file name
If for some reason that doesn't work, you can use this:
$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];
may be something like this
$parsedUrl = parse_url('http://site-name/images/dude-i-m-batman.jpg?1414151413');
$parsedFileInfo = pathinfo($parsedUrl['path']);
echo $parsedFileInfo['extension'];
http://codepad.org/KXZwKCjs
$u = 'http://site-name/images/dude-i-m-batman.zip.jpg?1414151413?1234';
$u = explode('?', $u, 2 ); // ignore everything after the first question mark
$ext = end(explode('.',$u[0])); // last 'extension'

PHP removing text in a link

How do you strip/remove wording in PHP?
I have a form that's passing a full URL link to an output page.
Example:
maps/africa.pdf
And on the output page, I want to provide an "href link", but in PHP use that same posted URL, but strip off the "maps" and have it provide a link that just says africa.
Example:
africa
can this be done?
Thanks!
Use pathinfo:
$filename = 'maps/africa.pdf';
$title = pathinfo($filename, PATHINFO_FILENAME);
If you want only .pdf to be stripped, use basename:
$filename = 'maps/africa.pdf';
$title = basename($filename, '.pdf');
$string = 'maps/africa.pdf';
$link_title = str_replace(array('maps/', '.pdf'), '', $string);
So you just want the file name? If so, then that would be everything between the last slash and the last dot.
if (preg_match("#/([^/]+)\\.[^\\./]+$#", $href, $matches)) {
$linkText = $matches[1];
}
Some good answers here. Also, if you know the url every time you could count the characters and use substr() e.g. http://uk3.php.net/substr
$rest = substr("abcdef", 2, -1); // returns "cde"

Categories