PHP, random image code generation integrated with CSS - php

I had a piece of code which randomly selected an image for display on a website. That however was before I upgraded my HTML skills with CSS. Now I want to integrate the CSS into the PHP code.
I never was good with PHP, and only managed the random image generator because a friend did the coding for me. Now I have no idea how to integrate the required formatting characters from the CSS into the PHP.
Original Code:
<?php
$images = array("banner001.jpg", "banner002.jpg", "banner003.jpg",
"banner004.jpg", "banner005.jpg", "banner006.jpg", "banner007.jpg", "banner008.jpg",
"banner009.jpg", "banner010.jpg", "banner011.jpg", "banner012.jpg", "banner013.jpg",
"banner014.jpg", "banner015.jpg",); mt_srand((double)microtime() * 1000000);
$num = array_rand($images);
print("<img src=\"_pic-lib/banner-bg/".$images[$num]."\" alt=\"A random banner image\" class=\"bordered\" id=\"rightside\" />");
?>
Working HTML w/ CSS that does a single image:
<table id="banner"><tr><td id="banner" style="background-image:url('_pic-lib/banner-
bg/banner005.jpg')"><img src="_pic-lib/banner.png" alt="NCPAM GRS Banner" /></td>
</tr></table>
Hybrid code I have so far: (which doesn't work)
<table id="banner"><tr><?php $images = array("banner001.jpg", "banner002.jpg",
"banner003.jpg", "banner004.jpg", "banner005.jpg", "banner006.jpg", "banner007.jpg",
"banner008.jpg", "banner009.jpg", "banner010.jpg", "banner011.jpg", "banner012.jpg",
"banner013.jpg", "banner014.jpg", "banner015.jpg",); mt_srand((double)microtime() *
1000000); $num = array_rand($images); print("<td id=\"banner\" style=\"background-
image:url('_pic-lib/banner-bg/".$images[$num]. '\")" alt=\"A random banner image\"
/>");?></td></tr></table>
Website where code is to be used.
The picture on top is what the final result is supposed to be. The second picture is the randomly selected picture code, without the CSS integrated. The third image... which isn't there... is the final integrated version.
#

Actually figured it out. Turns out that the "View Page Source" in firefox is a decent code debugger. It has syntax highlighting which can be very helpful in diagnosing code errors.
<table id="banner2"><tr><?php $images = array("banner001.jpg", "banner002.jpg",
"banner003.jpg", "banner004.jpg", "banner005.jpg", "banner006.jpg", "banner007.jpg",
"banner008.jpg", "banner009.jpg", "banner010.jpg", "banner011.jpg", "banner012.jpg",
"banner013.jpg", "banner014.jpg", "banner015.jpg",); mt_srand((double)microtime() *
1000000); $num = array_rand($images); print("<td id=\"banner2\" style=\"background-
image:url('_pic-lib/banner-bg/$images[$num]')\" >");?><img src="_pic-lib/banner.png"
alt="NCPAM GRS Banner" /></td></tr></table>

Related

PHP check if file_exists without extension then Ajax a div with appropriate media tag (img or video) based on filepath

First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.

i want to retrieve data from MySQL db by displaying it using table, arrange it the same way it appear in the image

<?php
$con = mysqli_connect("localhost","root","","shady");
$query = "SELECT * fROM hall1 ";
$result = mysqli_query($con,$query) or die(mysqli_error());
echo "<form action='food.php' method='post'>";
echo "<table >";
$size = 0;
while($row = mysqli_fetch_array($result))
{
$imagewidth=200;
if($size > 900)
{
echo"<tr>";
}
echo'<td width='.$td3=100 .'px > </td>' ;
echo'<td width='.$td1=200 .'px> <label><input type="radio" name="radii" value='.$row[1].' checked> <img src="'.$row['image'].'" width="200" height="200" style="margin-top:10px;"> </label></td>' ;
echo"<td width=".$td2=200 ."px> Name &nbsp: " .$row[1] ."<br> Size &nbsp &nbsp : ".$row[2] ."Person <br> Price &nbsp &nbsp: ".$row[3] ." SDG <br> See More </td>";
$size+= $imagewidth+$td1+$td2+$td3;
if($size > 900)
{
echo"<tr>";
}
}
echo"</table>";
echo "<BR><BR><BR><CENTER><input type='submit' name='radiii' value='next' width='200PX' height='200PX' ></a> </CENTER></b>";
echo "</form>";
}
?>
There are many problems with your code:
It's unclear what the variable size does. I'm willing to bet it's unnecessary
You are using deprecated code. The width attribute on HTML elements is no longer supported, and if you insist on using it, you should only enter the width in pixels without the px like so: <td width="200">. The <center> tag is also deprecated.
Your <label> tag is pretty much useless. What are you trying to achieve with it?
It's a bad practice to set the widths on all rows, just set the widths on the first row's cells. Even better, do not use any style directly on the HTML tags and using CSS rules instead.
Lastly, i believe it would be much more readable code to NOT echo HTML and instead use the following approach to "plug in" your variables from PHP into HTML code :
<? $a = "Some variable"; $b = 123; $c = "http://example.com/img/1.png"; ?>
<p><strong>My variable a: <?=$a?></p>
<p><strong>My variable b: <?=$b?></p>
<p><strong>My img: <img src="<?=$c?>"></p>
In short, wrap your PHP logic in <? and ?> (be sure to have short_open_tag = On in your PHP settings or you'll need to use the alternative opening tag <?php like you did.
The write plain old HTML without all the echo. Whenever you want to echo something you simply write a new PHP opening tag like so :
<? echo $a ?>
OR, the shorthand version
<?=$a?>
Now your real problem is about designing the page. And i think you are starting in the wrong order. I would suggest you
1- Build a design that works using some IDE like Adobe Dreamweaver or a freeware alternative. With that tool, make the design for 1 item (1 iteration of your while loop).
The next step is to see how you're gonna repeat it. You seem to want a Horizontal list that wraps around lines at a certain width. One way you would do that is that you would wrap all the list items with a div element for which you will set a fixed width. And inside you will have the code you have for each item repeated for all items. If your outer div has a width of 900px and each element consumes 300px in width and you have 9 items, you would have a 3x3 grid.
Here is a summary code of what i explained. In your PHP file you would have:
<div class="grid">
<? while($row = .... ){ ?>
<div class="item">
<!-- The code for the image, label and whatever information you want to have for each item -->
</div>
<? } ?>
</div>
And a CSS file which you would link in your PHP file, containing:
.grid {
width: 900px;
}
.item {
width: 300px;
}
If the information your are displaying come from user input you should sanitize it and have some sort of logic that breaks long text, either with CSS or PHP.
In short, you seem to be doing all the math in PHP so that you jump into a new line once the total width exceeds your desired grid width. This is a design issue and not a logic / programming issue. Therefore you should tackle this with CSS and not PHP.
I strongly suggest you either follow a video tutorial (there are plenty online) or read some documentations on HTML, CSS, JavaScript, PHP and MySQL in that order.
Here is a link to get you started: Mozilla Developer Network

How to connect mySQL to SVG using RaphaelJS?

I am trying to link a MySQL DB to an SVG image to dynamically change the SVG elements with Raphael JS.
I have a MySQL DB where I query using PHP and display the results in table form to an html page: (The script below works and displays the username and a picture only when the condition of the timestamp is met.)
<?php
mysql_connect("","","");
mysql_select_db("");
$res=mysql_query("select username, picture from 'table' WHERE status > UNIX_TIMESTAMP(NOW()) - 300");
echo "<table>";
if (!$res) {
die("Query to show fields failed");
}
$fields_num = mysql_num_fields($res);
echo "<h1>Table:Status</h1>";
echo "<table border='1'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($res);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>"; echo $row["username"]; echo "</td>";
echo "<td>"; ?> <img src=" <?php echo $row["picture"]; ?>" height="50">
<?php
How can I take the similar concept above of displaying the results in table form to an SVG image where the SVG elements will change/update only when the query condition is met?
Here is my sample SVG image with 5 elements:
<polygon fill="#B2B2B2" points="150.3,8.8 203.8,31.7 169.8,91.4 133.4,75.8 "/>
<circle id="circleT3" circle fill="#FFFFFF" cx="163.1" cy="53.6" r="7.3"/>
<circle id="circle3_1" circle fill="#CCCCCC" cx="184.5" cy="82.4" r="7.3"/>
<circle id="circle3_5" circle fill="#CCCCCC" cx="136.6" cy="27.2" r="7.3"/>
<circle id="circle3_4" circle fill="#CCCCCC" cx="166.4" cy="7.3" r="7.3"/>
Can someone point me to some sample code or tutorial? Or is there a better way to do this? Thanks.
EDIT:
In MySQL DB I have a column for username, password and timestamp. When a user logs into webpage the timestamp updates. The PHP code above is used to query who has logged within 5 minutes ago from current time.
What I would like to do with this information with SVGs is create a graphical representation of the login.
So each username will have their own SVG element (a circle) associated with them and when they log in/out, that SVG element (code above) will change color.
Right now I do not know how to link the username with my SVG elements so the SVG element will dynamically update like my table I query from MySQL when the timestamp changes.
The answer will depend on further information that isn't really available until the rest is written.
You could combine Snap (to modify existing inline SVG or create it) or Raphael (to create new SVG only, you can't use it to modify inline SVG), or another SVG library of choice (eg svg.js or jquery.svg maybe).
Assuming you already have something to use on the page, that is showing the logged in user, you could do something like in pseudocode...
loop user;
if( document.getElementById( userId ) ) Snap('#' + userId + '_image').attr({ fill: 'green' });
(The svg reference may be the same as the circles, but somewhere you would need some type of lookup to know which circle is which userid)
This assumes the svg is on the page. If its not, you could create it with
paper.circle(x,y,r).attr({ fill: 'green' });
If you want it dynamic (so status changes without a refresh), you may need to tie ajax calls to get status from the mysql db, but if you already have a user name displaying on the page, I'm assuming that is already taken care of.
I have successfully update the svg element color to when the user logs in, the corresponding circle will change color. So I have my svg code from illustrator. I then put in this script in my php file:
window.onload = function () {
if(document.body.innerHTML.toString().indexOf('username') > -1){
circle1_1.setAttribute("fill", "yellow");
};
};
Whenever a user logs in, the info is populated on the table in the html from the MYSQL query and the script looks to see if that username is on the page and if it is, change color of SVG element.
So it basically links the SVG element to any value/variable.
Not the prettiest code or logic out there but for anyone else doing something similar, enjoy.

Base64 image doesn't show when using PHP

I need to display an image which is in Base64 format. When I build the img tag in PHP it doesn't show the image (just the defualt 'broken image' icon). When I view the page source and click on the Base64 data is shows the picture as expected. Also, if I copy and paste the page source and save it as an HTML file it displays as expected. I also tried a random image and that worked however as my image works from a .html file I assume it is OK and should work?
The .php code:
header('content-type: text/html');
...
echo "<html><head></head><body>";
echo "Name = $name<br/>";
echo "<img src=\"data:image/jpg;base64,$photo\"/>";
echo "</body></html>";
The HTML from View Source:
<html>
<head></head>
<body>Name = Andrea Pilipczuk<br/>
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAyADIAA...{too big to fit here].../9k="/>
</body>
</html>
EDIT:
This didn't come up in View Source but digging around Chrome, I inspected the image element and found at the end was "9k=�������". Is this some kind of padding? When I edited the element to remove these the image showed up as expected.
The following code removes the random characters and displays the image correctly but seems a bit hacky, would obviously prefer to solve the underlying issue.
$unpadded = explode("=", $photo);
$padding = strlen($unpadded[0]) % 3;
$padded = $unpadded[0];
while ($padding > 0) {
$padded .= "=";
$padding--;
}
echo "<img src=\"data:image/jpeg;base64,$padded\"/>";

dynamic iframe height depending on PHP content?

How can I set my Iframe height to be dynamic to its content.
The content is only PHP code, nothing else.
I use the php to query database, and then show some ads. The more ads, the higher the iframe should be.
I thought height='100%' should do it, but no...
I have read other Q but their solutions doesn't work for me.
Suggestions ?
Thanks
You have to set height of iframe in javascript. JavaScript should be in page inside the iframe (must be if page with iframe and page in iframe are from different domains).
a.html:
<iframe src="b.html" id="myiframe"></iframe>
b.html:
<div style="height: 500px; background:magenta;"></div>
<script>
parent.document.getElementById('myiframe').style.height = document.body.offsetHeight+'px';
</script>
If the ads are just text, you can use line height * number of lines as the height. I assume you know the font size, and number of lines can be found by counting <br />'s:
<?php
// $content is your ads
// assuming ads.php returns an ad with an id, this example uses ad #10
// We are reading it with a full url because we don't want to read it as just
// a text file (we want it to be interpreted by php before we load it)
$content = file_get_contents('http://www.example.com/ads.php?id=10');
$line_height = 12; // line-height: 12px; is set in CSS
$number_of_lines = substr_count($content,'<br />'); // you can search for <br>
// and <br/> as well if you
// need to
$height = $line_height * $number_of_lines; // You may also want to have padding
?>
<iframe src="ads.php?id=10" height="<?php echo $height; ?>" />
EDIT: changed $font_size to $line_height

Categories