I'm looking for a travel auto-link detection.
I'm trying to make a social media website and when my users post URLs I need it so like shows instead of just normal text.
Try Autologin for Laravel by dwightwatson, which provides you to generate URLs that will provide automatic login to your application and then redirect to the appropriate location
As far as I know, there's no equivalent in the Laravel's core for the auto_link() funtion helper from Code Igniter (assuming you are refering to the CI version).
Anyway, it's very simple to grab that code and use it in Laravel for a quick an dirty workaround. I just did casually looking for the same issue.
Put in your App directory a container class for your helpers (or any containter for the matter, it's just need to be discovered by the framework), in this case I put a UrlHelpers.php file. Then, inside of it put this two static functions grabbed for the CI version:
class UrlHelpers
{
static function auto_link($str, $type = 'both', $popup = FALSE)
{
// Find and replace any URLs.
if ($type !== 'email' && preg_match_all('#(\w*://|www\.)[^\s()<>;]+\w#i', $str, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
// Set our target HTML if using popup links.
$target = ($popup) ? ' target="_blank"' : '';
// We process the links in reverse order (last -> first) so that
// the returned string offsets from preg_match_all() are not
// moved as we add more HTML.
foreach (array_reverse($matches) as $match) {
// $match[0] is the matched string/link
// $match[1] is either a protocol prefix or 'www.'
//
// With PREG_OFFSET_CAPTURE, both of the above is an array,
// where the actual value is held in [0] and its offset at the [1] index.
$a = '<a href="' . (strpos($match[1][0], '/') ? '' : 'http://') . $match[0][0] . '"' . $target . '>' . $match[0][0] . '</a>';
$str = substr_replace($str, $a, $match[0][1], strlen($match[0][0]));
}
}
// Find and replace any emails.
if ($type !== 'url' && preg_match_all('#([\w\.\-\+]+#[a-z0-9\-]+\.[a-z0-9\-\.]+[^[:punct:]\s])#i', $str, $matches, PREG_OFFSET_CAPTURE)) {
foreach (array_reverse($matches[0]) as $match) {
if (filter_var($match[0], FILTER_VALIDATE_EMAIL) !== FALSE) {
$str = substr_replace($str, static::safe_mailto($match[0]), $match[1], strlen($match[0]));
}
}
}
return $str;
}
static function safe_mailto($email, $title = '', $attributes = '')
{
$title = (string)$title;
if ($title === '') {
$title = $email;
}
$x = str_split('<a href="mailto:', 1);
for ($i = 0, $l = strlen($email); $i < $l; $i++) {
$x[] = '|' . ord($email[$i]);
}
$x[] = '"';
if ($attributes !== '') {
if (is_array($attributes)) {
foreach ($attributes as $key => $val) {
$x[] = ' ' . $key . '="';
for ($i = 0, $l = strlen($val); $i < $l; $i++) {
$x[] = '|' . ord($val[$i]);
}
$x[] = '"';
}
} else {
for ($i = 0, $l = strlen($attributes); $i < $l; $i++) {
$x[] = $attributes[$i];
}
}
}
$x[] = '>';
$temp = array();
for ($i = 0, $l = strlen($title); $i < $l; $i++) {
$ordinal = ord($title[$i]);
if ($ordinal < 128) {
$x[] = '|' . $ordinal;
} else {
if (count($temp) === 0) {
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) === $count) {
$number = ($count === 3)
? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64)
: (($temp[0] % 32) * 64) + ($temp[1] % 64);
$x[] = '|' . $number;
$count = 1;
$temp = array();
}
}
}
$x[] = '<';
$x[] = '/';
$x[] = 'a';
$x[] = '>';
$x = array_reverse($x);
$output = "<script type=\"text/javascript\">\n"
. "\t//<![CDATA[\n"
. "\tvar l=new Array();\n";
for ($i = 0, $c = count($x); $i < $c; $i++) {
$output .= "\tl[" . $i . "] = '" . $x[$i] . "';\n";
}
$output .= "\n\tfor (var i = l.length-1; i >= 0; i=i-1) {\n"
. "\t\tif (l[i].substring(0, 1) === '|') document.write(\"&#\"+unescape(l[i].substring(1))+\";\");\n"
. "\t\telse document.write(unescape(l[i]));\n"
. "\t}\n"
. "\t//]]>\n"
. '</script>';
return $output;
}
}
The function safe_mailto is used in case there are email links in your string. If you don't need it you are free to modify the code.
Then you could use the helper class like this in any part of your Laravel code as usually (here inside a blade template, but the principle is the same):
<p>{!! \App\Helpers\Helpers::auto_link($string) !!}</p>
Quick and dirty, and It works. Hope to have helped. ¡Good luck!
Related
I am trying to generate html from a given string pattern, similar to a plugin.
There are three patterns, a no arg, a single arg and a multi arg string pattern. I can't change this pattern since it's from a CMS.
{pluginName} or {pluginName=3} or {pluginName id=3|view=simple|arg999=asv}
An example:
<p>Hi this is a html page</p>
<p>The following line should generate html</p>
{pluginName=3}
<p>The following line also should generate html</p>
{pluginName id=3|view=simple|arg999=asv}
My goal is to replace those "tags" with something (it's not relavant for this question the processing per say). However I want to be able to pass the args given to a class/function that should handle that logic.
This is my first attempt, without using regexes since I don't know how I could approach this problem with them (and mainly because they are slower).
<?php
function processPlugins($text, $pos = 0, $start = '{', $end = '}') {
$plugins = array('plugin1', 'plugin2');
while(($pos = strpos($text, $start, $pos)) !== false) {
$startPos = $pos;
$pos += strlen($start);
foreach($plugins as $plugin) {
if(substr($text, $pos, strlen($plugin)) === $plugin
&& ($endPos = strpos($text, $end, $pos + strlen($plugin))) !== false) {
$char = substr($text, $pos + strlen($plugin), 1); // 1 is strlen of (= or ' ')
$pos += strlen($plugin) + 1; // 1 is strlen of (= or ' ')
$argString = substr($text, $pos, $endPos - $pos);
if($char === ' ') { //Multi arg
$params = explode('|', trim($argString));
$paramDict = array();
foreach ($params as $param) {
list($k, $v) = array_pad(explode('=', $param), 2, null);
$paramDict[$k] = $v;
}
//$output = $plugin->processDictionary($paramDict);
var_dump($paramDict);
} elseif ($char === '=') { //One arg
//$output = $plugin->processArg($argString);
echo $argString . "\n";
} elseif ($char === $end) { //No arg
//$output = $plugin->processNoArg();
echo $plugin. "\n";
}
$pos = $endPos + strlen($end);
break;
}
}
}
}
processPlugins('{plugin1}');
processPlugins('{plugin2=3}');
processPlugins('{plugin2 arg1=b|arg2=d}');
The previous code works in a PHP sandbox.
This code seems to work (for now) but it seems sketchy. Would you approach this problem differently? Could I refactor this code somehow?
If you opt for string manipulation functions over regex, why not use explode for stripping the input down to the significant part?
Here is an alternative implementation:
function processPlugins($text, $pos = 0, $start = '{', $end = '}') {
$t = substr($text, $pos);
if($pos > 0) {
echo "$pos chracters removed from the begining: $t" . PHP_EOL;
} else {
echo "Starting with '$t'" . PHP_EOL;
}
$parts = explode($start, $t);
$t = $parts[1];
$parts = explode($end, $t);
$t = $parts[0];
echo "The part between curly braces: '$t'" . PHP_EOL;
$t = str_replace(['plugin1', 'plugin2'], '', $t);
echo "After plugin name has been removed: '$t'" . PHP_EOL;
$n = strlen($t);
if(!$n) {
echo "Processing complete: " . trim($parts[0]) . PHP_EOL . PHP_EOL;
return;
}
$params = explode('|', $t);
echo 'Key-Values: ' . json_encode($params) . PHP_EOL;
$kv = [];
foreach($params as $p) {
list($k, $v) = explode('=', trim($p));
echo " Item: '$p', Key: '$k', Value: '$v'" . PHP_EOL;
if($k === '') {
echo "Processing complete: $v" . PHP_EOL . PHP_EOL;
return;
}
$kv[$k] = $v;
}
echo "Processing complete: " . json_encode($kv) . PHP_EOL . PHP_EOL;
}
echo '<pre>';
processPlugins('{plugin1}');
processPlugins('{plugin2=3}');
processPlugins('{plugin2 arg1=b|arg2=d}');
Of course the echo lines could be thrown away. With them in place we get this output:
Starting with '{plugin1}'
The part between curly braces: 'plugin1'
After plugin name has been removed: ''
Processing complete: plugin1
Starting with '{plugin2=3}'
The part between curly braces: 'plugin2=3'
After plugin name has been removed: '=3'
Key-Values: ["=3"]
Item: '=3', Key: '', Value: '3'
Processing complete: 3
Starting with '{plugin2 arg1=b|arg2=d}'
The part between curly braces: 'plugin2 arg1=b|arg2=d'
After plugin name has been removed: 'arg1=b|arg2=d'
Key-Values: [" arg1=b","arg2=d"]
Item: ' arg1=b', Key: 'arg1', Value: 'b'
Item: 'arg2=d', Key: 'arg2', Value: 'd'
Processing complete: {"arg1":"b","arg2":"d"}
This version works with inputs having more than one plugin token.
function processPlugins($text, $pos = 0, $start = '{', $end = '}') {
$processed = [];
$t = substr($text, $pos);
$parts = explode($start, $t);
array_shift($parts);
foreach($parts as $part) {
$pparts = explode($end, $part);
$t = trim($pparts[0]);
$t = str_replace(['plugin1', 'plugin2'], '', $t);
$n = strlen($t);
if(!$n) {
$processed[] = trim($pparts[0]);
continue;
}
$params = explode('|', $t);
$kv = [];
foreach($params as $p) {
list($k, $v) = explode('=', trim($p));
if(trim($k) === '') {
$processed[] = trim($v);
continue 2;
}
$kv[trim($k)] = trim($v);
}
$processed[] = $kv;
}
return $processed;
}
function test($case) {
$p = processPlugins($case);
echo "$case => " . json_encode($p) . PHP_EOL;
}
$cases = [
'{plugin1}',
'{plugin2=3}',
'{plugin2 arg1=b|arg2=d}',
'text here {plugin1} and more{plugin2=55}here {plugin2 arg1=b|arg2=d} till the end'
];
foreach($cases as $case) {
test($case);
}
The output:
{plugin1} => ["plugin1"]
{plugin2=3} => ["3"]
{plugin2 arg1=b|arg2=d} => [{"arg1":"b","arg2":"d"}]
text here {plugin1} and more{plugin2=55}here {plugin2 arg1=b|arg2=d} till the end => ["plugin1","55",{"arg1":"b","arg2":"d"}]
what i am trying to do is to get directory of my page like this
Home / Clothes / Something
i have tried this but i didn't understand a lot in this but it doesn't work as i want it
<?php
// current directory
echo getcwd() . "\n";
chdir('cvs');
// current directory
echo getcwd() . "\n";
?>
here's example what i need to do
my page is example.com/clothes/something.php
and on that page "something.php" i want to echo out something like this
Home / clothes / Something
i forget what this was called but hope you understand
<?php
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $parts[$i])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $parts[$i]);
};
};
};
?>
Try something like this:
$subPath = '';
$path = explode('/', $_SERVER['REQUEST_URI']);
array_shift($path);
foreach ($path as $segment) {
$subPath.= $segment.'/';
echo "$segment / ";
}
You may need to tweak it a bit, but that's the basic idea.
[EDIT]
Or maybe something like this:
$Pages = [
'/clothes' => 'Clothes',
'/clothes/something.php' => 'Something'
];
$subPath = '';
$BreadCrumbs = [];
$path = explode('/', $_SERVER['REQUEST_URI']);
array_shift($path);
foreach ($path as $segment) {
$subPath.= '/'.$segment;
$BreadCrumbs[] = "$Pages[$subPath]";
}
echo implode(' > ', $BreadCrumbs);
If your version of PHP is before 5.4.0, then you'll need a different syntax for the arrays:
$Pages = array(
'/clothes' => 'Clothes',
'/clothes/something.php' => 'Something'
);
$BreadCrumbs = array();
[EDIT]
OK, one last go:
<?php
$Pages = array(
'clothes' => 'Clothes',
'something' => 'Something'
);
$path = $_SERVER["PHP_SELF"];
$parts = explode('/',$path);
if (count($parts) < 2)
{
echo("home");
}
else
{
echo ("Home » ");
for ($i = 1; $i < count($parts); $i++)
{
if (!strstr($parts[$i],"."))
{
echo("<a href=\"");
for ($j = 0; $j <= $i; $j++) {echo $parts[$j]."/";};
echo("\">". str_replace('-', ' ', $Pages[$parts[$i]])."</a> » ");
}
else
{
$str = $parts[$i];
$pos = strrpos($str,".");
$parts[$i] = substr($str, 0, $pos);
echo str_replace('-', ' ', $Pages[$parts[$i]]);
};
};
};
?>
Let's say I have a string from the user ($input). I can go and strip tags, to allow only allowed tags in. I can convert to text with htmlspecialchars(). I can even replace all tags I don't want with text.
function html($input) {
$input = '<bl>'.htmlspecialchars($input).'</bl>'; // bl is a custom tag that I style (stands for block)
global $open;
$open = []; //Array of open tags
for ($i = 0; $i < strlen($input); $i++) {
if (!in_array('code', $open) && !in_array('codebl', $open)) { //If we are parsing
$input = preg_replace_callback('#^(.{'.$i.'})<(em|i|del|sub|sup|sml|code|kbd|pre|codebl|quote|bl|sbl)>\s*#s', function($match) {
global $open; //...then add new tags to the array
array_push($open,$match[2]);
return $match[1].'<'.$match[2].'>'; //And replace them
}, $input);
$input = preg_replace_callback('#^(.{'.$i.'})(https?):\/\/([^\s"\(\)<>]+)#', function($m) {
return $m[1].''.$m[3].'';
}, $input, -1, $num); //Simple linking
$i += $num * 9;
$input = preg_replace_callback('#^(.{'.$i.'})\n\n#', function($m) {
return $m[1].'</bl><bl>';
}, $input); // More of this bl element
}
if (end($open)) { //Close tags
$input = preg_replace_callback('#^(.{'.$i.'})</('.end($open).')>#s', function($match) {
global $open;
array_pop($open);
return trim($match[1]).'</'.$match[2].'>';
}, $input);
}
}
while ($open) { //Handle unclosed tags
$input .= '</'.end($open).'>';
array_pop($open);
}
return $input;
}
The problem is that after that, there is no way to write literally <i&lgt;</i>, because it will be automatically parsed into either <i></i> (if you write <i></i>), or &lt;i&gt;&lt;/i&gt; (if you write <i></i>). I want the user to be able to enter < (or any other HTML entity) and get < back. If I just send it straight to the browser unparsed, it would (obviously) be vulnerable to whatever sorcery the hackers are trying (and I'm letting) to (be) put on my site. So, How can I let the user use any of the pre-defined set of HTML tags, while still letting them use html entities?
This is what I eventually used:
function html($input) {
$input = preg_replace(["#&([^A-z])#","#<([^A-z/])#","#&$#","#<$#"], ['&$1','<$1','&','<'], $input); //Fix single "<"s and "&"s
$open = []; //Array of open tags
$close = false; //Is the current tag a close tag?
for ($i = 0; $i <= strlen($input); $i++) { //Start the loop
if ($tag) { //Are we in a tag?
if (preg_match("/[^a-z]/", $input[$i])) { //The tag has ended
if ($close) {
$close = false;
$sPos = strrpos(substr($input,0,$i), '<') + 2; //start position of tag
$tag = substr($input,$sPos,$i-$sPos); //tag name
if (end($open) == $tag) {
array_pop($open); //Good, it's a valid XML closing
} else {
$input = substr($input, 0, $sPos-2) . '</' . $tag . substr($input, $i); //BAD! Convert tag to text (open tag will be handled later)
}
} else {
$sPos = strrpos(substr($input,0,$i), '<') + 1; //start position of tag
$tag = substr($input,$sPos,$i-$sPos); //tag name
if (in_array($tag, ['em','i','del','sub','sup','sml','code','kbd','pre','codebl','bl','sbl'])) { //Is it an acceptable tag?
array_push($open, $tag); //Add it to the array
$j = $i + 1;
while (preg_match("/\s/", $input[$j])) { //Get rid of whitespace
$j++;
}
$input = substr($input, 0, $sPos - 1) . '<' . $tag . '>' . substr($input, $j); //Seems legit
} else {
$input = substr($input, 0, $sPos - 1) . '<' . $tag . substr($input, $i); //BAD! Convert tag to text
}
}
$tag = false;
}
} else if (!in_array('code', $open) && !in_array('codebl', $open) && !in_array('pre', $open)) { //Standard parsing of text
if ($input[$i] == '<') { //Is it a tag?
$tag = true;
if ($input[$i+1] == '/') { //Is it a close tag?
$i++;
$close = true;
}
} else if (substr($input, $i, 4) == 'http') { //Link
if (preg_match('#^.{'.$i.'}(https?):\/\/([^\s"\(\)<>]+)#', $input, $m)) {
$insert = ''.$m[2].'';
$input = substr($input, 0, $i) . $insert . substr($input, $i + strlen($m[1].'://'.$m[2]));
$i += strlen($insert);
}
} else if ($input[$i] == "\n" && $input[$i+1] == "\n") { //Insert <bl> tag? (I use this to separate sections of text)
$input = substr($input, 0, $i + 1) . '</bl><bl>' . substr($input, $i + 1);
}
} else { // We're in a code tag
if (substr($input, $i+1, strlen(end($open)) + 3) == '</'.current($open).'>') {
array_pop($open);
$i += 2;
} elseif ($input[$i] == '<') {
$input = substr($input, 0, $i) . '<' . substr($input, $i + 1);
$i += 3; //Code tags have raw text
} elseif (in_array('code', $open) && $input[$i] == "\n") { //No linebreaks are allowed in inline tags, convert to <codebl>
$open[count($open) - 1] = 'codebl';
$input = substr($input, 0, strrpos($input,'<code>')) . '<codebl>' . substr($input, strrpos($input,'<code>') + 6, strpos(substr($input, strrpos($input,'<code>')),'</code>') - 6) . '</codebl>' . substr($input, strpos(substr($input, strrpos($input,'<code>')),'</code>') + strrpos($input,'<code>') + 7);
$i += 4;
}
}
}
while ($open) { //Handle open tags
$input .= '</'.end($open).'>';
array_pop($open);
}
return '<bl>'.$input.'</bl>';
}
I know it's a bit more risky, but you can first assume the input's good, then filter out the stuff explicitly found as bad.
I found a script which can extract the artist & title name from an Icecast or Shoutcast stream.
I want the script to update automatically when a song changed, at the moment its working only when i execute it. I'm new to PHP so any help will be appreciated.
Thanks!
define('CRLF', "\r\n");
class streaminfo{
public $valid = false;
public $useragent = 'Winamp 2.81';
protected $headers = array();
protected $metadata = array();
public function __construct($location){
$errno = $errstr = '';
$t = parse_url($location);
$sock = fsockopen($t['host'], $t['port'], $errno, $errstr, 5);
$path = isset($t['path'])?$t['path']:'/';
if ($sock){
$request = 'GET '.$path.' HTTP/1.0' . CRLF .
'Host: ' . $t['host'] . CRLF .
'Connection: Close' . CRLF .
'User-Agent: ' . $this->useragent . CRLF .
'Accept: */*' . CRLF .
'icy-metadata: 1'.CRLF.
'icy-prebuffer: 65536'.CRLF.
(isset($t['user'])?'Authorization: Basic '.base64_encode($t['user'].':'.$t['pass']).CRLF:'').
'X-TipOfTheDay: Winamp "Classic" rulez all of them.' . CRLF . CRLF;
if (fwrite($sock, $request)){
$theaders = $line = '';
while (!feof($sock)){
$line = fgets($sock, 4096);
if('' == trim($line)){
break;
}
$theaders .= $line;
}
$theaders = explode(CRLF, $theaders);
foreach ($theaders as $header){
$t = explode(':', $header);
if (isset($t[0]) && trim($t[0]) != ''){
$name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
array_shift($t);
$value = trim(implode(':', $t));
if ($value != ''){
if (is_numeric($value)){
$this->headers[$name] = (int)$value;
}else{
$this->headers[$name] = $value;
}
}
}
}
if (!isset($this->headers['icymetaint'])){
$data = ''; $metainterval = 512;
while(!feof($sock)){
$data .= fgetc($sock);
if (strlen($data) >= $metainterval) break;
}
$this->print_data($data);
$matches = array();
preg_match_all('/([\x00-\xff]{2})\x0\x0([a-z]+)=/i', $data, $matches, PREG_OFFSET_CAPTURE);
preg_match_all('/([a-z]+)=([a-z0-9\(\)\[\]., ]+)/i', $data, $matches, PREG_SPLIT_NO_EMPTY);
echo '<pre>';var_dump($matches);echo '</pre>';
$title = $artist = '';
foreach ($matches[0] as $nr => $values){
$offset = $values[1];
$length = ord($values[0]{0}) +
(ord($values[0]{1}) * 256)+
(ord($values[0]{2}) * 256*256)+
(ord($values[0]{3}) * 256*256*256);
$info = substr($data, $offset + 4, $length);
$seperator = strpos($info, '=');
$this->metadata[substr($info, 0, $seperator)] = substr($info, $seperator + 1);
if (substr($info, 0, $seperator) == 'title') $title = substr($info, $seperator + 1);
if (substr($info, 0, $seperator) == 'artist') $artist = substr($info, $seperator + 1);
}
$this->metadata['streamtitle'] = $artist . ' - ' . $title;
}else{
$metainterval = $this->headers['icymetaint'];
$intervals = 0;
$metadata = '';
while(1){
$data = '';
while(!feof($sock)){
$data .= fgetc($sock);
if (strlen($data) >= $metainterval) break;
}
//$this->print_data($data);
$len = join(unpack('c', fgetc($sock))) * 16;
if ($len > 0){
$metadata = str_replace("\0", '', fread($sock, $len));
break;
}else{
$intervals++;
if ($intervals > 100) break;
}
}
$metarr = explode(';', $metadata);
foreach ($metarr as $meta){
$t = explode('=', $meta);
if (isset($t[0]) && trim($t[0]) != ''){
$name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
array_shift($t);
$value = trim(implode('=', $t));
if (substr($value, 0, 1) == '"' || substr($value, 0, 1) == "'"){
$value = substr($value, 1);
}
if (substr($value, -1) == '"' || substr($value, -1) == "'"){
$value = substr($value, 0, -1);
}
if ($value != ''){
$this->metadata[$name] = $value;
}
}
}
}
fclose($sock);
$this->valid = true;
}else echo 'unable to write.';
}else echo 'no socket '.$errno.' - '.$errstr.'.';
}
public function print_data($data){
$data = str_split($data);
$c = 0;
$string = '';
echo "<pre>\n000000 ";
foreach ($data as $char){
$string .= addcslashes($char, "\n\r\0\t");
$hex = dechex(join(unpack('C', $char)));
if ($c % 4 == 0) echo ' ';
if ($c % (4*4) == 0 && $c != 0){
foreach (str_split($string) as $s){
//echo " $string\n";
if (ord($s) < 32 || ord($s) > 126){
echo '\\'.ord($s);
}else{
echo $s;
}
}
echo "\n";
$string = '';
echo str_pad($c, 6, '0', STR_PAD_LEFT).' ';
}
if (strlen($hex) < 1) $hex = '00';
if (strlen($hex) < 2) $hex = '0'.$hex;
echo $hex.' ';
$c++;
}
echo " $string\n</pre>";
}
public function __get($name){
if (isset($this->metadata[$name])){
return $this->metadata[$name];
}
if (isset($this->headers[$name])){
return $this->headers[$name];
}
return null;
}
}
$t = new streaminfo('http://64.236.34.196:80/stream/1014'); // get metadata
echo Meta Interval: $t->icymetaint;
echo Current Track: $t->streamtitle;
You will need to constantly query the stream at a set interval to find when the song changes.
This can be best done by scheduling a cron job.
If on Windows, you should use the Windows Task Scheduler
If you want to run the PHP script to keep your meta data up to date (I'm assuming you're making a website and using html audio tags here) you can use the ontimeupdate event with an ajax function. If you're not you probably should look up your audio playback documentation for something similar.
<audio src="http://ip:port/;" ontimeupdate="loadXMLDoc()">
You can find a great example here http://www.w3schools.com/php/php_ajax_php.asp
You want to use the PHP echo function all the relevant information at once using one php variable at the very end of your script.
<?php ....
$phpVar=$streamtitle;
$phpVar2=$streamsong;
$result="I want my string to look like this: <br> {$phpVar} {$phpVar2}";
echo $result;
?>
and then use the function called by the .onreadystatechange to modify the particular elements you want on your website by using the .resonseText (this will contain the same content as your PHP script's echo).
After SCOURING the web for 4 hours, this is the only Shoutcast metadata script I've found that works! Thankyou.
To run this constantly, why not use a setInterval combined with jQuery's AJAX call?
<script>
$(function() {
setInterval(getTrackName,16000);
});
function getTrackName() {
$.ajax({
url: "track_name.php"
})
.done(function( data ) {
$( "#results" ).text( data );
});
}
</script>
Also your last couple 'echo' lines were breaking the script for me. Just put quotes around the Meta Interval, etc....
I have a simple task to do with PHP, but since I'm not familiar with Regular Expression or something... I have no clue what I'm going to do.
what I want is very simple actually...
let's say I have these variables :
$Email = 'john#example.com'; // output : ****#example.com
$Email2 = 'janedoe#example.com'; // output : *******#example.com
$Email3 = 'johndoe2012#example.com'; // output : ***********#example.com
$Phone = '0821212121'; // output : 082121**** << REPLACE LAST FOUR DIGIT WITH *
how to do this with PHP? thanks.
You'll need a specific function for each. For mails:
function hide_mail($email) {
$mail_segments = explode("#", $email);
$mail_segments[0] = str_repeat("*", strlen($mail_segments[0]));
return implode("#", $mail_segments);
}
echo hide_mail("example#gmail.com");
For phone numbers
function hide_phone($phone) {
return substr($phone, 0, -4) . "****";
}
echo hide_phone("1234567890");
And see? Not a single regular expression used. These functions don't check for validity though. You'll need to determine what kind of string is what, and call the appropriate function.
For e-mails, this function preserves first letter:
function hideEmail($email)
{
$parts = explode('#', $email);
return substr($parts[0], 0, min(1, strlen($parts[0])-1)) . str_repeat('*', max(1, strlen($parts[0]) - 1)) . '#' . $parts[1];
}
hideEmail('hello#domain.com'); // h****#domain.com
hideEmail('hi#domain.com'); // h*#domain.com
hideEmail('h#domain.com'); // *#domain.com
I tried for a single-regex solution but don't think it's possible due to the variable-length asterisks. Perhaps something like this:
function anonymiseString($str)
{
if(is_numeric($str))
{
$str = preg_replace('/^(\d*?)\d{4}$/', '$1****');
}
elseif(($until = strpos($str, '#')) !== false)
{
$str = str_repeat('*', $until) . substr($str, $until + 1);
}
return $str;
}
I create one function to do this, works fine for me. i hope help.
function ofuscaEmail($email, $domain_ = false){
$seg = explode('#', $email);
$user = '';
$domain = '';
if (strlen($seg[0]) > 3) {
$sub_seg = str_split($seg[0]);
$user .= $sub_seg[0].$sub_seg[1];
for ($i=2; $i < count($sub_seg)-1; $i++) {
if ($sub_seg[$i] == '.') {
$user .= '.';
}else if($sub_seg[$i] == '_'){
$user .= '_';
}else{
$user .= '*';
}
}
$user .= $sub_seg[count($sub_seg)-1];
}else{
$sub_seg = str_split($seg[0]);
$user .= $sub_seg[0];
for ($i=1; $i < count($sub_seg); $i++) {
$user .= ($sub_seg[$i] == '.') ? '.' : '*';
}
}
$sub_seg2 = str_split($seg[1]);
$domain .= $sub_seg2[0];
for ($i=1; $i < count($sub_seg2)-2; $i++) {
$domain .= ($sub_seg2[$i] == '.') ? '.' : '*';
}
$domain .= $sub_seg2[count($sub_seg2)-2].$sub_seg2[count($sub_seg2)-1];
return ($domain_ == false) ? $user.'#'.$seg[1] : $user.'#'.$domain ;
}
Output: a******#gmail.com
$email = str_replace(substr($old_email, 1, strlen(explode("#", $old_email)[0])-1), "**********", $old_email);
This is a quick fix to the question above;
It ensures just the first character of the email address as the extension shows up.
You can increase or reduce the number of asterisks depending