How to use "If empty" or "if (isset)" in this scenario - php

In my site, I allow my users to upload an avatar. The following code is used to print the URL:
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
This will give us for example /wp-content/uploads/userphoto/2.thumbnail.png.
The problem is that if the user has not uploaded an avatar, the URL will of course be /wp-content/uploads/userphoto/. So it will be a broken image.
I want to display a custom image for users with no avatar, for example no-image.png. I'm guessing that this is done by adding an if (isset) statement there? I can't seem to figure out how to solve this.

You could use empty:
$image_id = get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . (empty($image_id) ? 'no-image.png' : $image_id);

Something like this should work, depending on if get_user_meta actually returns Null.
if (is_null(get_user_meta($user_info->ID, 'userphoto_thumb_file', true))) {
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/customimage.png';
} else {
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
}

You can do
if(!empty(get_user_meta($user_info->ID, 'userphoto_thumb_file', true)))
{
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
}
else
{
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/no-image.png';
}

You should test if the file exists :
if(!file_exists( $_SERVER['DOCUMENT_ROOT'] . $r)) {
$r = '/path/to/default/image.jpg';
}
With this approach, even if the user has uploaded an avatar, but for some reason the image is not present on the server, it will display the default avatar.

You can actually just check if the function returns something that evaluates to false. An empty string evaluates to false in php.
$img = get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
if(!$img) {
$img = 'no-image.png';
}
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . $img;

Related

if ($obj->hashes > $minimal_withdraw) do { ); $response but response is too much

everytime that there are 256 hashes available there should be added 1 credits to the user account.
but it keeps looping , it add's more credits to the user account then there are actually hashes been made...
how can i fix this?
this is where i am :
<?php //second one ,much loops to
$x = $obj->hashes;
$minimal_withdraw = "255";
if ($obj->hashes > $minimal_withdraw)
do {
$DBcon->query("UPDATE promotion_users SET credits=credits+1 WHERE username='$session'");
$response = file_get_contents("https://webminepool.com/api/PK_bzM7NcgKs2c4pkidkiNpp/withdraw/" . $userRow[username] . "/" . $minimal_withdraw);
$x = $obj->hashes;
} while ($x >= $minimal_withdraw) ;
?>
This is what i also try'd :
<?php // first one
//$minimal_withdraw = "256";
//if ($obj->hashes > $minimal_withdraw) { $DBcon->query("UPDATE * FROM promotion_users SET credits=credits + 1 WHERE username=='$session'");
//$response = file_get_contents("https://webminepool.com/api/PK_bzM7NcgKs2c4pkidkiNpp/withdraw/" . //$userRow[username] . "/" . $minimal_withdraw); }
?>
And this one (didnt even load):
<?php //didnt load page
//$x = $obj->hashes;
//$minimal_withdraw = "256";
//foreach ($x >= $minimal_withdraw) {
//$DBcon->query("UPDATE promotion_users SET credits=credits+1 WHERE username='$session'");
//$response = file_get_contents("https://webminepool.com/api/PK_bzM7NcgKs2c4pkidkiNpp/withdraw/" . //$userRow[username] . "/" . $minimal_withdraw);
//} ?>

Variable seems to keep it's initial value in if statement - PHP, SimpleXML

I have the following PHP code which should store the index of a single customer matched with an XPath expression in $customerIndexOfMatch and then uses $customerIndexOfMatch to edit the XML values of the customer located at that index.
My issue is that $customerIndexOfMatch gives the expected value but only outside of the if (isset($_POST['updateCustomer'])) statement and I'm not sure why it's doing this.
<?php
$customerIndexOfMatch = -1;
if (isset($_POST['search'])) {
$searchTerm = $_POST['searchTerm'];
$searchBy = $_POST['search-by'];
if (isset($searchBy)) {
if ($searchBy == "Last Name") {
$precedingCount = $customersXml->xpath('//customer/customerInfo/lastName[text()="' . $searchTerm . '"]/preceding::customer');
$ancestorCount = $customersXml->xpath('//customer/customerInfo/lastName[text()="' . $searchTerm . '"]/ancestor-or-self::customer');
$customerIndexOfMatch = (count($precedingCount) + count($ancestorCount));
}
elseif ($searchBy == "Customer Number") {
$precedingCount = $customersXml->xpath('//customer[#number="' . $searchTerm . '"]/preceding::customer');
$ancestorCount = $customersXml->xpath('//customer[#number="' . $searchTerm . '"]/ancestor-or-self::customer');
$customerIndexOfMatch = (count($precedingCount) + count($ancestorCount));
}
elseif ($searchBy == "Meter Number") {
$precedingCount = $customersXml->xpath('//customer[#meterNumber="' . $searchTerm . '"]/preceding::customer');
$ancestorCount = $customersXml->xpath('//customer[#meterNumber="' . $searchTerm . '"]/ancestor-or-self::customer');
$customerIndexOfMatch = (count($precedingCount) + count($ancestorCount));
}
}
}
// var_dump($customerIndexOfMatch); // not -1, gives expected value
// die();
$fname = someDataFromAForm
$mname = someDataFromAForm
$lname = someDataFromAForm
$address = someDataFromAForm
$ph1 = someDataFromAForm
$ph2 = someDataFromAForm
$ph3 = someDataFromAForm
// var_dump($customerIndexOfMatch); // not -1, gives expected value
// die();
if (isset($_POST['updateCustomer'])) {
// edit the details and write to file
$customersXml = simplexml_load_file('customers.xml', null, true) or die('Error: Cannot load XML from file customers.xml"');
// The value of $customerIndexOfMatch isn't the expected value, therefore I cannot properly write the edited data to file
// $customerIndexOfMatch represents the index of the customer that is to be edited. $customerIndexOfMatch isn't 0 based.
// the value of the index before this if statement is correct but in the if statement it is -1
// var_dump($customerIndexOfMatch); // -1, the default value for $customerIndexOfMatch
// die();
/*
$customersXml->customer[$customerIndexOfMatch]->customerInfo->firstName = $fname;
$customersXml->customer[$customerIndexOfMatch]->customerInfo->middleName = $mname;
$customersXml->customer[$customerIndexOfMatch]->customerInfo->lastName = $lname;
$customersXml->customer[$customerIndexOfMatch]->customerInfo->address = $address;
$customersXml->customer[$customerIndexOfMatch]->customerInfo->telephone[0] = $ph1;
$customersXml->customer[$customerIndexOfMatch]->customerInfo->telephone[1] = $ph2;
$customersXml->customer[$customerIndexOfMatch]->customerInfo->telephone[2] = $ph3;
$customersXml->asXML('customers.xml')
*/
}
// the html form where someDataFromAForm comes from
Are there any reasons as to why $customerIndexOfMatch keeps it's initial value when in the if (isset($_POST['updateCustomer'])) block, but before the block it has it's expected value? What options do I have to fix this issue? Still fairly new to PHP, can't see why it's doing this.
Any help is appreciated!

stopping duplicate urls in a form submission

I have a community site, where people can put up pages, and the url generates from their name. e.g. My Business, becomes my-business. I want to create a way, that if there is another My Business, it will check and make the url my-business-2, my-business-3, etc.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$slugs = array();
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
if(in_array($url, $slugs)) {
$max = 1;
while(in_array(($url . '-' . ++$max ), $slugs)) $url .= '-' . $max;
}
}
return $url;
}
This is my function, but this still wont work, as if there is a business called My Bus, it will make it my-bus-2, when it would have been unique at my-bus. I have experimented with other functions too, but this one is the closest I got. Can anyone tell me one that works perfectly?
So form my understanding, you are trying to avoid inserting/generating duplicate URL. Output will be something like this -
www.example.com/my-business
www.example.com/my-business-1
www.example.com/my-business-2
www.example.com/my-business-3
...
Try using this function -
function check_url($base_url, $new_url='', $num=0) {
if($new_url == '') {
$new_url = $base_url;
}
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url = '$new_url'");
if(mysqli_num_rows($qry) > 0) {
while($row = mysqli_fetch_array($qry)) {
$num++;
check_url($base_url, $base_url . '-' . $num, $num);
}
}
return $url;
}
Basically, this function will check the database until it finds a valid URL. Each time it will increment the number and recursively call the same function to generate new/valid URL.
Simple and basic!
#SpritsDracula has working code, but his function will query your database each time it executes. That being said, the recursion is a nice concept. Here is a piece of code that will save your the multiple database calls.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$baseUrl = $url;
$slugs = [];
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
$max = 1;
while(in_array($url, $slugs)) {
$url = $baseUrl . "-" . $max++;
}
}
return $url;
}

Error Sending Request for Last.FM Album Artwork

Currently, I am attempting to use the metadata from our streaming provider, StreamOn to send a request out to Last.FM to get the original sized album artwork. I am new to the world of APIs so it is rather confusing to me, however I am managing. My problem arises in the sending and receiving of the image over XML. In the code below, the contents of the metadata page are set as variables, which are then A.) displayed, and B.) used to look for the appropriate album artwork.
<?php
$request = file_get_contents('http://ckpk.streamon.fm/card.php');
$doubleQuotation = '"';
//Artist Request
$artistTitle = '"artist": "';
$artistTitlePosition = intval(strpos($request, $artistTitle));
$artistBeginningPosition = $artistTitlePosition + 11;
$artistEndingPosition = intval(strpos($request, $doubleQuotation, $artistBeginningPosition));
$artistName = substr($request, $artistBeginningPosition, $artistEndingPosition - $artistBeginningPosition);
echo '<b>' . $artistName . '</b>';
echo '<br />';
$artist = $artistName;
//Track Request
$trackTitle = '"title": "';
$trackTitlePosition = intval(strpos($request, $trackTitle));
$trackBeginningPosition = $trackTitlePosition + 10;
$trackEndingPosition = intval(strpos($request, $doubleQuotation, $trackBeginningPosition));
$trackName = substr($request, $trackBeginningPosition, $trackEndingPosition - $trackBeginningPosition);
echo '<i>' . $trackName . '</i>';
echo '<br />';
//Album Name Request
$albumTitle = '"album": "';
$albumTitlePosition = intval(strpos($request, $albumTitle));
$albumBeginningPosition = $albumTitlePosition + 10;
$albumEndingPosition = intval(strpos($request, $doubleQuotation, $albumBeginningPosition));
$albumName = substr($request, $albumBeginningPosition, $albumEndingPosition - $albumBeginningPosition);
echo $albumName;
$album = $albumName;
/*
* Last.FM Artwork Class
* Author: Caleb Mingle (#dentafrice)
* http://dentafrice.com
*/
class LastFM {
const API_KEY = "7facb82a2a573dd483d931044030e30c";
public static $size_map = array("small" => 0, "medium" => 1, "large" => 2, "extralarge" => 3, "mega" => 4);
public static function getArtwork($artist, $return_image = false, $size = "image_mega", $album) {
$artist = urlencode($artist);
$returnedInfo = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=" . self::API_KEY . "&artist=" . $artist . "&album=" . $album . "&image=" . self::$size_map[$size] . "&format=json";
$returnedInfo = #file_get_contents($returnedInfo);
if(!$returnedInfo) {
return; // Artist lookup failed.
}
$xml = new SimpleXMLElement($xml);
$xml = $xml->artist;
$xml = $xml->image[self::$size_map[$size]];
return (!$return_image) ? $xml : '<img src="' . $xml . '" alt="' . urldecode($artist) . '" />';
}
}
$artwork = LastFM::getArtwork($artist, true, $size, $album);
if($artwork) {
echo $artwork;
}
else{
return;
}
?>
I temporarily styled the elements to distinguish between them and I will worry about the styling later. However, I would like to know how to go about using the data to send a request to the Lsat.FM servers and receive the image to then properly display it. It's different with StreamOn than with something else, such as ShoutCast.
According to your reply in the comments, my hypothesis is confirmed.
Because you are requesting the Last.FM API to return JSON, you get the error:
Fatal error: Uncaught exception 'Exception' with message 'String could
not be parsed as XML
Because it is JSON, not XML.
You can fix this in two ways. Either change the response format to XML or do not use SimpleXML but json_decode() instead.
The first is probably the easiest to adjust. Try to change the &format=json part to &format=xml
I haven't tested this but highly probably that this will be supported by Last.fm.
Also note that you don't supply an image size, and "image_mega" the default value is not a valid value (see API specs # http://www.last.fm/api/show/artist.getInfo). You probably want want to use "mega" not "image_mega"
Updated, working code using JSON:
<?php
class LastFM {
const API_KEY = "7facb82a2a573dd483d931044030e30c";
public static $size_map = array("small" => 0, "medium" => 1, "large" => 2, "extralarge" => 3, "mega" => 4);
public static function getArtwork($artist, $return_image = false, $size = "mega", $album) {
$artist = urlencode($artist);
$album = urlencode($album);
$returnedInfo = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=" . self::API_KEY . "&artist=" . $artist . "&album=" . $album . "&image=" . self::$size_map[$size] . "&format=json";
$returnedInfo = #file_get_contents($returnedInfo);
if(!$returnedInfo) {
return; // Artist lookup failed.
}
$json = json_decode($returnedInfo, true);
$albumArt = $json["artist"]["image"][self::$size_map[$size]]["#text"];
return (!$return_image) ? print_r($json) : '<img src="' . $albumArt . '" alt="' . urldecode($artist) . '" />';
}
}
$artist = "Daft Punk";
$album = "Random Access Memories";
$size = "mega";
$artwork = LastFM::getArtwork($artist, true, $size, $album);
if($artwork) {
echo $artwork;
}
else{
return;
}
I know I rock. I choose JSON because I find it easier to work with. It returns exactly what you want, e.g.:
<img src="http://userserve-ak.last.fm/serve/500/10923145/Daft+Punk+6a00e398210d13883300e55ui6.png" alt="Daft Punk" />
Finally, I added urlencoding() for the album name, since I had issues with that in my example.
Working PHPFiddle

How to use array in function to get only value I want

I am trying to work this function in wordpress theme the way where I can get value only what I want and not all to gather. I am not much familiar with using array in function so I need you expert help to make it works and I would really appreciate that.
Here is my code
function gallery_artist($arg=null, $arg2=null, $arg3=null){
global $png_gallery_meta;
$png_gallery_meta->the_meta();
$gallery = get_post_meta(get_the_ID(), $png_gallery_meta->get_the_id(), TRUE);
$gallery_value = $gallery['image_artist'];
$artist_info = $gallery_value;
$string = $artist_info;
$artist = substr($string, 0, stripos($string, "/") );
// getting first name and last name from user id
$author_first_name = get_userdata(basename($string))->first_name;
$author_last_name = get_userdata(basename($string))->last_name;
$author_full_name = $author_first_name . ' ' . $author_last_name;
$user_id = '<a href=" ' . get_author_posts_url(basename($string)) . ' " title="more submissions of ' . $author_first_name .' '. $author_last_name . ' " >' . $artist . '</a>';
$arg = $author_first_name;
echo $arg;
$arg2 = $author_last_name;
echo $arg2;
$arg3 = $user_id;
echo $arg3;
}
After than I want to use this function to get any value I want and not unnecessary to render all three to gather. Means if I want only first name than I pass value only for that and it will render only first name so on..
Here how I want to use something. but you can suggest any code and type of function I have no issue.
<?php call_user_func_array('gallery_artist', array('first_name','last_name','artist_id') ) ?>
Big Big thanks to you all..
Try replacing the bottom section with this:
if(!is_null($arg))
{
$arg = $author_first_name;
echo $arg;
}
if(!is_null($arg2))
{
$arg2 = $author_last_name;
echo $arg2;
}
if(!is_null($arg3))
{
$arg3 = $user_id;
echo $arg3;
}

Categories