Image is not taking 100% of div? - php

I am trying to create a paragraph and next to that paragraph are images that are generated randomly from a database table. The main container is called ".container" and this includes every element. .container is set to width: 90%. The paragraph (.header) floats to the left and has a width of 70%. The generated images (.recommend) floats to the right and has a width of 30%. Everything works out fine, but the only problem is that when I set the images to take up the whole space of the .recommend div (width: 100%), but it doesn't do that. Instead, the width of the images are 30%. How do I make the images take up the whole space of the .recommend div?
<!DOCTYPE html>
<html>
<head><link type="text/css" rel="stylesheet" href="/science/template.css"></head>
<body>
<div class="container">
<div class="header">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="recommend">
<?php
$numArray = array();
for ($i = 1; $i <=10; $i++)
{
$numArray[$i] = $i;
}
shuffle($numArray);
$resultSet = $db->query("SELECT * FROM table");
if ($resultSet->num_rows != 0)
{
while ($rows = $resultSet->fetch_assoc())
{
$id = $rows["id"];
$image1 = $rows["image1"];
$image2 = $rows["image2"];
$image3 = $rows["image3"];
$title = $rows["title"];
$title2 = $rows["title2"];
$title3 = $rows["title3"];
echo "<div class=row>";
if ($id == $numArray[0])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
if ($id == $numArray[1])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
if ($id == $numArray[2])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
echo "</div>";
}
}
?>
</div>
</div>
</body>
</html>
CSS
.container{
background--color: green;
width: 90%;
height: auto;
}
.header{
background-color: blue;
float: left;
width: 70%;
}
.recommend{
background-color: red;
width: 30%;
float: right;
}
.recommend img{
width: 100%;
}

It would be FAR more useful to see the rendered HTML than the PHP that generates the html.
The image is taking the full width of the containing div - which is set to 30% width. This markup: <div class=col-md-4 id=left> is using a Bootstrap grid class. And, col-md-4 tells the div to be 4/12 (or 30%) of the width of the parent. Since the parent is .recommend, then the div is 30%, and the image inside is 100% of THAT (which means it is 30% of the .recommend div)
So, you can either remove the col-md-4 class from the divs, or you can try and resolve it another way.

According to the CSS provided .recommend div is set to width:30%
All the child elements that have width:100% (images) will only take up as much space as .recommend div, which is 30%

Related

PHP- Session lost upon refresh or revist

I'm new to php as you can tell and I'm having trouble with my session.Session is being lost upon refreshing page. I have a simple button that toggles between light and dark mode, it works and I store the value into a session value. I'm able to print the value and see that it is being stored, however upon a refresh or a revisit, the mode switches to the opposite mode and then upon refresh/revisit, the state is actually saved. I've tried to search for my issue but I cant find anything and I'm off to bed so I thought I may as well post in the meantime. I'm not sure what I'm missing, probably something obvious, but I appreciate the help. I can only use PHP for this by the way.
<?php
session_start();
//header('Refresh: 3000; url=index.php');
echo "" . $_SESSION['color'] . "";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
<!DOCTYPE html>
<html lang = "en-US">
<head>
<link rel="stylesheet" href="index.css">
<title>
Web Technologies
</title>
</head>
<body>
<?php session_start();
include_once "templateFunctions.php";
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
//session_register('color');
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
}
}
/*$color = "rgb(48, 48, 48)";
setcookie('color', $color, time() + 10, '/');
$_COOKIE['color'] = [$color];
echo "<p>'$cookie'</p>";
echo "<body style = 'background-color: $cookie;'>";
else {
$_SESSION['color'] = "rgb(54, 53, 53)";
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
}
*/
?>
<div class = "header">
<div class = "title" >
<h1>Jimbo Fimbo</h1><h2><u>Software Stuff</u></h2></th>
</div>
<div class = "img">
<img id = "img1" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTci5Mqm2mgMe_9KfJR0TqMEd-A_wtmqq69cru0wed7OEQF6jVAYycqCY_KzWV0o3hIVYs&usqp=CAU" alt="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
</div>
</div>
<hr style = "margin-bottom: 20px;">
<div class = "colgroup">
<div class="column1">
<h3 style = "text-align: center;">Menu</h3><hr style = "color:white;">
<ul style = "padding-left:20px; font-size: 25px;">
<li>GitHub<br></li>
<li>Courses<br></li>
<li>School<br></li>
</ul>
</div>
<div class="column2">
<h1>About Me</h1>
<img id = "img2"src="https://i.ytimg.com/vi/KEkrWRHCDQU/maxresdefault.jpg">
<p>
Heres some lorem ipsum! <br> Lorem ipsum dolor sit amet. Reprehenderit sunt est quia
necessitatibus est eius quis. Est dolor adipisci et dolor molestiae hic vitae expedita eum inventore quam aut mollitia natus. Qui quia
dolor aut totam Quis qui expedita repudiandae non quam magni et enim ipsa qui consequatur omnis. Ea incidunt debitis est nemo nesciunt
eum quia rerum eum recusandae sunt nam maiores saepe. Hic omnis dolores ab deserunt vero cum fugiat explicabo vel perferendis numquam.
Sed unde voluptatibus quo aliquid iure rem accusamus voluptatum aut maxime adipisci id molestiae voluptatem? In quia necessitatibus et
provident id nobis eius ea enim voluptatem in aliquam voluptas ut similique facilis. Et porro ipsam eos excepturi voluptatem non ullam sint.
</p>
<p>Stuff goes here </p>
</div>
<div class="column3">
<p style = "text-align: center;">Enrolled Courses</p>
<hr style = "color:white;">
<ol style = "padding-left: 20px; font-size: 25px;">
<li>CS-3753</li>
<li>CS-4393</li>
<li>CS-4413</li>
<li>CS-4423</li>
<li>CS-4843</li>
</ol>
<form action="index.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Dark Mode">
</form>
</div>
</div>
<footer class="foot">
Copyright 2022, Jimbo Fimbo
</footer>
</body>
</html>
I'm expecting what I mentioned above.
I've looked over the code to no avail, I've tried using another session variable to save the color change, I tried saving the session to a path using said method, and I've looked on the internet for similar problems but I guess I suck at googling since this seems like it would be straightforward.
If you want to get rid of the problem that the session variable will be "toggled" on page refresh, One of the ways is to separate the change color part from your display part, so the form submission target can be set to "changecolor.php", which will trigger a page redirection to index.php upon changing the session variable :
index.php
<?php
session_start();
/// initalize the color to be white if no color session variable
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "white";
}
echo "<body style = 'background-color: " . $_SESSION['color'] . ";'>";
?>
/// other HTML code
<form action="changecolor.php" method = "post" accept-charset=utf-8 >
<input type="submit" name = "dark" id ="submit" value = "Change Color Mode">
</form>
changecolor.php
<?php session_start();
if (isset($_POST['dark'])) {
if (!isset($_SESSION['color'])) {
$_SESSION['color'] = "rgb(54, 53, 53)";
} else {
if ($_SESSION['color'] == "rgb(54, 53, 53)") {
$_SESSION['color'] = "white";
} else {
$_SESSION['color'] = "rgb(54, 53, 53)";
}
}
header("Location: index.php");
}
?>

Capture the image in background and save in folder in PHP

Capture the image in the background and save it in a folder in PHP.
I have created a PHP page in which we capture the image of an HTML using html2canvas() and via ajax save that image in a folder.
When I run the code from the browser it shows an HTML and saves the image in a given folder. (Here it is working fine).
The issue is when I run the same file using cmd like via PHP cmd or via CRON (php test.php) then that is not generating an image just render HTML in the terminal.
How I run the same code in the background and save in the generated image in a folder?
test.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<button type="button" id="capture">Capture & Save</button>
<div class="parent-wrapper">
<div class="wrapper-box" id="canvas" width="1080" height="1080">
<div class="heading">
Lorem Ipsum
</div>
<div class="sub-heading">
Lorem ipsum , Lorem
</div>
<div class="paragraph">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="bottom-heading">
#Lorem
</div>
</div>
</div>
<script type="text/javascript">
function truncate(source, size) {
return source.length > size ? source.slice(0, size - 1) + "..." : source;
}
var para = document.querySelector('.paragraph');
var res = truncate(para.innerHTML, 280);
para.innerHTML = res;
</script>
<script src="jquery-3.5.1.min.js"></script>
<script src="html2canvas.min.js"></script>
<script type="text/javascript">
$(function(){
$('.movable_div').on('contextmenu', function(){
return false;
});
$('#capture').click(function(){
div_content = document.querySelector("#canvas");
html2canvas(div_content, {
dpi: 96,
width: 1080,
height: 1080,
}).then(canvas => {
data = canvas.toDataURL('image/jpeg', 1);
save_img(data);
});
});
// Onload Click capture
$('#capture').click();
});
//to save the canvas image
function save_img(data){
//ajax method.
$.post('save_jpg1.php', {data: data}, function(res){
});
}
</script>
</body>
</html>
save_jpg1.php
<?php
//just a random name for the image file
$random = rand(100, 1000);
$savefile = #file_put_contents("output/$random.jpg", base64_decode(explode(",", $_POST['data'])[1]));
//if the file saved properly, print the file name
if($savefile){
echo $random;
}
?>
Thanks in advance.
Tried below code also but not work for me:
setTimeout(function(){
div_content = document.querySelector("#canvas");
html2canvas(div_content, {
dpi: 96,
width: 1080,
height: 1080,
}).then(canvas => {
data = canvas.toDataURL('image/jpeg', 1);
save_img(data);
});
}, 5000);
You can achieve this by using below library.
Source: https://github.com/stil/gd-text
Wrote the script in PHP and run via terminal to create image in background.
The terminal doesn't know how to render an html file like a browser does - the terminal will simply output the html as a text file. I think there may be a way to programmatically trigger such a rendering, and you could update the javascript to trigger the html2canvas when the page loads rather than after a click. In that way, you could trigger it from the command line, it would render, and fire the save function with the image.
Looks like this might have some ideas for how to run an html file from the terminal:
How can I run a html file from terminal?
Specifically, you may want to try serving the html file locally, and triggering a browser view

PHP : How to break a line

I am programming on wordpress and I want to edit a php file. I want the text to be displayed with line breaks and not all in one line.
Here is my code(I want jonh in one line and travolta in another but it gets displayed in one):
<div class="slide">
<img class="animated fade_left" src='<?php echo esc_url(onepage_get_option('onepage_testimonial_2_image', ONEPAGE_DIR_URI . "assets/images/team2.jpg")); ?>' onmouseover="javascript: this.title = '';" title="">
<div class="bx-caption animated fade_right"><span><a class="arrow"></a><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_content', __('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.','one-page'))); ?><a class="testimonial"><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_name', __('john \n travolta','one-page'))); ?></a></span></div>
Any suggestions?
If you want the link / element with the class testimonial on a new line, I would use css as that keeps it flexible and makes it easy to change if you want to do it differently in the future.
So in your css file:
.testimonial {
display: block;
}
In general, I would try to keep presentational stuff out of the php code.

Fulltext-search in php without database

I have a really small webpage written in php (approx. 5 pages + blog entries). All pages are located in php files on the server side (no database is used). So far I managed to search inside my 'blog entries' - because these are just plain textfiles with HTML markup (I strip the tags & performing a search operation):
$file_name=array();
$search_string="";
if(isSet($_GET["query"])){
$search_string=$_GET["query"];
}
$search_result="";
$files="";
$phpfilename="";
$i=0;
if (!$search_string){
echo 'No query entered<br />';
}else{
if ($handle = opendir('content/')) {
while (false !== ($file = readdir($handle))){
if(strrchr($file, '.') === ".txt"){
$filename[]= $file;
}
}
closedir($handle);
}
foreach($filename as $value){
$files="content/$value";
$fp = strip_tags(file_get_contents($files));
if(stripos($fp, $search_string)) {
$search_result.=preg_replace('/<[^>]*>[^<]*<[^>]*>/', '', substr($fp,0,255)); // append a preview to search results
}
if($search_result!=""){
echo $search_result;
}else{
echo "No Results<br />";
}
}
}
Of course that works just because the files are plain text. But I've got also pages that are real 'php' files and want to perform a search operation on them too. But I don't want to search inside the 'php code' of course. I figured out, that I would need the preparsed files that the browser gets from the webserver - I thought about using file_get_contents()‎ with http requests to all my pages (ok, 'just' about 5 pages but still)...
I've read here on SO that it's considered bad practice to do so and it feels like I'm taking the wrong approach.
Any ideas & suggestions would be highly appreciated.
Edit: A example for a regular page that I want to be able to search in
index.php
<?php ob_start(); require_once("./include/common.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $lang['WEBSITE_TITLE']; ?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="keyword, keyword, keyword" />
<link href="css/main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="page">
<!-- Header Area -->
<?php include("./include/header.php"); ?>
<?php include("./include/banner.php"); ?>
<div id="content">
<?php
$page = '';
if(isSet($_GET["page"])){
$page=$_GET["page"];
}
switch($page){
case 'category_1':
include("./include/category_1.php");
break;
case 'about':
include("./include/category_2.php");
break;
case 'contact':
include("./include/contact.php");
break;
default:
include("./include/home.php");
}
?>
<!-- /content --></div>
<!-- /page --></div>
<br />
<br /><br /><br />
<!-- Footer Area -->
<?php include("./include/footer.php"); ob_end_flush(); ?>
</body>
</html>
/include/category_1.php
<?php echo '<h2>'.$lang['NAVI_CAT_1'].'</h2>'; ?>
<div id="entry">
<br/>
<?php echo $lang['CAT_1_TEXT']; ?>
</div>
language file
<?php
$lang = array();
$lang['NAVI_CAT_1'] = 'Category 1';
$lang['CAT_1_TEXT'] = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.';
?>
Why not include into a buffer and then search the buffer's contents?
ob_start();
include ('index.php');
$contents = ob_get_clean();
//the $contents now includes whatever the php file outputs
I actually use this method in production code for all kinds of things, but mainly previewing site-generated emails before users send them. The nice thing is, you can use this on all the files, not just the php files.
this is failed by design.
consider not using plain mixed html sides. try to use xml files or wathever.
the alternative is crawling your own side. take a look at http://symfony.com/doc/current/components/dom_crawler.html

PHP - How can I retrieve and process all images and their parent anchor tags from a content block?

Note: I'm using Wordpress, but I don't believe it's relevant to the answer, so I've asked it on SO. If I'm wrong, please tell me/move the question.
Okay, I'm loading up blocks of rich content (via Wordpress) which frequently contain many images wrapped in anchor tags. I'd like to step through all of them in order to display them as a tags with their relevant imgs inside.
I've already found this handy bit of regex-powered code which gets me the images perfectly well:
// Get the all post content in a variable
$posttext = $post->post_content;
//$posttext1 = get_cleaned_excerpt();
// We will search for the src="" in the post content
$regular_expression = '~src="[^"]*"~';
$regular_expression1 = '~<img [^\>]*\ />~';
// WE will grab all the images from the post in an array $allpics using preg_match_all
preg_match_all( $regular_expression, $posttext, $allpics );
// Count the number of images found.
$NumberOfPics = count($allpics[0]);
// This time we replace/remove the images from the content
$only_post_text = preg_replace( $regular_expression1, '' , $posttext1);
/*Only text will be printed*/
// Check to see if we have at least 1 image
if ( $NumberOfPics > 0 )
{
$this_post_id = get_the_ID();
for ( $i=0; $i < $NumberOfPics ; $i++ )
{ $str1=$allpics[0][$i];
$str1=trim($str1);
$len=strlen($str1);
$imgpath=substr_replace(substr($str1,5,$len),"",-1);
$theImageSrc = $imgpath;
global $blog_id;
if (isset($blog_id) && $blog_id > 0) {
$imageParts = explode('/files/', $theImageSrc);
if (isset($imageParts[1])) {
$theImageSrc = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
?>
<img class="alignleft" src='<?php echo get_bloginfo('template_directory').'/timthumb.php?src=' . $theImageSrc . '&h=150&w=150'; ?>' height="150" width="150" alt=""/>
I'd really like to wrap that bottom img with the relevant parent a. Any help here would be greatly appreciated.
An example of the content to be searched might be:
<h5>
<a href="http://www.example.com/imagefoo.jpg">
<img class="size-thumbnail wp-image-4091 alignleft" src="http://www.example.com/imagefoo-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<h5>
<a href="http://www.example.com/Image-Bar.jpg">
<img class="wp-image-4087 alignleft" title="Image - Bar" src="http://www.example.com/Image-Bar-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<h5>
<a href="http://www.example.com/Image-Alphe.jpg">
<img class="wp-image-4090 alignleft" title="Image-Alpha" src="http://www.example.com/Image-Alpha-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<img class="size-thumbnail wp-image-4088 alignleft" title="EXAMPLE-image-150" src="http://www.example.com/EXAMPLE-image-150-150x150.jpg" alt="" width="150" height="150" />
<h5>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</h5>
<a href="http://www.example.com/insanely-long-permalink-created-as-if-by-a-madman-who-knows-no-bounds-of-shame/" rel="attachment wp-att-2780">
<img class="alignright size-thumbnail wp-image-2780" title="Exhibition Title: Image Name by Artist Person" src="http://www.example.com/wp-content/uploads/2011/12/ExtraordinaryImage-150x150.jpg" alt="Example UK | Exhibition: Image by Artist Person" width="150" height="150" />
</a>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
EDIT: Here's the working code based on my needs. It uses XPath, based on cHao's answer below. (For what it's worth, I found Tizag's webpage very useful as an XPath primer, alongside this EarthInfo page.):
// Get the all post content in a variable
$posttext = $post->post_content;
$document = DOMDocument::loadHTML($posttext);
$xpath = new DOMXPath($document);
$i = 0;
# for each link that has an image inside it, set its href equal to
# the image's src.
foreach ($xpath->query('//a/img/..') as $link) :
$img = $link->getElementsByTagName('img')->item(0);
$link_src = $link->getAttribute('href');
$link_title = $link->getAttribute('title');
$img_src = $img->getAttribute('src');
$theImageSrc = $img_src;
global $blog_id;
if (isset($blog_id) && $blog_id > 0) {
$imageParts = explode('/files/', $theImageSrc);
if (isset($imageParts[1])) {
$theImageSrc = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
?>
<a href="<?php echo $link_src; ?>" rel="lightbox[<?php echo $this_post_id; ?>]" title="<?php if ($link_title) {
echo $link_title;
} else { the_title(); } ?>" class="cboxElement">
<img class="alignleft" src='<?php echo get_bloginfo('template_directory').'/timthumb.php?src=' . $theImageSrc . '&h=150&w=150'; ?>' height="150" width="150" alt=""/>
</a>
<?php
endforeach;
?>
You'd be better off not trying to use regular expressions for finding the images. They suck at parsing HTML.
Instead, check out the DOMDocument and DOMXPath classes.
$document = DOMDocument::loadHTML($posttext);
$xpath = new DOMXPath($document);
# for each link that has an image inside it, set its href equal to
# the image's src.
foreach ($xpath->query('//a[/img]') as $link) {
$img = $link->getElementsByTagName('img')->item(0);
$src = $img->getAttribute('src');
# do your mangling of $src here, resulting in $href.
# for example...
$href = preg_replace('/-\d+x\d+(?=\.[^.]*$)/', '', $src);
$link->setAttribute('href', $href);
}
$fixed_html = $document->saveHTML();

Categories