EDITED
I'm trying to setup a random link at the bottom of all my pages. I'm using the code below, but want to make it so the current page is not included in the random rotation of links.
Example:
I need code to randomly select and display ONE of these links. The exception being, IF article1.php is currently being viewed, I want it to be excluded from the random selection. That way only links to OTHER articles are seen on any given article.
http://mysite.com/article1.php
http://mysite.com/article2.php
http://mysite.com/article3.php
I would use array_rand with something like:
<?php
$links = array(array('url' => 'http://google.com', 'name'=>'google'),
array('url' => 'http://hotmail.com', 'name' => 'hotmail'),
array('url' => 'http://hawkee.com', 'name' => 'Hawkee'));
$num = array_rand($links);
$item = $links[$num];
printf('%s', $item['url'], $item['name'], $item['name']);
?>
Where links makes it easier to build an array. Nevertheless, I think we miss some details about how you grab your links.
What is the mean of "current page"? because the simplest way to do, is just not add the page to the array.
And the use of array_rand avoids confusion with size of array and so.
Edit: I suppose you use a database, so you may have an sql request like:
SELECT myfieldset FROM `articles` WHERE id = 'theid';
So you know the id of the current article. Now you just have to build an array with some other articles with a query like:
SELECT id FROM `articles` WHERE id NOT IN ('theid') ORDER BY RAND LIMIT 5
And build the candidate array with those results.
Each time you randomly choose a URL to display, pop it off of the array and store it in a temporary variable. Then, on the next rotation make your selection and THEN push the previously used URL back into the array.
$lastUrl = trim(file_get_contents('last_url.txt'));
while($lastUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){}
file_put_contents('last_url.txt', $randUrl);
// ...
echo $randUrl;
Ensures that on each page load, you will not receive the previous URL. This, however is just an example. You would want to incorporate file locking, exception handling (perhaps) or an entirely different storage medium (DB, etc.)
To ensure the URL is not the same as the current, this should do the trick:
// get current URL
$currentUrl = 'http://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
// randomize URLs until you get one that doesn't match the current
while($currentUrl == ($randUrl = $urls[rand(0, count($urls) - 1)])){ }
echo $randUrl;
Google "PHP get current URL", and you'll get considerably more detailed ways to capture the current URL. For example, conditions on whether or not you're use HTTPS, to append an 's' to the protocol component.
try the codes below :
$links = array(
'http://mysite.com/article1.php',
'http://mysite.com/article2.php',
'http://mysite.com/article3.php',
'http://mysite.com/article4.php',
'http://mysite.com/article5.php'
);
$currentPage = basename($_SERVER['SCRIPT_NAME']);
$count = 0;
$currentIndex = NULL;
foreach($links as $link) {
if(strpos($link, "/".$currentPage)>-1) $currentIndex = $count;
$count++;
}
if($currentIndex) {
do{
$random = mt_rand(0, sizeof($links) - 1);
} while($random==$currentIndex);
} else {
$random = mt_rand(0, sizeof($links) - 1);
}
$random_link = $links[$random];
Related
I have the URL https://android.rediptv2.com/ch.php?usercode=5266113827&pid=1&mac=02:00:00:00:00:00&sn=&customer=GOOGLE&lang=eng&cs=amlogic&check=3177926680
which outputs statistics.
For example:
[{"id":"2972","name":"MBC 1","link":"http://46.105.112.116/?watch=TR/mbc1-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC1En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc1.png"},{"id":"1858","name":"MBC 2","link":"http://46.105.112.116/?watch=TN/mbc2-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC2En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc2.png"},{"id":"1859","name":"MBC 3","link":"http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc3.png"}]
I want to get the value of link count.
Can anyone help?
I tried to do:
<?php
$content = file_get_contents("https://android.rediptv2.com/ch.php?usercode=5266113827&pid=1&mac=02:00:00:00:00:00&sn=&customer=GOOGLE&lang=eng&cs=amlogic&check=3177926680");
$result = json_decode($content);
print_r( $result->link );
?>
But it didn't work.
Put the JSON in an editor and you'll see that it's an array and not an object with the link attribute. This is why you cannot access it directly. You have to loop over the items and then you'll be able to access the link property of one of the items. If you need to access the link by id, as you asked 4 months later, then just create a dictionnary in an array indexed by id and containing just the interesting data you need.
PHP code:
<?php
// The result of the request:
$content = <<<END_OF_STRING
[{"id":"2972","name":"MBC 1","link":"http://46.105.112.116/?watch=TR/mbc1-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC1En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc1.png"},{"id":"1858","name":"MBC 2","link":"http://46.105.112.116/?watch=TN/mbc2-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC2En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc2.png"},{"id":"1859","name":"MBC 3","link":"http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc3.png"}]
END_OF_STRING;
$items = json_decode($content);
echo '$items = ' . var_export($items, true) . "\n\n";
// Create a dictionnary to store each link accessible by id.
$links_by_id = [];
// Loop over all items:
foreach ($items as $i => $item) {
// Show how to access the current link.
echo "Link $i = $item->link\n";
// Fill the dictionary.
$links_by_id[(int)$item->id] = $item->link;
}
// To access the first one:
echo "\nFirst link = " . $items[0]->link . "\n";
// Example of access by id:
// The id seems to be a string. It could probably be "1895" or "zhb34" or whatever.
// (If they are only numbers, we could convert the string to an integer).
$id = "1859";
echo "\nAccess with id $id = " . $links_by_id[$id] . "\n";
Test it here: https://onlinephp.io/c/e8ab9
Another important point: You are getting a 403 Forbidden error on the URL you provided. So typically, you will not obtain the JSON you wanted.
As I explained in the comment below, I think that you will not be able to access this page without having a fresh URL with valid query parameters and/or cookies. I imagine you obtained this URL from somewhere and it is no longer valid. This is why you'll probably need to use cURL to visit the website with a session to obtain the fresh URL to the JSON API. Use Google to find some examples of PHP scraping/crawling with session handling. You'll see that depending on the website it can get rather tricky, especially if some JavaScript comes into the game.
Can anyone suggest a method in php or a function for parsingSEO friendly urls that doesn't involve htaccess or mod_rewrite? Examples would be awesome.
http://url.org/file.php/test/test2#3
This returns: Array ( scheme] => http [host] => url.org [path] => /file.php/test/test2 [fragment] => 3 ) /file.php/test/test2
How would I separate out the /file.php/test/test2 section? I guess test and test2 would be arguments.
EDIT:
#Martijn - I did figure out what your suggested before getting the notification about your answer. Thanks btw. Is this considered an ok method?
$url = 'http://url.org/file.php/arg1/arg2#3';
$test = parse_url($url);
echo "host: $test[host] <br>";
echo "path: $test[path] <br>";
echo "frag: $test[fragment] <br>";
$path = explode("/", trim($test[path]));
echo "1: $path[1] <br>";
echo "2: $path[2] <br>";
echo "3: $path[3] <br>";
echo "4: $path[4] <br>";
You can use explode to get the parts from your array:
$path = trim($array['path'], "/"); // trim the path of slashes
$path = explode("/", $path);
unset($path[0]); // the first one is the file, the others are sections of the url
If you really want to make it zerobased again, add this as last line:
$patch = array_values($path);
In response to your edit:
You want to make this as flexible as you can, so no fixed coding based on a max of 5 items. Although you probably will never exceed that, just don't pin yourself to it, just overhead you dont need.
If you have a pages system like this:
id parent name url
1 -1 Foo foo
2 1 Bar, child of Foo bar-child-of-foo
Make a recursive function. Pass the array to a function which takes the first section to find a root item
SELECT * FROM pages WHERE parent=-1 AND url=$path[0]
That query will return an id, use that in the parent column with the next value of the array. Unset each found value of the $path array. In the end, you will have an array with the remaining parts.
To sketch an example:
function GetFullPath(&$path, $parent=-1){
$path = "/"; // start with a slash
// Make the query for childs of this item
$result = mysqli_query($conn, "SELECT * FROM pages WHERE parent=".$parent." AND url=".current($path)." LIMIT 1");
// If any rows exists, append more of the url via recursiveness:
if($result->num_rows!==0){
// Remove the first part so if we go one deeper we start with the next value
$path = array_slice($patch,1); // remove first value
$fetch = $result->fetch_assoc();
// Use the fetched value to go deeper, find a child with the current item as parent
$path.= GetFullPath($path, $fetch['parent']);
}
// Return the result. if nothing is found at all, the result will be "/", probs home
return $path;
}
echo GetFullPath($path); // I pass it by reference, any alterations in the function happen to the variable outside the scope aswell
This is a draft, I did not test this, but you get the idea im trying to sketch. You can use the same method to get the ID of the page you are at. Just keep passing the variable back up again c
One of these days im getting the hang of recursiveness ^^.
Edit again: Oops, that turned out to be quite some code.
I've had excellent support here, so I figured I'd try again, as I have no clue where to even begin looking for this answer.
I have a simple MySQL database, named "testimonials", which contains 3 tables, "id", "name", "content"
What I want to do, is display testimonials within a fixed size block. Just simply displaying the content is no problem at all, however where I'm stuck is the (somewhat) unique way I'm trying to make it work. I would like to display a random item on each page load, and then to check the character length of the "content" within the testimonial, and if it's equal to or greater than XX length, then just display the one testimonial, otherwise if it's less than XX in length to display a second testimonial (assuming it combined with the first doesn't break the container box).
The box in question is 362px in width and 353px in height using 14px font with Verdana. An example of how the testimonial will appear on the page is like this:
"This is the testimonial content, some nice message from a client."
-- Billy Bob, Owner, Crazy Joe's Tavern
The "name" table in the database holds everything in bold (minus the -- of course), in case someone felt the need to ask.
As I typed that, I felt as if I was asking for a miracle, however I'll still post the question, hoping someone might just know the answer. As always, thanks for any help I may get, if this is just simply asking too much, I'm not totally against the idea of only displaying one testimonial at a time making a ground rule saying they have to contain a minimum of XX characters.
Thanks!
Quick Update: I didn't expect to get answers so quickly, I'm not at my desk at the moment, so as soon as I sit back down I'll go through and see which answer fits best. However, do you guys get together and try to make your answer more complex than the previous answer? lol, thanks though, for anyone who's offering help, you guys rock!
Final edit: I decided against this whole idea, as it just way over complicated everything. For the time being, I'm just going to display all testimonials, and make them scroll, while I work on a jQuery snippet to make it prettier. Thanks everyone for your help though! Should I decide again to do this, I'll be trying my chosen answer.
You just need a loop. Pseudo-code:
$length = 0;
$target = 200; // or whatever
while( $length < $target ) {
$comment = getOneComment();
displayComment($comment);
$length += strlen( $comment['content'] ); // assuming getOneComment() returns an associative array
}
To make it pretty, if the display box is going to a be a fixed height, you could use some jQuery to toggle whether to show the second comment on not.
Assuming you have testimonials in an array:
$testimonials = array(
't1' => array(
'content' => 'testimonials 1 content..',
'author' => 'the author'
),
't2' => array(
'content' => 'testimonials 2 content..',
'author' => 'the author 2'
),
);
You could have an maxLengthTestimonialsContent and maxLenthAllTestimonnials variable :
$maxLengthTestimonialsContent = 120;
$maxLenthAllTestimonnials = 240;
And now with a simple loop you build the array testimonials that you will use to show:
$testimonialsToShow = array();
$i = 1; $totalLength = 0
foreach($testimonials as $t) {
if( $i > 1 && strlen( $t['content']) < $maxLengthTestimonialsContent
&& $totalLength < $maxLenthAllTestimonnials )
break; // basically here you test that testimonials less first
// and with less length than maxLengthTestimonial, and also
// total length less than maxLengthAll to be stored
//in $testimonialsToShow
else {
$testimonialsToShow[] = $t;
$totalLength = $t['content'];
}
}
Something like this is what you would need.
<?php
$str = $res["testimonial"];
if (strlen($str) > 50) {
// Logic to retrieve and display second testimonial
}
?>
Obviously there's some more processing you'll have to come up with to determine if the second testimonial is short enough to fit or not. But that should get you started.
EDIT:
For the randomization, I use this on my own site:
$referrals = mysql_query("SELECT id FROM ts_testimonials");
$referralView = array();
$i = 0;
while ($newReferral = mysql_fetch_array($referrals)) {
$referralView[$i] = $newReferral['id'];
$i++;
}
if (sizeof($referralView) >= 1){
$referralTop = rand(0,sizeof($referralView)-1);
$newReferralTop = mysql_fetch_array(mysql_query("SELECT * FROM ts_testimonials WHERE id = '".$referralView[$referralTop]."'"));
if (sizeof($referralView) >=2){
$referralBottom = rand(0,sizeof($referralView)-1);
while ($referralBottom == $referralTop) {
$referralBottom = rand(0,sizeof($referralView)-1);
}
$newReferralBottom = mysql_fetch_array(mysql_query("SELECT * FROM ts_testimonials WHERE id = '".$referralView[$referralBottom]."'"));
}
}
Im learning JQuery and php.
Is it possible to store multiple video links within variables and get php to echo one at random??
My goal is to control my own video ads on my site and I thought this would be a good idea but I dont have a clue where I should look online.
Here is what I was thinking
<?php
$advert1 = 'MyVIDEO1.mp4';
$advert2 = 'MyVideo2.mp4';
$advert3 = 'MyVideo3.mp4';
I want a code that would go here and say: randomly select one of these vars.
echo "At random one of the vars";
?>
I hope Im making sense. help?
You could make an array, like this:
$advert[] = array();
$advert[1] = 'MyVIDEO1.mp4';
$advert[2] = 'MyVIDEO2.mp4';
$advert[3] = 'MyVIDEO3.mp4';
$chosen_one = rand(1,count($advert));
echo $advert[$chosen_one];
You can also use array_rand() instead of shuffle():
<?php
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
echo $videos[array_rand($videos)];
?>
For embedding the video in the right way, have a look at http://www.w3schools.com/html/html_videos.asp
For a start, PHP itself won't exactly play a video. You could use it to echo out one of the URL's to a video. So, bear in mind there is a lot more to do than just select a video.
To answer your question in the code I'd recommend the following:
Try looking up PHP arrays. You want to keep all the videos in an array.
Next up, you'll want to shuffle that array. Then select the first element.
$videos = array("MyVIDEO1.mp4", "MyVideo2.mp4", "MyVideo3.mp4");
shuffle($videos);
echo $videos[0];
This is a simple solution
Place your adverts in an array
<?php
$adverts = array("advert1" => "MyVIDEO1.mp4",
"advert2" => "MyVIDEO2.mp4",
"advert3" => "MyVIDEO3.mp4");
$count = count($adverts);
$rand_advert = rand(1, $count);
echo $adverts['advert'.$rand_advert];
?>
Or alternatively if you don't want to have keys and just put the values in the array straight away
<?php
$adverts = array("MyVIDEO1.mp4",
"MyVIDEO2.mp4",
"MyVIDEO3.mp4");
shuffle($adverts);
echo $adverts[0];
?>
You have need all value in a array then find index randomly and show it.
<?php
$advert = array(
'MyVIDEO1.mp4',
'MyVideo2.mp4',
'MyVideo3.mp4'
);
$total_video = count($advert);
$total_video--; //array index starting from 0 so decrease 1
$random_index = rand(0, $total_video); //array index 0 to 2
$video_to_play = $advert[$random_index];
echo $video_to_play;
?>
I am working on a WordPress site where the client has uploaded thousands of photos to Flickr and now want me to move them all back into WordPress and associate them with there proper posts.
Even though there are thousands of images, there is really only about 50 unique images, all the other versions are the same image but uploaded to a different location on Flickr or a slightly different size or name.
In helping me track down all the unique images, based on a list like below, that part I have highlighted, I need to pull every record into a PHP array, the catch is the part I have highlighted, is what I want to make sure is UNIQUE among all records in the array.
Any help in taking an existing PHP ARRAy that has every record and making the array only show unique values based on that part of the Value string?
Is this a Regular Expressions use case?
If it used Regex or similar I think a pattern it could look for is /4485116555_ / followed by 10 digits and then followed up with a _
Appreciate any help in getting me 1 step closer to my goal, this is just 1 piece of the big puzzle.
http://farm5.static.flickr.com/4042/4485116555_19cc0eaa85.jpg
http://farm3.static.flickr.com/2703/4485767454_77476dbdd0.jpg
http://farm5.static.flickr.com/4008/4485116637_ff085b0ab2.jpg
http://farm5.static.flickr.com/4002/4485766896_af83d349c4.jpg
http://farm5.static.flickr.com/4037/4485766950_50d5739344.jpg
http://farm3.static.flickr.com/2785/4485116905_1fa0e2ea6c.jpg
http://farm5.static.flickr.com/4052/4704387613_77542dac2e.jpg
http://farm3.static.flickr.com/2734/4485767622_7b04c3bd3e.jpg
http://farm5.static.flickr.com/4037/4485767292_1a37fe6c57.jpg
http://farm5.static.flickr.com/4038/4485116955_f9c47672c3.jpg
http://farm5.static.flickr.com/4051/4485115681_6d7419a00b.jpg
http://farm3.static.flickr.com/2753/4485116095_30161a56bb.jpg
http://farm5.static.flickr.com/4123/4831194968_3977dff9dc.jpg
http://farm5.static.flickr.com/4054/4538941056_cda5a8242d.jpg
http://farm3.static.flickr.com/2091/4515081466_43cd1624ce.jpg
http://farm3.static.flickr.com/2684/4485766664_3bb9dd9c80_m.jpg
http://farm5.static.flickr.com/4010/4485115557_a38aac0e1f.jpg
http://farm5.static.flickr.com/4055/4485115633_19e6e92276.jpg
http://farm5.static.flickr.com/4045/4485766710_08691e99ed_m.jpg
http://farm5.static.flickr.com/4024/4485115521_9ab2a33d53_m.jpg
http://farm5.static.flickr.com/4048/4505577820_81ce080f2a_t.jpg
http://farm6.static.flickr.com/5294/5389182894_920a54ce97_m.jpg
http://farm5.static.flickr.com/4152/5073487038_5bdb9e3cbc_t.jpg
http://farm5.static.flickr.com/4024/4485115401_67a8957509_m.jpg
http://farm5.static.flickr.com/4062/4485766842_2209843592_m.jpg
$ids = array(); // Where we will keep our unique list of IDs
$lines = array(/* your list of URLs here */);
foreach ($lines as $line) {
preg_match(
'|^http://[A-Za-z0-9\\.]+/[0-9]+/([0-9]+)_[a-f0-9]+.*\\.jpg$|',
'http://farm5.static.flickr.com/4054/4538941056_cda5a8242d.jpg',
$matches
);
echo $matches[1]; // 4538941056
$ids[] = $matches[1]; // Push that into the IDs array
}
$ids = array_unique($ids);
print_r($ids);
Use this code to get your ID Portion
$url = 'Your image url';
$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);
$id = substr($end,0,9);
And then run array_unique() to get the unique values.