that might be something strange when I say that I want to encode a URL partially, But I am caught in this situation and it seems that I got no other solution...
here is my code snippet
$url = isset($_GET['u']) ? esc_url($_GET['u']) : '';
$image = isset($_GET['i']) ? $_GET['i'] : '';
maybeappend = '<a href="?ajax=photo_thickbox&i=' + encodeURIComponent(img.src) +
'&u=<?php echo urlencode($url); ?>&height=400&width=500" title=""
class="thickbox"><img src="' + img.src + '" ' + img_attr + '/></a>';
its taken from wordpress /wp-admin/press-this.php
the issue is, I cant post to my site via Press this bookmarklet
I searched the google, studied the wordpress forums and found that I need to tweek Press this button in my bookmark tool bar in broswer..
but for me, that is not a solution,,why? obviously, I cant teach every visitor to do this change in their broswer..so I have to edit my code residing on server...
how can I edit encodeURIComponent(img.src) and <?php echo urlencode($url); ?> so it DOES NOT ENCODE HTTP:// part of url,
say I got a url 'http://www.google.com I want it to be encoded as www.google.com
any suggesion?
How can I achieve my goal? might be some regex ? (dont know regex :( )
what would be the code adjustment for this??
thanks for your help..
First remove the http part using substr, then apply urlencode and then reattacht the http part.
Same method can be applied in JavaScript using the equivalent JavaScript functions.
$encoded = 'http://' . urlencode(substr($url, -7));
You could indeed use a regex to filter the http:// part of the url (which is, if I understood well, what you want to do).
Something like https?://(.*) should select the part of the url you want (the s? part takes into account potential secure links).
You'll want to make sure any matching strings are at the beginning of the strings
Javascript
Use String.replace with regex:
url.replace( /^(http|https):\/\//, '' );
^ means start of the string
PHP
Use str_replace(): php.net/str_replace
if( strpos( $url, 'http' ) == 0 ){
str_replace( array( 'http://', 'https://'), '', $url, 1 );
}
strpos can also return a FALSE so make sure you use ==.
Related
As a novice and beginner php learner, I'm using the Code-Canyon Premium URL Shortner script and done 2 days of research. Unfortunately I am unable to resolve my issue.
The url shorten script is urlencoding the API url that it sends to the script, In doing this it is replacing the & symbols with & causing the url to not work correctly on the final destination page.
I have tried to use preg_replace, str_replace and also tried to use urldecode on the destination page but none of these seem to work. Here is my current script:
$makeshort = "http://mywebsite.com/email/quote.php?quoteid=$visitor&customertype=fhbs";
$mkshrt = str_replace("/&/","%26",$makeshort);
$short = "http://shorturl.com/api?&api=REMOVED&format=text&url=".urlencode($mkshrt);
// Using Plain Text Response
$api_url = $short;
$res= #file_get_contents($api_url);
if($res)
$shorturl = $res;
$shorty = json_decode($shorturl);
$shorturl = $shorty->{'short'};
echo $shorturl;
Note: Where you see &format=text in the api url, I have tried to use it with and without the &format=text however this makes no difference what so ever.
I am hoping that there could be a simple and quick way to resolve this issue as I am only passing over 2 variables and its the second variable that is being displayed like this:
mywebsite.com/email/quote.php?quoteid=01234567890&customertype=fhbs
So the customertype variable is the one being messed up due to the amp; symbol.
I sincerely hope someone with the expertise could advise me on the best approach or even a simple way to resolve this issues as I really am at my whits end! MY knowledge is not good enough to research the exact key phrases in order to point myself in the right direction.
Thanks for your time in reading this and I hope someone would be kind enough to help me out here.
I know the feeling as i myself am just becoming to terms with coding and developing.
I personally would solve this by one of two ways, If you have tried to already use htmlspecialchars or htmlentities along with urldecode then the most simple and quickest way to achieve this would be to read the URL string then replace the &symbol with the & using str_replace and do either a meta refresh of the page or `header location redirect
Here is what i mean with a breif example however one must stress that some extra security maybe needed and this is ONLY a quick fix not a secure stable and permanent fix, Though one could play with this and maybe work something out for your own circumstances.
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(strstr($url, "&")){
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$url = str_replace('&', '&', $url);
echo "<meta http-equiv='refresh' content='0;URL=$url'>";
exit;
}
Alternative way with header location:
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(strstr($url, "&")){
$url = "http://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$url = str_replace('&', '&', $url);
header("Location: $url");
exit();
}
This will totally remove any & symbols from the url and replace them with &.
You can also play around with this to remove even more from the url string and replace things like / or forbidden words.
An example of the output will look like this:
Original url causing the problems:
http://mywebsite.com/email/quote.php?quoteid=1234567890&customertype=fhbs
New url after the script has executed and refreshed the page:
http://mywebsite.com/email/quote.php?quoteid=1234567890&customertype=fhbs
As you can see from the hyperlinked text above, The ampersand breaks the string and everything after that is not read correctly but when this script executes and refreshes the page the url will be just like the second hyperlink thus making the url work for what you require.
NOTE: THIS IS NOT A SECURE WAY OF DOING THINGS AND MAY NO BE IDEAL FOR YOUR CIRCUMSTANCES, THIS IS JUST AN IDEA AND HOPE THIS HELPS!
Thanks.
I need to automatically parse a string and find if a link to my site is present, automatically replace the address by a clickeable HTML link.
Supposing my site adresses are www.mysite.com + wap.mysite.com + m.mysite.com, I need to convert:
My pictures at m.mysite.com/user/id are great.
to:
My pictures at mysite.com/user/id are great.
The question is how to do this (with ereg_replace?) instead of using tons of lines of code.
Notice that the result must be a relative URL, so that the current protocol and subdomain is used for the target link. If the user is in the m subdomain of the HTTPS version, the target will be the m subdomain of the HTTPS protocol and so on. Only links to mysite.com must be linked, any other links must be treated as ordinary plain text. Thanks in advance!
First piece of advice, stay away from ereg, it's been deprecated for a long time. Second, you can probably google and experiment to concoct a preg expression that works well for you, so tweak what I have here to suit your needs.
I was able to put together a fairly simple regex pattern to search for the URLs.
preg_match("/m.mysite.com\S+/", $str, $matches);
Once you have the URLs, I'd suggest parse_url instead of regex.
And here is the code
$sSampleInput = 'My pictures at http://m.mysite.com/user/id are great.';
// Search for URLs but don't look for the scheme, we'll add that later
preg_match("/m.mysite.com\S+/", $sSampleInput, $aMatches);
$aResults = array();
foreach($aMatches as $sUrl) {
// Tack a scheme afront the URL
$sUrl = 'http://' . $sUrl;
// Try validating the URL, requiring host & path
if(!filter_var(
$sUrl,
FILTER_VALIDATE_URL,
FILTER_FLAG_HOST_REQUIRED|FILTER_FLAG_PATH_REQUIRED)) {
trigger_error('Invalid URL: ' . $sUrl . PHP_EOL);
continue;
} else
$aResults[] =
'<a href="' . parse_url($sUrl, PHP_URL_PATH) .
'" target="_blank">' . $sUrl . '</a>';
}
Trying to use a $_GET['url'] variable to grab data from a URL:
http://mysite.com/?url=http://this.is/?q=an&?example=url
What I want above is bolded, but sadly the $_GET['url'] will only get "http:// this.is/?q=an" because the & makes it interpret it as the beginning of a new variable within the URL.
Is there a way to ignore the ampersands so my script can get the entire URL I need it to? The URL that is appended to ?url= is not within my limits to control so most work but some do contain the dreaded &. After reading questions on Stack Overflow I'm not holding out much hope :(
If you have absolutely no control over the arguments placed on the query string (for whatever reason), you can also do this by manually parsing the $_SERVER['QUERY_STRING'] varible, e.g.
$page = str_replace("url=", "", $_SERVER['QUERY_STRING']);
Of course, if possible, you should encode it using the answers posted by everyone else.
Use urlencode()
$get_url = urlencode('http://this.is/?q=an&?example=url');
$url = 'http://mysite.com/?url=' . $get_url;
If you can't control the query string, you could use
$query = $_SERVER['QUERY_STRING'];
$pos = strpos($query, "url=");
if ($pos !== false) {
$url = substr($query, $pos + 4);
}
This code returns everthing after url=
If you have the possibility,you should encode the url with urlencode to create a clean url.
If you don't do this, you get eventually an server error, with strange urls and you can't pass more than one url(because everything after the url= is interpreted as url)
Here is the tested code:
if (!empty($_GET['url'])) {
echo $_GET['url'].'<br />';
}
$url = urlencode('http://this.is/?q=an&?example=url');
echo 'LINK';
Hope it will help you.
I'm developing a web app where users enter their facebook page url either in this format:
http://www.facebook.com/pages/Graffiti/119622954518
or
http://www.facebook.com/thefirkinandfox
With php - how do I detect which format automatically, then split (explode?) the parts (the slug and the id or just the slug if the second version).
There is sometimes query data at the end of the url when viewing your own facebook page as an administrator, how do I detect and remove that? I think the answer will be regex of some kind - but I've really only used this to make sure an input is email and still didn't understand it that well... thanks in advance.
Possible entires may or may not include http:// at the beginning... I'd like to account for this...
If you want to use one regexp, try this:
$url = 'www.facebook.com/pages/Graffiti/119622954518';
if(preg_match('#^(https?://)?(www\.)?facebook\.com/((pages/([^/]+)/(\d+))|([^/]+))#', $url, $matches)) {
$slug = isset($matches[5]) ? $matches[5] : (isset($matches[7]) ? $matches[7] : null);
$id = isset($matches[6]) ? $matches[6] : null;
}
Two parts:
^http://www.facebook.com/pages/([^/]+)/([^/]+)(?:\?.*)$
If the first one doesn't match, use this:
^http://www.facebook.com/([^/]+)(?:\?.*)$
The explosion, you mention is the value of the capturing group.
So the code might look something like this:
$subject = "my string";
if (preg_match ('#^http://www.facebook.com/pages/([^/]+)/([^/]+)(?:\?.*)$#', $subject))
print ($groups[1] + ' ' + $groups[1]);
else if (preg_match ('#^http://www.facebook.com/([^/]+)(?:\?.*)$#', $subject))
print ($groups[1]);
I am trying to fetch a variable address from my current URL using JRequest::getVar('address') method.
But if the address value has a (#) character, the part after the # character is not retrieved.
I understand that URI is a combination of query + fragment and the part after a hash symbol is treated as a fragment.
I have tried to use urlencode method but it still doesn't solve the problem.
Can anyone please tell me how to solve the issue?
What is the problem with using urlencode? It should replace # with %23 and all should be well. You can try JRequest::getVar(str_replace('#', '%23', 'address')) which should do the trick. Can you post an example URL that doesn't get properly urlencoded?
I guess you will have to replace the hash-symbol on your own. For example:
str_replace($the_url, '#', '-');
I don't know, where exactly you have to do that, because I don't know how the Joomla!-Framework handles links and urls. But I am sure, that someone else can help here any further...
Encode the Hash in the URL with a %23 replacement
http://twitter.com/home?status=I+believe+in+%23love
"I believe in #love"
The part after # is never sent to Apache/PHP, and can therefore not be retrieved by a PHP script. What you need to do, is to url encode the ADDRESS parameter of the URL.
test.com/index.php?ADDRESS=<?= urlencode('101 Street #6 City') ?>
That code will generate the following url
test.com/index.php?ADDRESS=101+Street+%236+City
Now on this URL, you can retrieve address with JRequest::getVar('ADDRESS')
Check this Joomla doc out. You can retrieve what Joomla call the 'fragment' by doing:
$uri = 'http://fredbloggs:itsasecret#www.example.com:8080/path/to/Joomla/index.php?task=view&id=32#anchorthis';
$u =& JURI::getInstance( $uri );
echo 'Fragment is ' . $u->getFragment();