How to use strpos() to check a variable's path? - php

I have a home page that shows some uploaded images.
I take it from the database and I use strpos() to check the URL due to directory problems, and it works fine:
if(strpos($row['cImage'],"http://") === FALSE){
echo "<img src='serintercement/".$row['cImage']."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$row['cImage']."' style='width: 107px; height:102px;' />";
}
I need to use the same logic in a page that shows the clicked image, but it has a variable for it and I'm struggling to fix this since it's a different way to write:
<img src='<?php echo $resultData->cImage; ?>'/>
I can't fix the directory problem. How can I use strpos() similarly for this second code?

You can do it like this.
if(strpos($resultData->cImage,"http://") === FALSE){
echo "<img src='serintercement/".$resultData->cImage."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$resultData->cImage."' style='width: 107px; height:102px;' />";
}
Better option is you can define a function like this and call it
checkImage($row['cImage']);//to be called in your first page
checkImage($resultData->cImage);//to be called in your second page
function checkImage($image)
{
if(strpos($image,"http://") === FALSE){
echo "<img src='serintercement/".$image."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$image."' style='width: 107px; height:102px;' />";
}
}

You should be able to check the path similarly - as long as the property of the object is set and a string, strpos() can be used.
if(strpos($resultData->cImage,"http://") === FALSE){
echo "<img src='serintercement/".$resultData->cImage."' />";
}else{
echo "<img src='".$resultData->cImage."' />";
}

If these cImage strings are coming from your database, you could just correct them in the query call.
For example, if you are using MySQL, you could prepare the data using LOCATE() AND CONCAT() like this:
SELECT
IF(LOCATE('http',`cImage`)!=1,CONCAT('serintercement/',`cImage`),`cImage`) `new_cImage`
FROM ...
Moving the conditional process to your query, will make your "displaying" code read more smoothly because all of the preparations are completed ahead of time.
Outside of that, you can make your code more DRY by not repeating the html parts that come before and after the image variable...
This is an echo with an inline condition (not everyone likes this style):
echo "<img src=\"",(strpos($resultData->cImage,"http")===0?'':'serintercement/'),"{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
This is a separated conditional:
echo "<img src=\"";
if(strpos($resultData->cImage,"http")!==0){
echo 'serintercement/'
}
echo "{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
This is a function call if you have to do this multiple times in the same script:
function fixPath($img){
if(strpos($img,"http")===0){
return $img;
}
return "serintercement/$img";
}
echo "<img src=\"",fixPath($resultData->cImage),"\" style=\"width:107px;height:102px;\" />\n";
Notice that I am only checking for http and that I am very accurately checking that it comes from the first position in the string. Across all these alternatives, the point I am making is DRYness (which is a typical pursuit of all programmers). How you chose to implement it comes down to your personal preference.

Related

images are not displaying in web page when i retrieve them from server folder

I'm trying to retrieve all images from a folder in the server to my web page through PHP.
At local server, they're displaying fine but at main server, images are not displaying and showing error 404 not found
even though the images are there.
Please help me to get rid of this. The images are in Big Rock server.
Here is my code:
$filename = $_POST['file'];
echo '<table class="table1" border="0" width="100%" >';
echo "<tr>";
echo "<td class='td1'>";
$images = glob($_SERVER["DOCUMENT_ROOT"].
"/admin/gallery/".$filename.
"/*.*");
$count = 0;
foreach($images as $image) {
echo '<a href="'.$image.
'" target="_blank"><img src="'.$image.
'"class="img-rounded mySlides" width="200" height="150"/></a><br />';
if ($count < 3) {
$count++;
echo "</td>";
echo "<td class='td1'>";
} else {
echo "</tr>";
$count = 0;
echo "<tr>";
echo "<td class='td1'>";
}
}
The HTTP 404 Not Found Error means that the webpage you were trying to reach could not be found on the server. It is a Client-side Error which means that either the page has been removed or moved and the URL was not changed accordingly, or that you typed in the URL incorrectly. Give extensions in giving url.
There is no issue with the permission on the file. The error is due to mismatch of the Relative Path of the image. 404 means the resource doesn't exist.
You can check my answer here [can't find correct relative paths of CSS background-image
The problem is glob($_SERVER["DOCUMENT_ROOT"]."/admin/gallery/".$filename."/.").$_SERVER["DOCUMENT_ROOT"] will take path as home/xxxx/public_html/admin/gallery.which cannot open in the browser.The image will open only by the path like this "http://example.com/folder/img.jpg".so i have cropped the path till admin folder like home/xxx/public_html/admin/gallery to admin/gallery and in the img src i have given src="http://example.com/".$image as shown in the code
$filename=$_POST['file'];
echo '<table class="table1" border="0" width="100%" >';
echo "<tr>";
echo "<td class='td1'>";
$curdir=getcwd();
$images = glob($curdir."/admin/gallery/".$filename."/*.*");
$count=0;
foreach($images as $image)
{
$dir="http://screccs.com".str_replace($curdir,"",$image);
echo "<a href='".$dir."' target='_blank'>"; echo "<img src='".$dir."'class='img-rounded' width='200' height='150'/></a><br />";
if($count<3)
{
$count++;
echo "</td>";
echo "<td class='td1'>";
}
else
{
echo "</tr>";
$count=0;
echo "<tr>";
echo "<td class='td1'>";
}
}
echo '</tr>';
echo '</table>';
}
I believe issue is related to folder permissions. Give proper read permission and it will work.

how to add html & javascript after PHP exit

Please Help, nothing i add after the ?> works, i tried to put the code in a echo, but its not working would someone please put together a JSFiddle for me or point me in the right direction, i am fairly new with PHP, Thanks for the help
<?php
$filepath = 'http://www.godsgypsychristianchurch.net/music.json';
$content = file_get_contents($filepath);
$json = json_decode($content, true);
foreach ($json['rows'] as $row)
{
if ($_GET['album'] == $row[doc]['album'])
{
echo "<title>{$row[doc]['album']}</title>";
echo "<table align=\"center\" border=\"0\"><tr><td valign=\"top\" width=\"330\">";
echo "<img src=\"{$row['doc']['artwork']}\" alt=\"my image \" width=\"250\" /><br /><br />";
echo "<div class=\"albuminfo\" id=\"albuminfo\">";
print ' Download entire album.<p>';
echo "<font color=\"#fff\">Album: {$row[doc]['album']}</font><br />";
echo "<font color=\"#fff\">Church: {$row[doc]['church']}</font><br />";
echo "<font color=\"#fff\">Description: {$row[doc]['des']}</font><P><br /><P>";
echo "Tweet<br><br>";
print '<div id="like-button"></div>';
echo "<td valign=\"top\">";
echo "<div class=\"playlist\" id=\"playlist\">";
echo "<ol>";
$songCount = 0;
foreach ($row['doc']['tracks'] as $song) {
++$songCount;
$songUrl = $row['doc']['baseurl'] . urldecode($song['url']);
echo "<li>{$song['name']}<div id=\"download\">Download</li>";
}
echo "</ol>";
echo "<br><div id=\"player\"><audio preload></audio></div>";
echo "</div>";
echo "<P>";
echo "<small>To download a single MP3 at a time:</br><b>Windows OS:</b> hold the ALT button on the keyboard and click the Download button<br><b>Mac OSX:</b> hold the OPTION button on the keyboard and click the Download button<P><BR><b>Controls:</b><br>Play/Pause = spacebar</br>Next track = Right arrow<br>Previous track = Left arrow";
echo '</tr></td></table>';
}
}
exit;
?>
<!----NOTTING SHOWING UP---->
<!-- begin htmlcommentbox.com -->
<div id="HCB_comment_box">HTML Comment Box is loading comments...</div>
<script type="text/javascript" language="javascript" id="hcb"> /*<!--*/ if(!window.hcb_user){hcb_user={};} (function(){s=document.createElement("script");s.setAttribute("type","text/javascript");s.setAttribute("src", "http://www.htmlcommentbox.com/jread?page="+escape((window.hcb_user && hcb_user.PAGE)||(""+window.location)).replace("+","%2B")+"&opts=0&num=10");if (typeof s!="undefined") document.getElementsByTagName("head")[0].appendChild(s);})(); /*-->*/ </script>
<!-- end htmlcommentbox.com -->
Because you are using exit, which terminates the script. Get rid of that and it will continue to output the HTML underneath.
http://php.net/manual/en/function.exit.php
Omit the exit.
Exit will end Php processing.
With php exit the parser stops, and hands back all the content gathered until that point to the web server. Simply delete the exit; row.

Facebook Image Links

I am using the following code to link to an image on Facebook:
foreach($photos["data"] as $photo)
{echo $photo['source'];
echo "<img src=’{$photo['source']}’ />", "<br />";
}
The echo $photo['source'] shows the correct URL, and so does the src= in the image tag, but it tries to load from my site. So:
If the path to the image is http://a1.myimagepath.jpg
It tries to load http://www.mysite.com/%E2%80%99http://a1.myimagepath.jpg
take care,
lee
Your code contains curly quotes. You need to replace them with single quotes.
foreach($photos["data"] as $photo)
{echo $photo['source'];
echo "<img src='{$photo['source']}' />", "<br />";
}
Try to post the URL manually:
foreach ($photos["data"] as $photo) {echo $photo['source'];
echo "<img src=’http://a1.myimagepath.jpg’ />", "<br />";
}
You can also try without the foreach.

Can't make PHP function work inside HTML inside PHP

I wrote this code, it gets an image from a link that varies according to where you are:
<img src='http://chusmix.com/Imagenes/grupos/<?php echo substr(get_search_query(), 1); ?>.jpg'>
I want to make that code run if a PHP condition proves true, but I cannot make it work. It seems that the function doesn't return a value instead it takes the link textually. I mean it goes to http://chusmix.com/Imagenes/grupos/.jpg literally. However the code works correctly by itself.
This is the PHP code:
<?php
$search=get_search_query();
$first=$search[0];
if ($first=="#"){
echo "<html>";
echo "<img src='http://chusmix.com/Imagenes/grupos/<?php echo substr(get_search_query(), 1); ?>.jpg'>";
}
?>
You are already inside the php tag. So there is no need for <?php and ?>.
Try:
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr($search,1).".jpg'>";
Replace line
echo "<img src='http://chusmix.com/Imagenes/grupos/<?php echo substr(get_search_query(), 1); ?>.jpg'>";
with
echo "<img src='http://chusmix.com/Imagenes/grupos/" . substr(get_search_query(), 1) . ".jpg'>";

php - Decide whether an image exist and if it does show it

I have a code that shows a different image depending where on the page I am, but some places don't have an image so it displays a "no image" icon. I want to add a condition that checks if there really is an image in the given path and if returns false don't do anything. I have no idea how to do it.
This is the original code:
<?php
$search=get_search_query();
$first=$search[0];
if ($first=="#"){
echo "<html>";
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr(get_search_query(), 1). ".jpg'>";
}
?>
What I need to know is which function do I use to get a true/false of that image path. Thanks
Use file_exists
$image_path = 'Imagenes/grupos/' . substr(get_search_query(), 1) . '.jpg';
if (file_exists($image_path)) {
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr(get_search_query(), 1). ".jpg'>";
} else {
echo "No image";
}
http://php.net/manual/en/function.file-exists.php
You can use file_exists

Categories