Unable to save an image from a remote server using PHP - php

OK,... this is in reference to: Copy Image from Remote Server Over HTTP
Here is my code:
for ($i = 0; $i < count($json_post['Category']); ++$i )
{
echo $json_post['Category'][$i]['CategoryID'] . '<br />';
echo $json_post['Category'][$i]['Name'] . '<br />';
echo $json_post['Category'][$i]['Image'] . '<br />';
$image_URL = "https://$_SSActiveWear_BaseURL/" . $json_post['Category'][$i]['Image'];
echo $image_URL . "<br /><br />";
copy("https://$_SSActiveWear_BaseURL/$image_URL", $_SERVER['DOCUMENT_ROOT']."/tmp/" . basename($image_URL));
die;
}
I have tried cURL with the same results.
What is happening is that the files are being created, but with all the same file length of 58k and when I attempt to open one to view it, it is unable to be opened. In fact its the HTML content of the index page from the server I am attempting to save the image from.
Edit 1
If I hard code the image to be saved instead of using the variables, it saves the correct image.

Figured this one out.
did the following change:
copy($image_URL, $_SERVER['DOCUMENT_ROOT']."/tmp/" . basename($image_URL));
I do not understand why when using a single variable, as in this case, it works and not when I use a compounded statement.

It's because your URL get interpreted wrong. Always use {} around variable in string:
copy("https://$_SSActiveWear_BaseURL/$image_URL", $_SERVER['DOCUMENT_ROOT']."/tmp/" . basename($image_URL));
is converted to copy("https://SSActiveWear_BaseUrl/_URL", ...). As you can see PHP does not find variables $_ and $image and applies null for them.
Correct syntax:
copy("https://{$_SSActiveWear_BaseURL}/{$image_URL}", "{$_SERVER['DOCUMENT_ROOT']}/tmp/".basename($image_URL));

Related

cant print images (.svg) of folder using matrix

just print the square but not the image, dont know what is wrong, doesnt throw mistake.
Thanks
echo "<img src=\"img/$numero[$i].svg\" alt=\"$numero[$i]\" title=\"$numero[$i]\" width=\"140\" height=\"140\">\n";
Nothing wrong in your code. Check if you have correct svg image or not at particular location. (inspect using chrome developer tool)
Check using Object tag or if your browser support or not. https://www.w3schools.com/html/html5_svg.asp
I would recommend to not mix strings with code vars. Always do proper concatenation:
$str = '<img src="/img/' . $numero[$i] . '.svg"';
$str .= ' alt="' . $numero[$i] . '"';
$str .= ' title="' . $numero[$i] . '"';
$str .= ' width="140" height="140">'. "\n";
echo $str;
your code seem right, try checking if the svg image is in the correct image path you placed
i tested with this and is working well
<?php
$numero = array('imagename', 'image alt', 'title');
echo "<img src=\"Images/$numero[0].svg\" alt=\"$numero[1]\" title=\"$numero[2]\" width=\"140\" height=\"140\">\n";
?>
thank you all, I discovered that it happened
I was missing a bar in front of the img
echo "<img src=\"/img/$numero[$i].svg\" alt=\"$numero[$i]\" title=\"$numero[$i]\" width=\"140\" height=\"140\">\n";
instead of
echo "<img src=\"img/$numero[$i].svg\" alt=\"$numero[$i]\" title=\"$numero[$i]\" width=\"140\" height=\"140\">\n";
I do not see any sense

Show table data on different page

I have a website where users can write posts, however im haveing trouble echoing the post along with its title.
Heres My Code:
Post.inc.php:
echo '<input type="button" value="Read More"
onclick="window.location=\'read_more.php?start=' .
urlencode($row['post']) . ' \';" />';
echo "</p>";
Read_more.php:
<?php
date_default_timezone_set('America/New_York');
include 'post.inc.php';
?>
<?php
$start = (!empty($_GET['start']) ? $_GET['start'] : false);
echo '<p>. $title .<br> ' . $start . '<p>';
?>
Only the post is being echoed and not the title. How would I go about fixing this problem?
-Thanks in advance
As Chris said, this is very vulnerable to XSS attacks, you need to sanitize the $_GET['start'] value before echoing it. Also, passing the entire post in the url is not a great idea. If you are storing the post in a database you are better off sending an ID value of some sort through the URL, validating/sanitizing it and retrieving the post directly from the database to be displayed.
I cannot see where you have given $title a value. It is not defined in any of the code you have provided. This means it cannot display anything when echoed.
Also, the structure of your echo is incorrect.
echo '<p>'. $title .'<br>'. $start .'</p>';
is what you are looking for here. notice the single quotes are closed before $title and re-opened before the break tag.
variable will not be expanded when it occur in single quoted strings.You can find this notice in PHP Manual
so,
echo '<p>. $title .<br> ' . $start . '<p>'
should be modified to
echo '<p>'. $title .'<br>'. $start .'</p>';
or use double quoted instead,
"<p>{$title}<br>{$start}</p>"
As Matt said, echoing the $_GET['start'] directly will make your site be vulnerable,which can result in attacks like phishing.
In a general way, there are some operations like filter,type check to sanitize the value gained from frontend. The PHP Manual provides a lot of function to do this,intval(),PCRE,mysqli_escape_string(),array_filter(),htmlspecialchars()...
IMHO,you should use a SQL server like MySQL,SQLite,or others to storage the data from frontend which can help your site work better.

How to correctly write <img src> in php without escaping to HTML

I am having trouble with my PHP code. I've been changing everything for 6 hours and I still get Parse errors no matter what I do. This is the code:
$slider3 = '<img src="'templates/' . $this->template . '/images/slider/slider3.jpg'">' . '" alt="' . $sitename . '" />';
The only way I can figure to not get it to throw an error is by writing it this way:
$slider3 = '<img src="templates/" . $this->template . "/images/slider/slider3.jpg" . "/>"';
but I don't think that's right.
I want $slider3 = "templates/MYTEMPLATE/images/slider/slider3.jpg" then later I will echo $slider3;
I get so confused with all the single and double quotation marks. I think the first one is right - I look at it and study it and it looks right to me. But it throws a parse error.
$slider3 = '<img src="templates/'.$this->template.'/images/slider/slider3.jpg"/>';
should work.
Explanation:
'<img src="templates/'
is a single-quoted string, which happens to contain a double-quote (which is needed for the html src attribute, or any other html attribute value really)
.
(dot) is the string concatenation operator. It concatenates ("glues") the first string together with...
$this->template
which is presumably a string containing the name of the template (not clear from your code example). Note that if $this->template comes from user input, or an otherwise unvalidated source, it could be used for cross-site scripting, eg. if it contains "><script>alert("XSS!")<script>, javascript is executed in the browser!
.
another concatenation with...
'/images/slider/slider3.jpg"/>'
which is another single-quoted string which happens to contain a double-quote, ending the src attribute value.
Try this:
$slider3 = '<img src="templates/"' . $this->template . '"/images/slider/slider3.jpg"/>';
$template = "MYTEMPLATE";
$slider3 = '<img src="templates/'.$template.'/images/slider/slider3.jpg"/>';
echo $slider3;
Will echo - >
<img src="templates/MYTEMPLATE/images/slider/slider3.jpg"/>
Just write:
<?php
$templates = "var";
echo "<img src='templates/${templates}/images/slider/slider3.jpg'/>";
it will result in
<img src='templates/var/images/slider/slider3.jpg'/>

unable to show image from external hd php

I'm new with programming and learning now php. I have installed xamp and have write a little bit code. I have some images on my external hd and I want to show some pictures.
The problem is I can get a list of path of my images with this code:
echo "<html><body>";
$outerDir = "x:\map\maps\more\\";
$total = count (array_diff (scandir ($outerDir), Array (".", "..")));
$dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
foreach ($dirs as $d) {
if (!is_dir($outerDir . $d)) {
echo $d . "<br>";
}
}
but if I want to show it as an image, i can't show the image. I tried this in the foreach:
if (!is_dir($outerDir . $d)) {
$file = $outerhDir . $d;
echo 'img src="' . $outerDir . $d . '> <br>';
echo "<img src='" . $outerDir . '\\' . $d . "'alt='" . $d . "'> <br>";
}
But none of them work. I also tried the header and file_get_content like this:
if (!is_dir($outerDir . $d)) {
$file = $outerDir . $d;
header('Content-type: image/jpeg');
header('Content-Length:' . filesize($file));
$image = file_get_contents('$file');
echo $image . "<br>";
}
Even a simple html code wont work! Like this:
echo '<img src="x:\map\maps\more\needwonder.jpg"> <br>';
BUTTTT!! When I store one of the image in the same folder as my php file it will work! Like this:
echo '<img src="needwonder.jpg"> <br>';
But I dont want to put all my files in the same folder as the php file, because of security, technicaly, comfortable reasons AND I want to learn programming not to avoid issues or problems with my code.
So I hope I defined my problem good and hope that one of you guys and/or girls know the solution to help me out
If your image files aren't in a folder that's set up to be accessible by the web server, you can't display them on a web page. Simple as that. Put them in a web directory to use them.
It is possible to write a PHP script that proxies image files (kind of like what you're trying with file_get_contents()), but doing that requires a separate PHP file for the images, and it's best avoided unless absolutely necessary, as it can easily introduce security vulnerabilities, and performs poorly. If you do want to do that, though:
Link to the PHP script in place of an image, and pass it an identifier for the image as a parameter (e.g, <img src="img.php?image=blah">).
In that script, use that identifier to send the appropriate Content-Type, then use readfile() to output the image. (It's equivalent to echo file_get_contents(...), but more concise and performs better in some situations.)
MAKE ABSOLUTELY SURE that the parameter to that script cannot be manipulated to load a file that you didn't intend to make available. This includes trickery like ?image=../../wrong/file.

Adding A Dynamic Link In Php

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

Categories