How to pass multiple variables in a href? - php

I tried some code based on similar questions but keep getting error. Based on this similar question I tried:
$step1 = 'my_shop';
$step2 = 'https://my-website.com/';
echo '<a href="' .$step2. .$step1. '">';
Following the logic from this similar question I also tried:
$step1 = 'my_shop';
$step2 = 'https://my-website.com/';
echo '<a href="' .$step2&$step1. '">';

You should use the http_build_query() function, as it was designed for this:
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'php' => 'hypertext processor'
);
and then:
$base_url = 'https://my-website.com/';
$query_params = http_build_query($data);
$link = $base_url . '?' . $query_params;
echo 'link text';
Result:
link text

Related

PHP: How to use two dimensional array to display menu?

I think I'm picking this up pretty well, but I'm just stuck on this. I want to display this menu using an array and foreach loop:
<img src="/img/page-icons/credit-card21.png" />Payments
<a target="_blank" href="/cloud"><img src="/img/page-icons/upload123.png" />Cloud</a>
<a target="_blank" href="/portal"><img src="/img/page-icons/earth208.png" />Portal</a>
So to do that I need to turn that into this line in PHP:
echo '<img src="/img/page-icons/' . $image . '" />' . $title . '';
To fill that out in the loop we need to create something like this... which is where I'm stuck:
foreach( $stamp as $link => $target ){
echo '<a href="/' . $link . '" target="' . $target . '">';
foreach( $stamp[] as $title => $image ){
echo '<img src="/img/page-icons/' . $image . '" />' . $title;
}
echo '</a>';
}
I don't really know how to go about the above, just been messing around with it for a while today. I also don't want to always display target="' . $target . '" on every link.
The array would probably be a two dimensional array? Something like this any way:
$stamp = array(
'link' => array('title' => 'image'),
'link' => array('title' => 'image'),
'link' => array('title' => 'image')
);
EDIT:
There's some confusion of what 'target' is, I want to echo 4 values from an array into a link, target is one of the values. I didn't know how to use that in the array so I just left it out.
When you do:
foreach( $stamp as $link => $target )
The $link variable contains the string "link" and the $target variable is an array such as ['title' => 'image'].
What you should probably do is have an array like this:
// Init links
$links = array();
// Add links
$links[] = array(
'title' => 'My Title',
'href' => 'http://www.google.com',
'target' => '_blank',
'image' => 'image.png',
);
foreach ($links as $link)
{
echo '<a href="'.$link['href'].'" target="'.$link['target'].'">';
echo '<img src="/img/page-icons/' . $link['image'] . '" />';
echo $link['title'];
echo '</a>';
}
This is a bit more flexible approach that lets you add other data items to the structure in the future. That $links array could easily be generated in a loop if you have a different data source such as a database as well.
EDIT
To answer your further question, you can prefix the link building with a set of sane defaults like this:
foreach ($links as $link)
{
// Use the ternary operator to specify a default if empty
$href = empty($link['href']) ? '#' : $link['href'];
$target = empty($link['target']) ? '_self' : $link['target'];
$image = empty($link['image']) ? 'no-icon.png' : $link['image'];
$title = empty($link['title']) ? 'Untitled' : $link['title'];
// Write link
echo "<a href='$href' target='$target'>";
echo "<img src='/img/page-icons/$image' />";
echo $title;
echo "</a>";
}
you can set your array like:
$stamp = array(
'0' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target),
'1' => array('title'=>$title, 'image'=>$image,'link'=>$link,,'target'=>$target),
'2' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target)
);
and in foreach you can write
$i=0;
foreach( $stamp as $st=> $target ){
echo '<a href="/' . $st['link'] . '" target="' . $st['target'] . '">';
echo '<img src="/img/page-icons/' . $st['image'] . '" />' . $st['title'];
echo '</a>';
}

PHP Preg_Match array

I want to remove certain characters in a link. i.e.
'http://www.bbc.co.uk', strip everything and just be left with 'bbd'
At the moment i have the following:
$filteredFeed[$item->get_title()] = array('title' => $item->get_title(), 'permalink' => $item->get_permalink(), 'date' => $item->get_date('G:i d-M-y'),
'url' =>$item->get_link());
}
endforeach;
foreach ($filteredFeed as $items) {
echo '<li class="tips"><a href="' . $items['permalink'] . ' "target="_blank"">';
echo $items['title'];
echo '</a>';
echo ' ';
echo '<span class="date">';
echo $items['date'];
echo '</span>';
echo ' ';
//echo $date;
echo '</li>';
'url' =>$item->get_link()); - i get the link here.
How can i strip out the characters?
$url= 'http://www.bbc.co.uk';
$url = basename($url);
$url = str_replace('www.','',$url);
$url = preg_replace('/\.[^\.].*$/','',$url );
But this match always first subdomain exept www. TThen you may have interest to keep the basename.

Streamline this PHP snippet

I know this is a Wordpress based question, but I think the answer is definitely more stand-alone PHP.
On almost every site I do for a client I have to add some social media links, which come from an options page. I currently use this kind of snippet;
$twt = of_get_option('twitter');
$fcb = of_get_option('facebook');
$ins = of_get_option('instagram');
if ($twt) {
echo '<li class="twitter">Twitter</li>';
}
if ($fcb) {
echo '<li class="facebook">Facebook</li>';
}
if ($ins) {
echo '<li class="instagram">Instagram</li>';
}
This is fine if there are only a couple of links, but recently one of my main clients seems to be including every social media link under the sun to their designs so doing it this way can be a bit clunky.
Is there a way I can combine everything into a foreach or something?
Identify commonalities:
echo '<li class="twitter">Twitter</li>';
^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^
Identify varying parts:
echo '<li class="twitter">Twitter</li>';
^^^^^^^ ^^^^^^^
Identify dependencies and relationships:
$twt depends on of_get_option(...) whose parameter is the same as the twitter in 2.
The class and the name of the service are dependent on each other. Their relationship is apparently that the name is just the first-letter-uppercased version of the class, but I wouldn't rely on that necessarily.
Unify:
$services = array(
'twitter' => 'Twitter',
'facebook' => 'Facebook'
...
);
foreach ($services as $service => $name) {
if ($url = of_get_option($service)) {
printf('<li class="%s">%s</li>', $service, $url, $name);
// or, if you can't be sure that the variables are safe for HTML interpolation:
// printf('<li class="%s">%s</li>', htmlspecialchars($service), htmlspecialchars($url), htmlspecialchars($name));
}
}
Don't know if you mean exactly that, but check this code:
foreach(array('twitter', 'facebook', 'instagram') as $source)
{
$data = of_get_option($source);
if($data)
{
echo '<li class="'.$source.'">'.ucfirst($source).'</li>';
}
}
You could try something like this:
$social_media = array(
array( 'name' => 'Twitter', 'href' => of_get_option('twitter') ),
array( 'name' => 'Facebook', 'href' => of_get_option('facebook') ),
array( 'name' => 'Instagram', 'href' => of_get_option('instagram') )
);
foreach( $social_media as $s )
echo '<li class="' . strtolower( $s["name"] ) . '">' . $s["name"] . '</li>';
Then simply add the new social media site into the $social_media array.
Try the following:
$social = array('Twitter', 'Facebook', 'Instagram');
for($i=0;$i<length($social); ++$i) {
$twt = of_get_option($social[$i]);
if ($twt) {
echo '<li class="' . strtolower($social[$i]) . '">' . $social[$i]. '</li>';
}
}
You can add additional social networks by adding them to the array. It's a compact solution.

Flickr API returning duplicate images

I'm trying to get images from flickr using the Flickr API and I'm having trouble figuring out how to get only unique images. I've already reviewed the arguments for the specific method that I'm using and here's what I came up with:
<?php
class Flickr {
private $flickr_key;
private $flickr_secret;
private $format = 'json';
public function __construct( $flickr_key, $flickr_secret ) {
$this->flickr_key = $flickr_key;
$this->flickr_secret = $flickr_secret;
}
public function searchPhotos( $query = '', $tags = '' ) {
$urlencoded_tags = array();
$tags_r = explode(',', $tags);
foreach($tags_r as $tag){
$urlencoded_tags[] = urlencode($tag);
}
$url = 'http://api.flickr.com/services/rest/?';
$url .= 'method=flickr.photos.search';
$url .= '&text=' . urlencode($query);
$url .= '&tags=' . implode(',', $urlencoded_tags);
$url .= '&sort=relevance';
$url .= '&safe_search=1';
$url .= '&content_type=4';
$url .= '&api_key=' . $this->flickr_key;
$url .= '&format=' . $this->format;
$url .= '&per_page=10';
$url .= '&media=photos';
$url .= '&privacy_filter=1';
$result = #file_get_contents( $url );
$json = substr( $result, strlen( "jsonFlickrApi(" ), strlen( $result ) - strlen( "jsonFlickrApi(" ) - 1 );
$photos = array();
$data = json_decode( $json, true );
if($data['stat'] != 'fail'){
$photos = $data['photos']['photo'];
return $photos;
}else{
return false;
}
}
}
And I'll just call it in like:
$flickr = new Flickr($flickr_key, $flickr_secret);
$query = 'Kaspersky Internet Security 2013';
$tags = 'software';
$results = $flickr->searchPhotos($query, $tags);
foreach($results as $img){
$src = "http://farm" . $img['farm'] . ".static.flickr.com/" . $img['server'] . '/' . $img['id'] . '_' . $img['secret'] . '_m.jpg';
?>
<img src="<?php echo $src; ?>"/>
<?php
}
The problem here is that I'm getting duplicate images from time to time.
I also tried using the phpflickr library. But I'm still having the same issues:
$flickr = new phpFlickr($api_key);
$args = array(
'text' => 'Kaspersky Internet Security 2013',
'tags' => 'software',
'per_page' => '10',
'safe_search' => '1',
'content_type' => '4',
'media' => 'photos',
'sort' => 'relevance',
'privacy_filter' => '1'
);
$results = $flickr->photos_search($args);
$hashes = array();
$sources = array();
$images = $results['photo'];
foreach($images as $img){
$src = "http://farm" . $img['farm'] . ".static.flickr.com/" . $img['server'] . '/' . $img['id'] . '_' . $img['secret'] . '_m.jpg';
$current_hash = sha1_file($src);
if(!in_array($current_hash, $hashes)){
?>
<img src="<?php echo $src; ?>" alt="">
<?php
}
$hashes[] = $current_hash;
}
As you can see from the above code I've used sha1_file method to compare the hashes of each of the images returned from flickr. But that's a big performance hit:
without sha1_file: 0.81311082839966
with sha1_file: 6.8974900245667
Any ideas what else can I do to prevent flickr from returning duplicates? As you can see I'm only returning 10 images and that's all I need. I've also tried to add as many arguments that matches my needs but still no luck. Thanks in advance!
try on API explorer, will this give you the same result?
I tried using the param you specified, it returns 34 result in total..

How can I make this work? http_build_query example

How can I addapt the following http_build_query script for my webpage?
$params = array(
'p' => 'foo',
'lang' => 'bar'
);
echo http_build_query($params); // p=foo&lang=bar
echo '?' . http_build_query($params); // ?p=foo&lang=bar
Related to PHP url strings conflict "?" and "&"
Here's how my page works:
Español
English
<?php
$p = $_GET['p'];
$pages = array('g1', 'g2', 'g3');
if (!empty($p)) {
if(in_array($p,$pages)) {
$p .= '.php';
include($p);
}
}
else {
echo 'Page 1 Page 2</li> Page 3';
}
?>
You could write a function to merge query parameters with the current $_GET array.
<?php
function merge_queries(array $original, array $updates) {
$params = array_merge($original, $updates);
return '?'.http_build_query($params);
}
?>
Español
English
<?php
// code abbreviated for clarity
echo 'Page 1
Page 2
Page 3';
?>
You could do that very easy:
$urlpath = implode('&', $params);
$url = $yourhost . '?' . $urlpart;

Categories