Share PHP GD-created image on Facebook - php

Using the PHP GD image library I have successfully outputted an image with text from url parameters (a, b, c).
I need to be able to send these images to the Facebook sharing url so that they can be sent to social media.
https://www.facebook.com/sharer/sharer.php?u=http://example.com/script.php?a=1&b=2&c=3
However, the sharing link does not seem to accept my php parameters. When I test the url, it pulls the image but does not send any numbers resulting in no text carried through.
Is there a way to save the complete image with parameters and have it sent to the Facebook sharing url? I am doing this through a link embedded in email, so it cannot use anything more complicated than basic HTML.

You'll likely need to encode your url such that the ?, = and & aren't read by facebooks php script.
See here for details of encoding.
? is %3F, = is %3D and & is %26
So your url would be :
https://www.facebook.com/sharer/sharer.php?u=http://example.com/script.php%3Fa%3D1%26b%3D2%26c%3D3
Note: I've not tested this as I don't want to post to facebook :)

So I did eventually end up solving this. After giving up on pushing a php image to Facebook with url parameters included, I attempted to place the image into an email. This worked well in nearly every client EXCEPT Gmail. I had to convert the url parameters to get around the Gmail proxy which allowed the image to be displayed AND it also happened to now be usable in the Facebook sharer. Double hooray!
The original way I had it set up was to link the php image with url parameters and use $_GET to place them on the image:
script-wrong.php
$var1 = $_GET['a'];
$var2 = $_GET['b'];
$var3 = $_GET['c'];
The correct way to do this is the following:
script.php
$uri = $_SERVER['REQUEST_URI'];
$path = substr($uri, strpos($uri, "a=")); // start your url parameters here
$delim = 'abc=&'; // enter all characters you use in parameters (a, b, c, =, &)
$tok = strtok($path, $delim);
$tokens = array();
while ($tok !== false) {
array_push($tokens, $tok);
$tok = strtok($delim);
}
$var1 = $tokens[0];
$var2 = $tokens[1];
$var3 = $tokens[2];
What this does is look at the url and pull specified characters ($delim) from it to place into an array. Then using what follows those characters, set their value to a token and place that token on the image.
Here is how I set up my php image to display in the email:
<img src="http://example.com/script.php/a=1&b=2&c=3">
And my share URL:
https://www.facebook.com/sharer/sharer.php?u=http://example.com/script.php/a=1%26b=2%26c=3

Related

Reduce link (URL) size

Is it possible to reduce the size of a link (in text form) by PHP or JS?
E.g. I might have links like these:
http://www.example.com/index.html <- Redirects to the root
http://www.example.com/folder1/page.html?start=true <- Redirects to page.html
http://www.example.com/folder1/page.html?start=false <- Redirects to page.html?start=false
The purpose is to find out, if the link can be shortened and still point to the same location. In these examples the first two links can be reduces, because the first points to the root, and the second has parameters that can be omitted.
The third link is then the case, where the parameters can't be omitted, meaning that it can't be reduced further than to remove the http://.
So the above links would be reduced like this:
Before: http://www.example.com/index.html
After: www.example.com
Before: http://www.example.com/folder1/page.html?start=true
After: www.example.com/folder1/page.html
Before: http://www.example.com/folder1/page.html?start=false
After: www.example.com/folder1/page.html?start=false
Is this possible by PHP or JS?
Note:
www.example.com is not a domain I own or have access to besides through the URL. The links are potentially unknown, and I'm looking for something like an automatic link shortener that can work by getting the URL and nothing else.
Actually I was thinking of something like a linkchecker that could check if the link works before and after the automatic trim, and if it doesn't then the check will be done again at a less trimmed version of the link. But that seemed like overkill...
Since you want to do this automatically, and you don't know how the parameters change the behaviour, you will have to do this by trial and error: Try to remove parts from an URL, and see if the server responds with a different page.
In the simplest case this could work somehow like this:
<?php
$originalUrl = "http://stackoverflow.com/questions/14135342/reduce-link-url-size";
$originalContent = file_get_contents($originalUrl);
$trimmedUrl = $originalUrl;
while($trimmedUrl) {
$trialUrl = dirname($trimmedUrl);
$trialContent = file_get_contents($trialUrl);
if ($trialContent == $originalContent) {
$trimmedUrl = $trialUrl;
} else {
break;
}
}
echo "Shortest equivalent URL: " . $trimmedUrl;
// output: Shortest equivalent URL: http://stackoverflow.com/questions/14135342
?>
For your usage scenario, your code would be a bit more complicated, as you would have to test for each parameter in turn to see if it is necessary. For a starting point, see the parse_url() and parse_str() functions.
A word of caution: this code is very slow, as it will perform lots of queries to every URL you want to shorten. Also, it will likely fail to shorten many URLs because the server might include stuff like timestamps in the response. This makes the problem very hard, and that's the reason why companies like google have many engineers that think about stuff like this :).
Yea, that's possible:
JS:
var url = 'http://www.example.com/folder1/page.html?start=true';
url = url.replace('http://','').replace('?start=true','').replace('/index.html','');
php:
$url = 'http://www.example.com/folder1/page.html?start=true';
$url = str_replace(array('http://', '?start=true', '/index.html'), "", $url);
(Each item in the array() will be replaced with "")
Here is a JS for you.
function trimURL(url, trimToRoot, trimParam){
var myRegexp = /(http:\/\/|https:\/\/)(.*)/g;
var match = myRegexp.exec(url);
url = match[2];
//alert(url); // www.google.com
if(trimParam===true){
url = url.split('?')[0];
}
if(trimToRoot === true){
url = url.split('/')[0];
}
return url
}
alert(trimURL('https://www.google.com/one/two.php?f=1'));
alert(trimURL('https://www.google.com/one/two.php?f=1', true));
alert(trimURL('https://www.google.com/one/two.php?f=1', false, true));
Fiddle: http://jsfiddle.net/5aRpQ/

How can I determine if a vimeo URL is a video? PHP

So I've been using this simple method to determine whether or not a URL is from vimeo
if (preg_match("/vimeo/",$url)) {
$getvim = (parse_url($url));
$vimid = str_replace("/", "", $getvim['path']);
}
As you can see this simply determines if the url contains "vimeo" then grabs the video id by grabbing everything after the slash. Works fine if you're actually linking a vimeo video, however utterly messes everything up if the link just contains "vimeo" without actually being a vimeo link.
Does anyone have a better method of doing this? There are tons of YouTube solutions available but finding a good vimeo one has been nearly impossible. Any help with this is appreciated, thank you.
Try this code:
$urls = parse_url($url);
if ($urls['host'] == 'vimeo.com'){
$vimid = ltrim($urls['path'], '/');
if (is_numeric($vimid)) {
// do something with $vimid
}
}
We assume that all video IDs are numerical.
Read the source of the page via file_get_contents($url) and then check if it contains the string <meta property="og:video" content="http://vimeo.com/moogaloop.swf?clip_id=".$vimid." /> If if contains that string, then you know its a valid video.

Protecting mp3 file path in flash player

I have flash player in my web site for playing the mp3 files.But if someone uses "viewsource" or any browser tools such as firebug, then they can find the parameter and then sort out the actual mp3 file url.I am using php in my back end. There should be someway to hide these parameters but couldn't figure out how?
Any ideas?
Preface: If you show it on the web you can steal it. Period.
That said, you can make it a lot harder by masking the URL of the file by passing it through a php script that does two things:
1) Translates an encrypted GET parameter which can be validated AND can be used only once (store the variable in a database or log). This code will be created when the player is loaded, and once it's started buffering the file cannot be used again. This way the parameter cannot just be a random string (it has to be decryptable) and the user cannot just use the same URL.
The php in the html page the user would receive would look something like:
$key = 'My EnCyption Key';
$unique_string = "Generated at ".time().$_SERVER['REMOTE_ADDR']; //the time element changes the string each time and the IP address controls for multiple users simultaneously loading the same page
$tolken = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
and then then the flash player would be set to use the mp3 file:
http://yoursite.com/mp3/file_fetcher.php?file_id=123&tolken=<?php echo $tolken;?>
The file file_fetcher.php would have something like this (obviously this requires some fleshing out):
$fixed_string_part = "Generated at ";
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($_GET['tolken']), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
if (substr($decrypted,0,strlen($fixed_string_part))!=$fixed_string_part){
die("Your tolken is invalid");
}
//check that the tolken hasn't been used before:
$check_query = mysql_query("select * from `mp3_tolken_log` where `tolken`='$decrypted';",[connection identifier]); //write this more cleanly
if (mysql_num_rows($query)){
die("You've already used that tolken!");
} else {
$log_it = mysql_query("insert into `mp3_tolken_log` (`tolken`,`dateadded`) VALUES ($decrypted,NOW())"); //make sure it's in there so it can't be used again
}
//now get the file if we haven't already died
$contents = file_get_contents([path/to/mp3/file/specified/by/id/$_GET['file_id']]);
header('Content-Type: audio/mpeg');
echo $contents;
2) Check that the referring site is your own site (rather than them trying to access the script directly). Something like:
if (!isset($_SERVER['HTTP_REFERER'])){die("Restricted Access!");};
$_u=parse_url($_SERVER['HTTP_REFERER']);
$_u=preg_replace("/(www.)/i","",strtolower($_u['host']));
$_i=$_SERVER['HTTP_HOST'];
$_i=preg_replace("/(www.)/i","",strtolower($_i));
($_u == $_i) or die("Restricted Access!");
Of course this information can be faked, but between it and the single-access pass you shouldn't have to worry about direct downloads. That said, remember that there are a million ways to get the file from the stream, and there's just no way to stop that.

recaptcha image and curl + php

$page = $curl->post($baseUrl.'/submit.php', array('url'=>$address,'phase'=>'1','randkey'=>$randKey[0],'id'=>'c_1'));
$exp = explode('recaptcha_image',$page);
The id recaptcha_image is not found although if i echo $page; the webpage will be displayed and surprisingly even the recpatcha div (with the image itself). Curl shouldn't load the image for recaptcha but somehow it does though when i try to find the div, it is not there. Is there a way to capture the url of the recaptcha image?
You'll want to use an HTML parser like this PHP Simple HTML DOM Parser.
Something like this will work then:
<?php
$page = $curl->post($baseUrl.'/submit.php', array('url'=>$address,'phase'=>'1','randkey'=>$randKey[0],'id'=>'c_1'));
$html->load($page);
$ret = $html->find('script[src^=http://api.recaptcha.net/]',0);
$src = $ret->src;
//I'm not sure how you get an url with your library, so this might or might not work
$page = $curl->get($src);
preg_match("%challenge\ :\ '([a-zA-Z0-9-_]*)',%", $page, $matches);
$img = "http://api.recaptcha.net/image?c=".$matches[1];
?>
This first fetches the page, parses it for the script URL, then opens that URL for the challenge which is then appended to the URL itself. The image will be in the $img variable.

Form Fix in php

I have a website form that collects url of users to store in a database. They should not enter the http:// with their URL however many and the result is that when their url is displayed it looks like this
http;//http://www.foo.com I need the form to strip it or ignore it or what ever you think is the best way to handle it.
thanks
Use this on the url given by the user:
$url=str_replace("http://","",$_POST['url']);
//Where $_POST['url'] is the users input
This function takes an argument and replaces all occurrences of that argument within a string. More on this function here.
You should do two things!
1 - Clean up your database and replace all http://http//example.org entries so that your database is fine with your convention (http://example.org, protocol is included in URL).
// Something like this ...
UPDATE table SET field = REPLACE(field, 'HTTP://HTTP://', 'HTTP://');
2 - After a user submitted his URL, you should check for the string "http://".
$url = trim('http://example.org');
if (0 !== strpos($url, 'http://')) {
$url .= 'http://' . $url;
}

Categories