php get all files from a remote directory - php

I have searched, and searched for 3+ hours this morning and tried over 10 different setups for how to grab and display a list of images from a url, and none of them worked correctly. I would either end up with no info displaying, or a 500 error. Can someone point me to an example or help me out here on how to do this properly. file_get_contents is not a viable option.
Example Directory: http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/
Files i know that are in that directory:
001.jpg,
002.jpg,
003.jpg
I would like the output to be the exact url to the file.
Let me know if more info is needed, i'm not 100% sure exactly how to explain it right lol.
Edit:
ok so what I guess i actually want to do is check the url for all the image tags and display a list with the full url to that image.
New to working with this url+images+php stuff so please don't hit me too hard with your downvote hammer with no comments lol.
Code I Tried:
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
$url = $location;
// Fetch page
$string = FetchPage($url);
// Regex that extracts the images (full tag)
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $string, $out, PREG_PATTERN_ORDER);
$img_tag_array = $out[0];
echo "<pre>"; print_r($img_tag_array); echo "</pre>";
// Regex for SRC Value
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);
$images_url_array = $out[1];
echo "<pre>"; print_r($images_url_array); echo "</pre>";
// Fetch Page Function
function FetchPage($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("The was a connection error!");
}
$data = '';
while (!feof($file))
{
// Extract the data from the file / url
$data .= fgets($file, 1024);
}
return $data;
}
?>
and it returned a blank page

Based loosely on the code you already tried (but was riddled with problems). This grabs the full contents of the URL $url, parses out the <img> src attributes, and then outputs them.
Because this particular web host uses <base href=""/> tag to reset the base part of all URLs on the page, I've added a $base variable which you should set to the contents of the base tag.
Additionally, it looks like this particular web host has some pretty smart anti-hotlinking in place, so not all images may be visible.
But! Give it a whirl, let me know if it does what you need it to, and any questions.
<?php
$url = 'http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/';
$base = 'http://www.webtoonlive.com/';
// Pull in the external HTML contents
$contents = file_get_contents( $url );
// Use Regular Expressions to match all <img src="???" />
preg_match_all( '/<img[^>]*src=[\"|\'](.*)[\"|\']/Ui', $contents, $out, PREG_PATTERN_ORDER);
foreach ( $out[1] as $k=>$v ){ // Step through all SRC's
// Prepend the URL with the $base URL (if needed)
if ( strpos( $v, 'http://' ) !== true ) $v = $base . $v;
// Output a link to the URL
echo '' . $v . '<br/>';
}
Sample output:
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/000.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/001.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/002.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/003.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/004.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/005.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/006.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/007.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/008.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/009.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/010.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/011.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/012.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/013.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/014.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/015.jpg
http://www.webtoonlive.com/webtoon/fantasy_world_survival/ch02/016.jpg

Related

String to URL but detect if url is image?

i'm trying to do something in PHP
I'm trying to get the link of an image -> store it to my DB, but I'd like the user to be able to store text before it, and after it, I've gotten my hands on a similar function for links, but the image part is missing.
As you can see the turnUrlIntoHyperlink does a regex check over the entire arg passed, turning the text that contains it to the url, so users can post something like
Hey check this cool site "https://stackoverflow.com" its dope!
And the entire argument posting to my database.
However i can't seem to get the same function working for the Convert Image, as it simply won't post and removed text before/after it before when i made the attempt.
How would i do this in a correct way, and can i combine these 2 functions in to 1 function?
function convertImg($string) {
return preg_replace('/((https?):\/\/(\S*)\.(jpg|gif|png)(\?(\S*))?(?=\s|$|\pP))/i', '<img src="$1" />', $string);
}
function turnUrlIntoHyperlink($string){
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $string, $url)) {
// Loop through all matches
foreach($url[0] as $newLinks){
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
// Create Search and Replace strings
$search = $newLinks;
$replace = ''.$link.'';
$string = str_replace($search, $replace, $string);
}
}
//Return result
return $string;
}
more explained in detail :
When i post a link like https://google.com/ I'd like it to be a href,
But if i post an image like https://image.shutterstock.com/image-photo/duck-on-white-background-260nw-1037486431.jpg , i'd like it to be a img src,
Currently, i'm storing it in my db and echoing it to a little debug panel,
Do you mean that you want to make an <img> inside <a> element?
Your turnUrlIntoHyperlink function have captured the url successfully, so we can just use explode to get string before and after the link.
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
Code example:
<?php
function turnUrlIntoHyperlink($string){
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $string, $url)) {
// add http protocol if the url does not already contain it
$newLinks = $url[0][0];
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
return $string_before.'<img src="'.$link.'">'.$string_after;
}
return $string;
}
echo turnUrlIntoHyperlink('Hey check this cool site https://stackoverflow.com/img/myimage.png its dope!');
Output:
Hey check this cool site <img src="https://stackoverflow.com/img/myimage.png"> its dope!
Edit: the question has been edited
Since an image URL is just another kind of link/URL, your logic should go like this pseudocode:
if link is image and link is url
print <img src=link> tag
else if link is url and link is not image
print <a href=link> tag
else
print link
So you can just write a new function to "merge" those two function:
function convertToImgOrHyperlink($string) {
$result = convertImg($string);
if($result != $string) return $result;
$result = turnUrlIntoHyperlink($string);
if($result != $string) return $result;
return $string;
}
echo convertToImgOrHyperlink('Hey check this cool site https://stackoverflow.com/img/myimage.png its dope!');
echo "\r\n\r\n";
echo convertToImgOrHyperlink('Hey check this cool site https://stackoverflow.com/ its dope!');
echo "\r\n\r\n";
Output:
Hey check this cool site <img src="https://stackoverflow.com/img/myimage.png" /> its dope!
Hey check this cool site https://stackoverflow.com/ its dope!
The basic idea is that since image url is also a link, such check must be done first. Then if it's effective (input and return is different), then do <img> convertion. Otherwise do <a> convertion.

PHP file_get_contents not showing url link

I'm having an issue with php file_get_content(), I have a txt file with links where I created a foreach loop that display multiple links in the same webpage but it's not working, please take a look at the code:
<?php
$urls = file("links.txt");
foreach($urls as $url) {
file_get_contents($url);
echo $url;
}
The content of links.txt is: https://www.google.com
Result: Only a String displaying "https://www.google.com"
Another code that works is :
$url1 = file_get_contents('https://google.com');
echo $url1;
This code returns google's homepage, but I need to use first method with loops to provide multiple links.
Any idea?
Here's one way of combining the things you already had implemented:
$urls = file("links.txt");
foreach($urls as $url) {
$contents = file_get_contents($url);
echo $contents;
}
Both file and file_get_contents are functions that return some value; what you had to do is putting return value of the latter one inside a variable, then outputting that variable with echo.
In fact, you didn't even need to use variable: this...
$urls = file("links.txt");
foreach($urls as $url) {
echo file_get_contents($url);
}
... should have been sufficient too.

PHP get meta tags function doesn't work with non http

I was hoping I can get help with a problem I am having.
I'm using the php get meta tags function to see if a tag exist on a list of websites, the problem occurs when ever there is a domain without HTTP.
Ideally I would want to add the HTTP if it doesn't exist, and also I would need a work around if the domain has HTTPS here is the code I'm using.
I will get this error if I land on a site without HTTP in the domain.
Warning: get_meta_tags(www.drhugopavon.com/): failed to open stream: No such file or directory in C:\xampp\htdocs\webresp\index.php on line 16
$urls = array(
'https://www.smilesbycarroll.com/',
'https://hurstbournedentalcare.com/',
'https://www.dentalhc.com/',
'https://www.springhurstdentistry.com/',
'https://www.smilesbycarroll.com/',
'www.drhugopavon.com/'
);
foreach ($urls as $url) {
$tags = get_meta_tags($url);
if (isset($tags['viewport'])) {
echo "$url tag exist" . "</br>";
}
if (!isset($tags['viewport'])) {
echo "$url tag doesnt exist" . "</br>";
}
}
You could use parse_url() to check if the element scheme exists or not. If not, you could add it:
$urls = array(
'https://www.smilesbycarroll.com/',
'https://hurstbournedentalcare.com/',
'https://www.dentalhc.com/',
'https://www.springhurstdentistry.com/',
'https://www.smilesbycarroll.com/',
'www.drhugopavon.com/'
);
$urls = array_map(function($url) {
$data = parse_url($url);
if (!isset($data['scheme'])) $url = 'http://' . $url ;
return $url;
}, $urls);
print_r($urls);
You can use this to check if the domain has http
foreach($urls as $url){
if(strpos($url, "http") === FALSE) //check if the url contains http and add it to the beginning of the string if it doesn't
$url = "http://" . $url;
$tags = get_meta_tags($url);
}
Another simpler option would be to check for :// in the url
foreach($urls as $url){
if(strpos($url, "://") === FALSE) //check if the url contains http and add it to the beginning of the string if it doesn't
$url = "http://" . $url;
$tags = get_meta_tags($url);
}
Or you can use regex like Wild Beard suggested
you know whats funny, I thought it was because it had http but I put error_reporting(0); in my original code and it worked as I wanted it to haha.

Apply php function to shortcode

I'll start by saying I'm fairly new to coding so I'm probably going about this the wrong way.
Basically I've got the below php function that changes urls to the page title of the url instead of a plain web address. So instead of www.google.com it would appear as Google.
<?php
function get_title($url){
$str = file_get_contents($url);
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
return $title[1];
}
}
?>
This is great but to implement this I have to use the below code.
echo get_title("http://www.google.com/");
However this just works on a predefined URL. What I have set up on my site at the moment is a shortcode in a html widget.
<a href='[rwmb_meta meta_key="link_1"]'>[rwmb_meta meta_key="link_1"]</a>
This shortcode displays a url/link that is input by the user in the backend of Wordpress and displays it on the frontend as a link. However I want to apply the get_title function to the above shortcode so instead of the web address it shows the page title.
Is this possible?
Thanks in advance.
for name of a url from a link you can use parse_url($url, PHP_URL_HOST);
easier way would be to have an array of links for example
$links[] = 'some1 url here';
$links[] = 'some2 url here';
then just loop your $links array with the function.
foreach($links as $link)get_title($link);
https://metabox.io/docs/get-meta-value/
try:
$files = rwmb_meta( 'info' ); // Since 4.8.0
$files = rwmb_meta( 'info', 'type=file' ); // Prior to 4.8.0
if ( !empty( $files ) ) {
foreach ( $files as $file ) {
echo $file['url'];
}
}

PHP Find & Replace where url and extension

I've been looking for an example on how to use preg_replace or RegEX to
search HTML for either http://www.mydomain.co.uk/page.html or /page.html
and replace .html with .app
I only want to replace the .html on pages that belong to this site
I have an app that uses pages from our website. When I link page from the app I put .app so it removes/ changes the formatting. Which works, I just want to dynamically edit the links on the pages.
Cheers
OK for those interested, I've cracked it.
It searches html for links then checks if the link belongs to site.
Find ".html" replace with ".app" within the link
Find old links replace with new links within html.
Thanks guys you pointed me in the right direction
function searchHTML($html){
// if the page is used by the app replace all domain pages .html with .app
$domain ='mydomain.com';
$regEX = '/<a[^>]+href=([\'"])(.+?)\1[^>]*>/I';
preg_match_all($regEX, $html, $match); //check page for links
for($l=0; $l<=count($match[2]); $l++){ //loop through links found
$link = $match[2][$l];//url within href
if ((strpos($link, $domain) !== false) || ($link[0]=="/")) { //check links are domain links(domain name or the first char is /)
$updateLink = str_replace(".html", ".app", $link);//replace .html ext with .app ext
$html = str_replace($link, $updateLink, $html); //update html with new links
}
}
return $html;
}
function changeURL($url) {
$url = str_replace('html', 'app', $url);
return $url;
}
echo changeURL('http://www.mydomain.co.uk/page.html');
Result: http://www.mydomain.co.uk/page.app
Try this, works with PHP 4 >= 4.0.5
<?php
$string = "http://www.mydomain.co.uk/page.html";
$string = preg_replace_callback("/mydomain.co.uk\/.+?(html)$/", "replace", $string);
function replace($matches) {
return str_replace("html", "app", $matches[0]);
}
echo $string;
<?php
// it's important to use the $ in regex to be sure to replace only the suffix and not a part of the url
function change_url($url, $find, $replace){
return preg_replace("#\\.".preg_quote($find, "#")."$#uim", ".".$replace, $url);
}
echo change_url("http://www.mydomain.co.uk/page.html", "html", "app");
//retuns http://www.mydomain.co.uk/page.app
?>

Categories