Just another php image exists issue - php

All of this stuff is for example (names aren't actual).
Everything is also located on localhost:8080 (USBWebserver 8.5)
Directory Structure:
(Files located on localhost:8080/[project_name])
/ajax
/ajax_file.php
/img
/250x250
/[image_name].jpg
Code (From ajax_file.php):
$url = 'img/250x250/'.$image_name.'.jpg';
$url = file_exists($url);
This will return false.
I've tried an img_exists($url) function which used cUrl that did not work.
I've also tried:
$url = 'img/250x250/'.$image_name.'.jpg';
$image_check = getimagesize($url);
if (!is_array($image_check))
{
$url = 'img/default_image.png';
}
but this returns a warning for getimagesize() saying no file or directory exists.
When I put $url = 'img/250x250/'.$image_name.'.jpg' into <img src="$url" /> the image shows up...but if the image does not exist then it comes up with a broken image...
How come anything I try to do fails in some way?
I want a default image to show up when the image is broken :/
EDIT
$url = 'img/products/250x250/'.$image_name.'.jpg';
$url = var_dump(file_exists($url));
Returns bool(false)
$url = '../img/products/250x250/'.$image_name.'.jpg';
$url = var_dump(file_exists($url));
Returns bool(false)

It appears as if you need to branch out of the ajax folder before accessing img folder?
Try:
$url = '../img/250x250/'.$image_name.'.jpg';
#Alex Lunix
My guess is that he put the img tag inside of the actual php page, not the ajax script.

If you're in /ajax/ajax_file.php and you look for 'img/250x250/'.$image_name.'.jpg' it will be looking for /ajax/img/250x250/'.$image_name.'.jpg. Instead you should be using
$url = '../img/250x250/'.$image_name.'.jpg';
Although I'm not sure why it shows up in image tags, my guess is you're getting lucky and your browser is fixing the url.

Related

Issues with using file_get_contents and file_put_contents in PHP

I have to download an image in a weblink to my local folder using php. Below is the program.
<?php
if (isset ($_POST['submit'])){
$URL = 'http://10.251.13.7/gtz/temp3.php/download.png'; // Like "http:// ...."
$FileToSave = 'uploads/download.png'; // Like "/home/.." or "C:/..."
$Content = file_get_contents($URL);
file_put_contents($FileToSave, $Content); //file_put_contents('uploads/image.jpg',file_get_contents('10.251.13.7/gtz/temp3.php/mtps_files.png'));
} ?>
I could successfully download the image. But when I try to open it's showing the file has been damaged. In one way I am able to right click the image in the weblink and save the file to my local directory. It works.
On the other hand, in php programming I was able to download the file and when I access the file, it is showing as file got damaged.
Please review below code. Please assign the home folder path in file & save file.
$URL = 'C:/home/demo/Downloads.png'; // Like "http:// ...."
$FileToSave = 'D:/demo/download.png'; // Like "/home/.." or "C:/..."
$Content = file_get_contents($URL);
file_put_contents($FileToSave, $Content);

What is the best way to get the parameters in PHP?

I will completely clarify my question, sorry to everybody.
I have code writed in files from a website that now is not working, the html code is on pages with php extension, in a folder of a Virtual Host in my PC using Wampserever. C:\wamp\1VH\PRU1, when the site was online there was a folder where was a file called image.php. This file was called from other pages inside the site like this: (a little code of a file, C:\wamp\1VH\PRU1\example.php)
"<div><img src="https://www.example.com/img/image.php?f=images&folder=foods&type=salads&desc=green&dim=50&id=23" alt="green salad 23"></div>"
And the result was that the images was showed correctly.
Now, like i have this proyect in local, and i HAVE NOT the code of that image.php file i must to write it myself, this way the images will be showed the same way that when the site was online.
When the site was online and i open a image returned by that image.php file the URL was, following the example, https://example.com/images/foods/salads/green_50/23.png.
Now how the site is only local and i have not that image.php file writed because i'm bot sure how to write it, the images obviously are not showed.
In C:\wamp\1VH\PRU1\example.php the code of files was changed deleting "https://www.example.com/img/image.php?" for a local path "img/image.php?".
And in the same folder there is anothers: "img" folder (here must be allocated the image.php file), and "images" folder, inside it /foods/salads/green_50/23.png, 24.png.25.png..............
So i have exactly the same folder architecture that the online site and i changed the code that i could only, for example replacing with Jquery "https://www.example.com/img/image.php?" for "img/image.php?" but wich i can not do is replace all the code after the image.php file to obtain a image file.
So i think that the easiest way to can obtain the images normally is creating that IMAGE.PHP file that i have not here in my virtual host.
I'd like to know how to obtain the parameters and return the correct URL in the image,php file.
The image of the DIV EXAMPLE must be C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
I have in my PC the correct folders and the images, i only need to write the image.php file.
Note that there are "&" and i must to unite the values of "desc=green&dim=50&" being the result: green_50 (a folder in my PC).
TVM.
You probably want something like this.
image.php
$id = intval($_GET['id']);
echo '<div><img src="images/foods/salads/green_50/'.$id.'.png" alt="green salad '.$id.'"></div>';
Then you would call this page
www.example.com/image.php?id=23
So you can see here in the url we have id=23 in the query part of the url. And we access this in PHP using $_GET['id']. Pretty simple. In this case it equals 23 if it was id=52 it would be that number instead.
Now the intval part is very important for security reasons you should never put user input directly into file paths. I won't get into the details of Directory Transversal attacks. But if you just allow anything in there that's what you would be vulnerable to. It's often overlooked, so you wouldn't be the first.
https://en.wikipedia.org/wiki/Directory_traversal_attack
Now granted the Server should have user permissions setup properly, but I say why gamble when we can be safe with 1 line of code.
This should get you started. For the rest of them I would setup a white list like this:
For
folder=foods
You would make an array with the permissible values,
$allowedFolders = [
'food',
'clothes'
'kids'
];
etc...
Then you would check it like this
///set a default
$folder = '';
if(!empty($_GET['folder'])){
if(in_array($_GET['folder'], $allowedFolders)){
$folder = $_GET['folder'].'/';
}else{
throw new Exception('Invalid value for "folder"');
}
}
etc...
Then at the end you would stitch all the "cleaned" values together. As I said before a lot of people simply neglect this and just put the stuff right in the path. But, it's not the right way to do it.
Anyway hope that helps.
You essentially just need to parse the $_GET parameters, then do a few checks that the file is found, a real image and then just serve the file by setting the appropriate content type header and then outputting the files contents.
This should do the trick:
<?php
// define expected GET parameters
$params = ['f', 'folder', 'type', 'desc', 'dim', 'id'];
// loop over parameters in order to build path: /imagenes/foods/salads/green_50/23.png
$path = null;
foreach ($params as $key => $param) {
if (isset($_GET[$param])) {
$path .= ($param == 'dim' ? '_' : '/').basename($_GET[$param]);
unset($params[$key]);
}
}
$path .= '.png';
// check all params were passed
if (!empty($params)) {
die('Invalid request');
}
// check file exists
if (!file_exists($path)) {
die('File does not exist');
}
// check file is image
if (!getimagesize($path)) {
die('Invalid image');
}
// all good serve file
header("Content-Type: image/png");
header('Content-Length: '.filesize($path));
readfile($path);
https://3v4l.org/tTALQ
use $_GET[];
<?php
$yourParam = $_GET['param_name'];
?>
I can obtain the values of parameters in the image.php file tis way:
<?php
$f = $_GET['f'];
$folder = $_GET['folder'];
$type = $_GET['type'];
$desc = $_GET['desc'];
$dim = $_GET['dim'];
$id = $_GET['id'];
?>
But what must i do for the image:
C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
can be showed correctly in the DIV with IMG SRC atribute?

Saving image file name exactly as URL image file into folder in PHP

I have visited this article previously and found it useful, but i would like to add more functionality to it by having it save an image file name according to the URL name.
This is what I've done so far and it works.
$contents=file_get_contents('http://www.domain.com/logo.png');
$save_path="C:/xampp/htdocs/proj1/download/[logo.png]";
file_put_contents($save_path,$contents);
Basically, where I have put square brackets around I want to have that dynamic based on the URL file name. For example, if i have an image url such as this: https://cf.dropboxstatic.com/static/images/brand/glyph-vflK-Wlfk.png, I would like it to save the image into the directory with that exact image name which in this case is glyph-vflK-Wlfk.png.
Is this possible to do?
I would do this way
$url = "http://www.domain.com/logo.png";
$file = file_get_contents($url);
$path = "C:/xampp/htdocs/proj1/download/". basename($url);
return !file_exists($path) ? file_put_contents($path, $file) : false;
From what I understand, what you're trying to do is the following :
$url = 'http://www.domain.com/logo.png';
$contents=file_get_contents($url);
$posSlash = strrpos($url,'/')+1);
$fileName = substr($url,$posSlash);
$save_path="C:/xampp/htdocs/proj1/download/".$fileName;
file_put_contents($save_path,$contents);
There is a function for that, basename():
$url="http://www.domain.com/logo.png";
$contents=file_get_contents($url);
$save_path="C:/xampp/htdocs/proj1/download/".basename($url);
file_put_contents($save_path,$contents);
You might want to check if it already exists with file_exists().

Getting base url of my project

I have an XML file that I use to create a PHP object. I then want to simply print out the image however I am getting the error 'Not allowed to load local resource'.
To get the image URL I have set a variable
$root = ( __DIR__ );
And then append that to the path in my XML file.
$parseXML = simplexml_load_file('chicken.xml');
$img_url = $parseXML->picture;
$imgg = $root . '/' . $img_url;
This now gives me the current path which is
C:\wamp\www\recipesUpdated/images/MarinoWebsite.jpg
If I copy and paste this into my browser it displays the image but won't work when I echo it in an img src.
Is there a way of getting the path just to
\recipesUpdated/images/MarinoWebsite.jpg
Without the C:\wamp etc ?
Thank you!
You get path to image on your local computer, and browser not allowed to load this path.
Url must contain web server address or be relative
Example:
http://localhost/recipesUpdated/images/MarinoWebsite.jpg
or
/recipesUpdated/images/MarinoWebsite.jpg
For your question, try to set variable $root to empty string or your web server address.

How to scrape only the largest images from the DOM?

I am using SimpleHTMLDOM to scrape pages (in servers other than mine).
The basic implementation is
try {
$html = file_get_html(urldecode(trim($url)));
} catch (Exception $e) {
echo $url;
}
foreach ($html->find('img') as $element) {
$src = "";
$src = $element->src;
if (preg_match("/\.(?:jpe?g|png)$/i", $src)) {
$images[] = $src;
}
}
This works fine but it returns all images from the page, including small avatars, icons, and button images. Of course I'd like to avoid these.
I then tried to insert within the loop as follows
...
if (preg_match("/\.(?:jpe?g|png)$/i", $src)) {
$size = getimagesize($src);
if ($size[0] > 200) {
$images[] = $src;
}
}
...
That works well on a page like http://cnn.com.
But in others it returns numerous errors.
For example
http://www.huffingtonpost.com/2012/05/27/alan-simpson-republicans_n_1549604.html
gives a bunch of errors like
<p>Severity: Warning</p>
<p>Message: getimagesize(/images/snn-logo-comments.png): failed to open stream: No such file or directory
<p>Severity: Warning</p>
<p>Message: getimagesize(/images/close-gray.png): failed to open stream: No such file or directory
which seem to happening because of relative URLs in some images. The problem here is that this crashes the script and then no images a loaded, with my Ajax box loading forever.
Do you have any ideas how to troubleshoot this?
The problem is that the image URLs are relative to the site root, so your server can't make sense of them to fetch them and find out their size. You could refer to this question to figure out how to get absolute URLs from relative ones.
The approach you tried with image size checking is correct.
However, in order for it to work on all sites, you would need to add some kind of relative URL parsing.
I don't know if there are any libraries or such for it but here's a quick overview on how to do it:
Find the domain part of the URL you're scraping
Assume any URL starting with / is an absolute URL. You can fetch these simply by concatenating domain and path
Assume any URL not starting with / is relative. You may need to parse any .. markers in the URL to locate the expected path
Check for the <base> tag in the document: If the document has a <base> tag, it will anchor all relative paths into the path defined in the tag.
You may be able to find a library to convert relative paths and absolute paths into something you can use, but in most cases they will not account for the <base> tag mentioned in the last point.
Try something like this assuming a url of http://somedomain.com...
$domain = explode('/', $url);
$domain = $domain[2];
// ... snip ...
if (preg_match("/\.(?:jpe?g|png)$/i", $src)) {
$size = getimagesize($src);
if ($size[0] > 200) {
if(strpos($src, '/', 0) === 0)
$src = $domain . $src;
$images[] = $src;
}
}
This will help some, but it won't be fool-proof - I can't think of many domains using ../../etc relative paths to images, but I'm sure someone is - of course, you could test for a match of anything other than the domain in the image's src attribute, and try throwing the domain on there but no promises that will work every time either. I would think there's a better way... perhaps have a default method and load a config with predefined domain "fixes" for troublesome domains.

Categories