Hey how do I call an iframe or something similar in PHP?
I have found some code but I might be setting up wrong, this is the code that I found, code:
<iframe id="frame" src="load.php?sinput="<?php echo $_GET["sinput"]; ?> > </iframe>
Does anybody know any iframe PHP codes or something similar for PHP?
Some people are saying not to use iframes what is there from PHP?
There is no function to generate an iframe in PHP.
What you're doing is fine, but allow me to make a suggestion:
<?
$input = "";
if(isset($_GET['sinput'])) {
$input = htmlspecialchars($_GET['sinput']);
}
?>
<iframe id="frame" src="load.php?sinput="<?php echo $input; ?>">Your browser does not support iframes</iframe>
EDIT: actually
<?
$url = "load.php";
// Query Building Logic
$querys = array();
if(isset($_GET['sinput'])) {
$queries[] = "sinput=".htmlspecialchars($_GET['sinput']);
}
// Generate full URL
if(count($queries) > 0) {
$url .= "?" . implode("&", $queries);
}
?>
<iframe id="frame" src="<? echo $url; ?>">Your browser does not support iframes</iframe>
I think is better quality overall, but ill let that up to my peers to judge. This is just another suggestion, to generate the full usable URL to use in your HTML in a full logic block, rather than relying on information to be present and usable in the template (because if the element ['sinput'] in the $_GET array is not set for whatever reason, the page will outright snap on you.
Related
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.
Hi i have an array with some Urls and Html code for open this webs in others tabs.
But the array dynamically changes the amount of Urls it contains. How can I change the Html code depending on the number of Urls that my array contains?
Code:
<?php
//$myarray can change dinamicaly the amount of urls contains
$myarray=array('www.google.com','www.piza.com','www.5.com');
?>
Now in my HTML code I have the code for open a tab, but i need open the array numbers of urls. In this case I need window.open('') three times.
<p><a href='#'
onclick='window.open('');
>Click to open webs</a></p>
<?php
//$myarray can change dinamicaly the amount of urls contains
$myarray=array('www.google.com','www.piza.com','www.5.com');
$windowsOpen = '';
foreach ($myarray as $value) {
$windowsOpen .= "window.open('$value', '_blank');";
}
?>
//now in my HTML code I have the code for open a tab, but i need open the array numbers of urls. In this case I need 'window.open('')' three times.
<p>Click to open webs</p>
Few things you should know, the URLs need to start with 'http://' or 'https://' in order to be an external link, if not it be considered as an internal link.
Moreover, most of the browsers will block the window.open if it is more than one as spam.
You could do something like this (although I'd advise against it without careful sanitzation if the urls are originating from inputs entered by users)
<?php
$arr = array("https://www.google.com", "https://www.pizza.com");
?>
<script>
function openWindows() {
var urlsArray = <?php echo '["' . implode($arr, '","') . '"]'; ?>;
for(i=0; i<urlsArray.length; i++) {
window.open(urlsArray[i]);
}
}
</script>
Open Windows
I need to fetch a remote page, modify some elements (using 'PHP Simple HTML DOM Parser' library for that) and output modified content.
There's a problem with remote pages that don't have full URLs in their source, so CSS elements and images are not loaded. Sure, it doesn't stop me from modifying elements, but the output looks bad.
For example, open https://www.raspberrypi.org/downloads/
However, if you use code
$html = file_get_html('http://www.raspberrypi.org/downloads');
echo $html;
it will look bad. I tried to apply a simple hack, but that helps just a little:
$html = file_get_html('http://www.raspberrypi.org/downloads');
$html=str_ireplace("</head>", "<base href='http://www.raspberrypi.org'></head>", $html);
echo $html;
Is there any way to "instruct" script to parse all links from $html variable from 'http://www.raspberrypi.org'? In other words, how to make raspberrypi.org to be the "main" source of all images/CSS elements fetched?
I daon't know how to explain it better, but I believe you got an idea.
I just have tried this on local, and I've noticed(in the source code) the link tags in the HTML are like this:
<link rel='stylesheet' href='/wp-content/themes/mind-control/js/qtip/jquery.qtip.min.css' />
It obviously requires a file that should be in my local directory (like localhost/wp-content/etc.../).
The href of the link tags must be something like
<link rel='stylesheet' href='https://www.raspberrypi.org/wp-content/themes/mind-control/js/qtip/jquery.qtip.min.css' />
So what you probably want to do is find all link tags and add in their href attribute "https://www.raspberrypi.org/" in front of the rest.
EDIT: Hey I've actually made the style work, try this code:
$html = file_get_html('http://www.raspberrypi.org/downloads');
$i = 0;
foreach($html->find('link') as $element)
{
$html->find('link', $i)->href = 'http://www.raspberrypi.org'.$element->href;
$i++;
}
echo $html;die;
Since only Nikolay Ganovski offered a solution, I wrote a code which converts partial pages into full by looking for incomplete css/img/form tags and making them full. In case someone needs it, find the code below:
//finalizes remote page by completing incomplete css/img/form URLs (path/file.css becomes http://somedomain.com/path/file.css, etc.)
function finalize_remote_page($content, $root_url)
{
$root_url_without_scheme=preg_replace('/(?:https?:\/\/)?(?:www\.)?(.*)\/?$/i', '$1', $root_url); //ignore schemes, in case URL provided by user was http://domain.com while URL in source is https://domain.com (or vice-versa)
$content_object=str_get_html($content);
if (is_object($content_object))
{
foreach ($content_object->find('link.[rel=stylesheet]') as $entry) //find css
{
if (substr($entry->href, 0, 2)!="//" && stristr($entry->href, $root_url_without_scheme)===FALSE) //ignore "invalid" URLs like //domain.com
{
$entry->href=$root_url.$entry->href;
}
}
foreach ($content_object->find('img') as $entry) //find img
{
if (substr($entry->src, 0, 2)!="//" && stristr($entry->src, $root_url_without_scheme)===FALSE) //ignore "invalid" URLs like //domain.com
{
$entry->src=$root_url.$entry->src;
}
}
foreach ($content_object->find('form') as $entry) //find form
{
if (substr($entry->action, 0, 2)!="//" && stristr($entry->action, $root_url_without_scheme)===FALSE) //ignore "invalid" URLs like //domain.com
{
$entry->action=$root_url.$entry->action;
}
}
}
return $content_object;
}
So I have three pages one that is the index page. One that writes the data from a form inside the index page to the database. And one that gets data from the database and echos out a html table with the data inside.
Currently if you write a link in the form. It will just come out as text. I would like the whole link to be like [link].
so say if I wrote this onto the form:
Look at this: www.google.com or Look at this: https://www.google.com
it would come out like this in html
Look at this: www.google.com
How could I go about doing this?
Okay so the html is:
<form class="wide" action="Write-to.php" method="post">
<input class="wide" autocomplete="off" name="txt" type="text" id="usermsg" style="font-size:2.4vw;" value="" />
</form>
in which the user would write:
"Look at this: www.google.com or Look at this: https://www.google.com"
This would then get sent to the database through Write-to.php.
$sql="INSERT INTO social (comunicate)
VALUES
('$_POST[txt]')";
}
this then gets written back into the database:
$result = mysqli_query($con,"(select * from social order by id desc limit {$limit_amt}) order by id asc");
while($row = mysqli_fetch_array($result))
{
echo "<tr div id='".$i."' class='border_bottom'>";
echo "<th scope='col'>";
echo "<span class='text'>".htmlspecialchars($row['comunicate'])."</span><br />";
echo "</th>";
echo "</tr>";
}
Just try:
echo(''.$your_url_variable.'');
Update:
The OP really wanted to detect url's in a string. One possible solution could be filter it using a regular expression. This code could help:
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "{$url[0]} ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
Source: http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
There are quite a few things you need to worry about when displaying user supplied (tainted) data.
You must ensure that all the data is sanitised -- never ever just echo the content, look into htmspecialchars and FILTER_VALIDATE_URL for example:
function validateUrl($url) {
return filter_var($url, FILTER_VALIDATE_URL);
}
What you are attempting to do is convert a string into a link, for example you can write a function like this:
function makeClickable($link) {
$link = htmlspecialchars($link);
return sprintf('%s', $link, $link);
}
You can use string concatenation as well, but I wouldn't do that in my view code. Just personal preference.
Take a look at the urlencode function, it will certainly come in handy.
I would also recommend you read about cross site scripting
Please note that I am not making any implementation recommendations, my aim is just to show you some contrived code samples that demonstrate making a string "clickable".
Update:
If you would like to make links clickable within text, refer to the following questions:
Best way to make links clickable in block of text
Replace URLs in text with HTML links
save the hyperlink in db and retrieve as a string by sql query
like:
select link from table_name where index = i
and save link as: whaatever here
and print it
Use this
echo '' . $res['url'] . '';
I wanna return a link inside to <img>. I dont know what is the problem.
categoria.php
<HTML>....
<img src="categoriaMAIN.php?type=celular">
</HTML>
categoriaMAIN.php
<?php
$varcate= $_GET['type'];
if ($varcate == "celular")
echo "http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg";
?>
categoriaMAIN.php
<?php
switch ($_GET['type'])
{
case 'celular':
header('Location: http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg');
break;
case '...':
header('Location: http://somesite.com/some/img/path/image.jpg');
break;
//...
}
Everyone else seemed to offer the readfile/grab and forward the content method. I thought I'd let the HTTP protocol do the work for us.
Well, the img tag is pointing to text, not an image.
Try:
header("Content-Type: image/jpg"); //tell the browser that this is an image.
$varcate= $_GET['type']; // you know this part
if ($varcate == "celular")
{
// readfile will grab the file and then output its contents without
// procressing it.
readfile("http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg");
}
Bit of a warning: if you don't output an image here, then the browser will probably complain about the image it is trying to load. You should add a default.
EDIT
Kristian made the point that this is a lot of work for the server and he is right. It would be much better if you could manage to make it so that the src of the img tag changed directly. The above, however, will get you where you are asking to go, though it may not be the best option.
The img tag has to point at the actual image - not a webpage containing the URL.
<img src="categoriaMAIN.php?type=celular">
has to get evalulated to
<img src="http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg">
It isn't being right now. How to accomplish this, greatly depends on the rest of your source code and what you actually are trying to accomplish.
This won't work! <img src="" searches for the image file, not its location! Try this:
categoria.php
<?php $varcate='celular'; ?>
<html>....
<img src="<?php include('categoriaMAIN.php'); ?>">
</html>
categoriaMAIN.php
<?php
if ($varcate == "celular")
echo "http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg";
?>
You give the img a PHP page as its src. So the browser is expecting that PHP page to return an image. Instead, you're having that page simply return a URL to the image. You'll have to change that so that you're actually echo ing the image data. I'm a little rusty will all this, but I think you'd do something like the following:
<?php
$varcate = $_GET['type'];
if ($varcate == 'celular') {
header('Content-type: image/jpg');
echo file_get_contents('http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg');
}
?>
If you really want to do it this way, your categoriaMAIN.php would need to look more like:
<?php
$varcate = $_GET['type'];
if ($varcate == "celular") {
header("Content-Type: image/jpeg");
echo file_get_contents("http://ecx.images-amazon.com/images/I/41l1yyZuyXL._AA160_.jpg");
}
?>
This will get the actual image data and return it to the browser as an image, which is what the browser needs.