if statement on one line if poss - php

I am printing an image using an ID which is generated. however i wanted to do a check to see if this image exists and if it doesnt print no-image.jpg instead...
<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" />
It would be great if this could be kept on one line is possible. Any help would be appreciated.

What Kristopher Ives says, and file_exists:
echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")
btw, your snippet is unlikely to work, as you seem to be combining plain HTML output and PHP without putting the PHP into <? ?>

My recommendation would actually be to abstract the decision making from the html tag itself, in a separate block of php logic that is not outputting html...here is an abbreviated example that assumes you are not using a template engine, or MVC framework.
<?php
$filename = 'th.jpg';
$filePath = '/public/images/' . $row['id'] '/';
$webPath = '/images/' . $row['id'] . '/';
//Logic to get the row id etc
if (!file_exists($filePath . $filename)) {
$filename ='no-image.jpg';
$webPath = '/images/';
}
?>
<img src="<?php echo $webpath . $filename;?>" />

Wow, this question gets asked and answered a lot:
http://en.wikipedia.org/wiki/Ternary_operation
You could do it by:
<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >

Related

Issue with passing variables in url for php

I feel a bit stupid having to ask this, but for the life of me it won't work and I know I must be missing something small. I have the following PHP code for a gallery of model's photos. I have 2 pages. guests1.php and guests2.php. Guests1 shows the thumbnails and lists all the models. guests2 will show a particular model's individual portfolio. I am trying to pass the model name in the url, as I need it for the title on the second page and also for the directory name, so that the page knows where to find the pictures.
Simple enough, I thought, just add it into the url as a variable. No problem... however no matter how I write it, it will not put it in the url. The name of the model is always missing... however if I echo the variable it does it no problem?! The pages are working wonderfully apart from this one little thing and it's driving me bonkers. Any help most appreciated.
Here is the code :
<?php
echo "<div class=\"guests-gallery\">";
echo "<ul class=\"guests-gallery-list\">";
$dirs = glob("guests/*", GLOB_ONLYDIR);
foreach($dirs as $model) {
$files = glob($model. "/*.{jpg,png,gif,JPG}", GLOB_BRACE);
foreach($files as $file) {
$m = basename($model);
echo "<li><a href=\"index.php?page=guests2&model=\"" .$m. "\">";
echo "<img src=\"" . $file . "\" alt=\"" .basename($model). "\"></a><br />
<h3>" .basename($model). "</h3></li>";
}
}
echo "</ul></div>";
?>
You're making your code harder to read by double quoting and escaping your HTML quotes so you're not spotting your mistake with the quotes, make it easier to read and write by using single quotes on your echos leaving the double quotes for the html then you won't need to escape them and it'll be easier to spot the extra unnecessary " you included.
Try this:
<?php
echo '<div class="guests-gallery">';
echo '<ul class="guests-gallery-list">';
$dirs = glob("guests/*", GLOB_ONLYDIR);
foreach($dirs as $model) {
$files = glob($model. "/*.{jpg,png,gif,JPG}", GLOB_BRACE);
foreach($files as $file) {
$m = basename($model);
echo '<li><a href="index.php?page=guests2&model=' .$m. '">';
echo '<img src="' . $file . '" alt="' .basename($model). '"></a><br>
<h3>' .basename($model). '</h3></li>';
}
}
echo '</ul></div>';
?>
try removing the quote s from the model and maybe try using the & character without using it encoded:
echo "<li><a href=\"index.php?page=guests2&model=" .$m. "\”>something</a></li>";
Tell me if this works.

Using a php function inside a php echo

I'm trying to setup my WordPress website so that if a post / page has a featured image assigned, this image will be used as the page banner. If however the page doesn't have a featured image, it must onload select a random image out of six available options. I've tried to used this if statement below:
<div id="slider">
<div class="theslide">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
else {
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6); '.jpg">';
}
?>
</div>
</div>
It works, but the random number function is not closing preperly, so the code ends up looking like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6 </div>
</div>
</div>
Instead of like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6.jpg">
</div>
</div>
I'm assuming my syntax is wrong for using php inside of the echo, but everything I try either has the same problem or cause a php error.
Any help would be appreciated.
Thanks in advance
Willem
If you don't need to know which header was chosen, just do this:
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';
Using more than one ; on a line is a no-go (you are essentially telling the php-interpreter that '.jpg">'; is an independant command - which will do nothing)
Assigning a variable (ie. $whatever = 'something) inside the echo statement won't be a problem in this case - though it really doesn't do any good either. What it does is create a new variable called $random that you could use afterwards to find out which header was used - but results will be unpredictable if used in the echo statement (ie. in your case the variable would contain [random number].jpg, not just the random number), instead assign the random number to $random first like this:
$random = rand(1,6);
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random . '.jpg">';
echo "We are using header {$random}, which was chosen at random.";
Note that the above example also shows an alternate way to include the variable in a string - using double-quotes you can simply write the variable directly inside the string itself. When doing so I recommend always using {} to wrap the variable though not needed in this case - this allows referencing more complex variables (such as array elements or object properties), and it makes the whole thing more readable too.
Other (IMO less readable, possibly more error-prone) solutions include:
$random = rand(1,6);
echo "<img src=\"/wp-content/uploads/link-ship-chandlers-banner-$random.jpg\">";
echo sprintf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
printf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
Actually this can work, but you end the line with ;.
So removing the ; and adding a .
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6) . '.jpg">';
do this alternatively you don't need to set this variable
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';

How to implement PHP inside a image src code?

<img src="socimages/logo/"<?php if ($soca == ""){ echo "logo.jpg"; } else { echo $anotherimage . ".jpg";} ?>>
Basically what I am trying to do is to change the end part of the image src, to pick from a range of specifically named images.
The syntax for the code is obviously not right since I closed the src after /logo/ with the ". But if I do not have the " then my php will not function.
I would suggest, don't mess the logic in your img tag.
<?php
$img = ($soca == "") ? "logo.jpg" : $anotherimage.".jpg";
?>
<img src="socimages/logo/<?php echo $img; ?>" />
Use a ternary, and remember to distinct between "" and '' :
<img src="socimages/logo/<? echo $soca == '' ? 'logo.jpg' : $anotherimage . '.jpg'; ?>">
This will produce a correct <img src="image.jpg"> tag.
A ternary conditional makes the line shorter:
<img src="socimages/logo/<?php echo ($soca=='')?'logo.jpg':$anotherimage.'.jpg';?>">
This is probably shortest:
<img src="socimages/logo/<?php echo ($soca=='')?'logo':$anotherimage;?>.jpg">
Or even this variant, but it depends on the short tags configuration of your site:
<img src="socimages/logo/<?= ($soca=='')?'logo':$anotherimage;?>.jpg">
But all variants are horrible style. You should always try to implement in a transparent manner, easy to read and understand. So instead store the final path inside a variable and echo that into the src attribute of the img tag.

Defining <img src = according to the end of the link

How do I set the src= of a <img> element, according to the end of my link?
Example 1:
Link:
http://www.endertec.com.br/hf/see-img.php?img=http://www.endertec.com.br/hf/do.php?imgf=325356456.png
<img> element in see-img.php file:
<img src="http://www.endertec.com.br/hf/do.php?imgf=325356456.png"/>
Example 2:
Link:
http://www.endertec.com.br/hf/see-img.php?img=http://www.endertec.com.br/hf/do.php?imgf=342424234.png
<img> element in see-img.php file:
<img src="http://www.endertec.com.br/hf/do.php?imgf=342424234.png"/>
I.E.: I want to know if there is any script that I can use in see-img.php do what I was demonstrating above file.
Edited
Try this:
<?php
//$str = 'http://www.endertec.com.br/hf/see-img.php?img=http://www.endertec.com.br/hf/do.php?imgf=342424234.png';
$str = 'http://www.endertec.com.br'.$_SERVER['REQUEST_URI'];
$src = str_replace('see-img.php?img=' , '' ,stristr($str , 'see-img.php?img='));
echo '<img src="'.$src.'"/>';
?>
In PHP you could do this:
$img_url = isset($_POST['img']) ? $_POST['img'] : null;
$img_file = isset($_POST['imgf']) ? $_POST['imgf'] : null;
Then with that $img_url you can do this:
if (!empty($img_url) && !empty($img_file)) {
echo '<img src="' . $img_url . '?imgf=' . $img_file . '"/>';
}
The idea is to get the URL values which are known as post values, assign them to a variable & then do a check where you echo the values into <img src= tags.
But that is the best that I can do based on the lack of detail in your question. But the concept is solid and should work in PHP.
You could try using a built in php function know as sttrpos, it will return an int with the position where the substring you need begins. Then a normal php substring will do the trick.

Adding A Dynamic Link In Php

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

Categories