I hope someone will help me with this. Namely, I need a PHP code which will display images in a HTML/PHP page based on their id. For example: the file ShowPicture.php, and the code in it something like this:
PictureID = "MyPicture1"
MyPicture1_Source = "/Pictures/Picture1.jpg";
PictureID = "MyPicture2"
MyPicture2_Source = "/Pictures/Picture2.png";
PictureID = "MyPicture3"
MyPicture3_Source = "/Pictures/Picture3.gif";
PictureID = "MyPicture4"
MyPicture4_Source = "/Pictures/Picture4.bmp";
Example of usage on the pages:
HTML/PHP PAGE 1: <IMG src="ShowPicture.php?id=MyPicture4">
HTML/PHP PAGE 4: <IMG src="ShowPicture.php?id=MyPicture2">
HTML/PHP PAGE 2: <IMG src="ShowPicture.php?id=MyPicture3">
HTML/PHP PAGE 3: <IMG src="ShowPicture.php?id=MyPicture1">
I don't currently use any code since I didn't find good enough which will suit this particular need of mine.
The file should be something like Facebook's rsrc.php file, which fetches all the graphics for the site whilst hiding the real source path.
EDIT: I do not need Sessions nor Cookies, I want the pictures to be displayed permanently on pages through PHP, even after the user refreshes/reloads the pages.
EDIT 2: No (My)SQL. The PHP file itself and alone must be sort of a database for storing and displaying images.
I wanted you to put efford in it yourself. Stack Overflow is ment to help you when you have issues with your code. It's not ment for people that just want some programmer to do all the work for them. Anyway, I've taken a few minutes to do it for you now, so here it is:
<?php
$id = $_GET["id"];
switch($id){
case "MyPicture1":
$file = "img/img1.jpg";
break;
case "MyPicture2":
$file = "img/img2.jpg";
break;
case "MyPicture3":
$file = "img/img3.jpg";
break;
case "MyPicture4":
$file = "img/img4.jpg";
break;
default:
echo "Invalid ID given!";
exit;
}
if(file_exists($file)){
$size = getimagesize($file);
$fp = fopen($file, 'rb');
if($size and $fp){
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
header('Content-Type: '.$size['mime']);
header('Content-Length: '.filesize($file));
fpassthru($fp);
}
exit;
} else {
echo "File not found!";
}
?>
You can modify it any further yourself.
Related
i was trying to rotate url using file get content but there's little error which I am not able to figure out.
<?php
//Rotate
$urls = array();
$divs[] = '/fun.jpg';
$divs[] = '/nuf.jpg';
echo file_get_contents(src="'. $divs[rand(0, count($divs)-1)] .'");
?>
But it's not returning any random div.
Well, if you just show images from same folder, as your PHP script is in, you should be able to do it like this. (did not test it)
<?php
header("Content-Type: image/jpg");
$divs[] = 'fun.jpg';
$divs[] = 'nuf.jpg';
echo file_get_contents($divs[array_rand($divs)]);
?>
You need to include header: Show image using file_get_contents
And for picking random key from array you can use array_rand() function: https://www.php.net/manual/en/function.array-rand.php
The above two function not working in wordpress. I want to download file and i am running wordpress in xampp also i have tried it in another online server with wordpress framework still not working.
but this is working in another online server where i have not used wordpress framework.
Is there is problem with wordpress using the above two function?
(below code just take get request which is the path to the file to be downloaded from the server and after validating token the path is given from database)
<?php
ini_set('display_errors', -1 );
require('wp-blog-header.php');
require('wp-config.php');
$token = ($_GET["token"]);
$platform = ($_GET["platform"]);
$resolution = ($_GET["resolution"]);
$assetName =($_GET["assetName"]);
$currentTime = date("ymdHi" , time());
if($wpdb->query("SELECT * FROM wp_token_table WHERE token='$token'")){
$result = $wpdb->get_results("SELECT (path) FROM wp_path_table WHERE os='$platform' AND res = '$resolution' AND bundle_name= '$assetName'");
if($result){
$path = $result[0]->path;
$fileName = basename($assetName);
$filePath = $path;
if(!empty($fileName) && file_exists($filePath)){
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/zip");
header("Content-Length:".filesize($filePath));
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Transfer-Encoding: binary");
readfile($filePath);
exit;
}
}
}else echo "false";
?>
first of all lets verify my assumption is correct. In the wordpress index.php file, right at the top add this ( obviously after the <?php tag though )
ini_set('display_errors', -1 );
Let me know what that says when you try to download the file.
SQL Injection would let me
do this with your url
$token="'; SELECT * FROM wp_token_table WHERE 1 LIMIT 1; --";
And then your query would be this
"SELECT * FROM wp_token_table WHERE token=''; SELECT * FROM wp_token_table WHERE 1 LIMIT 1; --'"
The -- is start of comment to discard the ending ' then i would essentially select the first entry from that table. Or worse.
It's very important to prevent that.
For the error, I would do this
<?php
echo "hello";
/* -- rest of code */
And make sure the page works first. Once you know that you can rule out problems with the url, then uncomment bits of the code tell it breaks. That will show you where the error is. Unfortunately error reporting wont generally work if its on a page with a syntax error, because php cant even parse the page, so it cant run anything on it.
For my current assignment I'm trying to store files into the DB and display them. Currently I have no problem storing the files but I can't display them properly. I'm using this in my main form.
<td><a href=getImage.php?id='.$file[0].'" />Resume</a></td>
And this is the query I'm using to get the file out of the DB.
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo "<img src=\"{$row['file']}\" /><br />";
The result is
…³V!µÔ¢ošweöÿZ–îÌèEÈÎpEJ·˜kä€òþòâGas
È*G¨¥vA¤uEN¤S]‰:ñY“iwØ8‡¥e]ØÝGÑ‘øQÍ!«3¨ÄvÙÁu§]zÕÿOã^ssÌuáY7WP“ÔT6Æà™ëâþÊQË!üioe8
9ô5ã?ÛSÇÔ‘RÃ⛘VCBh¹>ϳ=BïÃVwåçÔW#¯|8†ufŠ4ob1PiÞ=q(,>µÐYx®Æ÷¥ò›Ñ5b½äy6«ðÆbͲϡ®fóá–
í„ξ‹’xvîYVEöæ«6§]|²½ýj‡Ï#åËßjv™-k.u\ŠÈ›O–#ó!ЊúÊmcLþ-¹ïšÆÔ4ïkùñE¸ÿ0h±j§‘òù
Ԉ켯íº×ÂÝã/g:»¸âïþ=³-²û?áHÑI3ŒKÙW¨ÍNºŽî-¶_Ã#IÙ¸{Tiû¸>â€3ÿu7#V[àüš‘í•ùT[9\Ó’ª?oçJ©ù…69Ùxß÷¹©ö¼
|ÊOµ°™W##êàÔ²iw®»–uõ5Eíåˆà«ôÅHä¯"‘\PˆÙŽ>ïÖœÖò'¡÷†^Ž#3Sg+ÀéYžt±uBG>=H'ÞB>”À¾7ƒè)É#)åsU×S‰‡R>µ"\£ô4‹é"ç=D/ÿ-
š¦¼ô©àuCó'´‰ Ë7çPëÑ¿Z½åÛÌ>\Mk
&ʱœÒ0ê*#)ÏAV怩#Bd`^):ܲ¯ü*îÛERk†^ù¦CiÃsõ¦
ší¹Îj¬“*øhf﶑¬†CqíH’ëëIæsŒŠÐ{=ÍW{
:dÓ¸aÐœýjXîæCÃA:æ”CŽÿe5iG£}h7I7ßCüê¬8èqP–t<Ò…©£¸MÄúbª¼EM'ÚJš‘oPýôϽHˆ2GµZ¶¾T
H/Ò¢yb“§ò¦R9ÓC6,n...
I'm using images as a sample at the moment but the finished php should eventually allow to display PDF documents. If it's any help I'm using phpmyadmin and MySQLi.
As the comments suggest, storing the file location in the database is much better than storing the file's data in the database. BUT if you need to store the file contents in the database for some reason, there are two methods. One is using the HTML data: URL and the other is having a PHP file as the middle man.
For the PHP Middle Man method, look at the answer above mine where it sets the header information and then echo's the file contents. The file extension doesn't matter since browsers refer to the content-type header instead of file extensions.
For the Data URL method, which can be placed directly in your code easily check out http://en.wikipedia.org/wiki/Data_URI_scheme
<?php
// Array of valid Mime Types, prevents possible XSS methods.
$valid_mimes = array(
'image/png',
'image/gif',
'image/jpeg'
);
// Obtain Mime Type using finfo
// Finfo allows for strings instead of file path
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->buffer($row['file']);
// Check if mime is in our $valid_mimes array
if(!in_array($mime,$valid_mimes)) {
// Handle Error
echo 'Illegal Mime Type: '.$mime;
die();
}
$b64 = base64_encode($row['file']);
echo '<img src="data:'.$mime.';base64,'.$b64.'" />';
?>
You cant output <img src=\ as an output it will corrupt the image file and
Please use getImage.php as a different file to output images or verify that no output is printed before,after or in mid of image else it will corrupt the image.
if(isset($_GET['id'])){
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo $row['file'];
}
I have created a script which takes a random IMAGE ID from the database, converts it to a valid file name and then I use it to generate random images from a link.
This is how such a link looks like (works - try it):
http://imgit.org/roll.php?image=3J9N0Y4k8g4l4G7
When you reload that link, you'll notice the image changes. If I add this image to <img src="THAT LINK" /> it works, however, it doesn't work on message board like phpBB or vBulletin when I put that link inside [img][/img] BBCode tags.
I suppose there is a problem with my script, because there are various services out there that do exactly the same thing (link on forums) and it works.
Here is my roll.php script:
<?php
$imgit_root_path = '.';
include("{$imgit_root_path}/common.php");
if ($config['disable_roll'])
{
redirect('index.php');
}
$roll_key = request_var('image', '');
$roll_key = substr($roll_key, 0, 15);
if (!$roll_key)
{
redirect('index.php?action=404');
}
if (!$image->roll_key_exists($roll_key))
{
redirect('index.php?action=404');
}
$images = $image->roll_info($roll_key);
$images = explode('|', $images);
$count = sizeof($images);
$index = mt_rand(0, $count - 1);
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$image_url = generate_site_url() . IMAGES_PATH . $image->get_name($images[$index]);
$image_inf = pathinfo($image_url);
header('Content-type: ' . $extList[$image_inf['extension']]);
readfile($image_url);
?>
I believe the problem may be that phpBB will disallow links which aren't confirmed as images. That is, don't have a known image extension, such as .jpg;
https://www.phpbb.com/community/viewtopic.php?f=46&t=1285255
For security reasons, images whose extensions cannot be confirmed
(such as in the first example) aren't allowed by BBCode. Instead of an
image, it's fully possible for someone to embed a JavaScript script,
or even worse, onto a page which could be a security risk to anyone
visiting the page, or possibly even the server.
This is most likely the same in vBulletin.
Seems you can override it in the forum settings maybe?
Alternatively, if you can change you script, so that you can append a ".jpg" extension to the end, then that may also work!
I think what happens is browser caches image. Try adding header('Cache-Control: max-age=0'); before readfile($image_url);
I currently have a database where i can store images in..
But the PHP page i created to display them... doesnt work.
But when i use the link as scr for a < img> it shows a empty image frame.
if i echo the image directly, i get a lot of strange signs
the way i want to display the images is:
< img src="image.php?image="'.$imageID.'/>
the code i use for displaying the image(image.php) is:
<?php session_start();
if(!isset($_GET['image']))
{
header("HTTP/1.0 404 Not Found");
}
else{
$link = mysql_connect('localhost', '45345345435435345', 'wewfsersdfds');
if (!$link) {
echo "error";
die;
}
$db_selected = mysql_select_db(Tha base, $link);
if (!$db_selected) {
echo "error";
die;
}
$nummer=(int)trim(stripslashes($_GET['image']));
$mynr=$nummer;
$sql="SELECT * FROM Foto WHERE fotonr=$mynr";
$result=mysql_query($sql);
if(!$result)
{
echo "error".mysql_error();
header("HTTP/1.0 404 Not Found");
}
else
{
$foto = mysql_fetch_assoc($result);
header("Content-type: ".$foto['type']);
echo $foto['image'];
}
}
?>
I tried a lot already but it wont work :(
i updated the code to the newest version.
Made mistakes with the sql(selected nothing/never do mysql_real_escape_string of a int)
Now it shows a straight line of characters, instead of an image, thats at least a improvement...
Can someone help me?
Thanx for your time!
Honestly, I know it can be tricky. I think it has to do with how your storing it, not how your outputting it. I have one example of storage from a recent project I can show.
$fp = fopen($image_path, 'r');
$image = fread($fp, filesize($image_path));
$image = addslashes($image);
fclose($fp);
// save $image into DB.
Not sure if you do similar with file_get_contents. How I output is similar to how you are doing it, only I use a ORM and a framework.
I suspect that your problem is in your conversion - perhaps between strings and images, or perhaps between the different image formats.
Have you tried saving the image gotten through image.php, and comparing the binary against the known-good image file? Perhaps once you do that, the answer will be apparent (e.g. wrong length, corrupted header, etc.)
You may want to consider a different database record. Most db's support storage of binary blob data, which you could more simply return. This would be simpler (and take less space in your db!) than using the php functions to stringify and imagecreatefromstring.
Also, I believe that you're attempting to use imagegif, imagejpeg, imaging to perform image format conversion for you. This isn't how I understand them to work, based on my reading at: http://php.net/manual/en/function.imagecreatefromstring.php. Try storing and retrieving the same format to tease out whether this is your problem.
Try looking at Content-type. I think it's case sensitive. Try Content-Type.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
$sql = "SELECT * FROM Foto WHERE fotonr=$mynr";
$result = $conn -> query($sql);
while ($row = $result -> fetch_assoc()) {
$img= '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'" width=350px0px height=300px/>';
}
echo $img;