Jump to content

Recommended Posts

I want to be able to grab any new images uploaded and display them right away on the front page, at the moment I can grab the id of each but that won't update the gallery. Once 4 images are uploaded, the next one to be uploaded pushes the last out of the gallery.

 

At the moment, I only have 2 images on the db, but I want it ready to be used by a community :)

<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post"  
	enctype="multipart/form-data"> 
	Upload:<br><br> 
	<input type="file" name="image"><br><br> 
	<input type="submit" name="submit" value="Upload"> 
	</form>
	
	<?php
	
	if(isset($_POST['submit']))
	{
		mysql_connect("localhost","____","____");
		mysql_select_db("moduni_images");
		
		$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
		$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
		$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
		
		if(substr($imageType,0,5) == "image")
		{
			mysql_query("INSERT INTO `images` VALUES('','$imageName','$imageData')");
			echo "Image uploaded!";
		}
		else
		{
			echo '<br>O<font color="#8B0000">nly images are allowed!</font>';
		}
		
	}
	
	?>
<?php 

	mysql_connect("localhost","____","____");
	mysql_select_db("moduni_images");
	
	if(isset($_GET['id']))
	{
		$id = mysql_real_escape_string($_GET['id']);
		$query = mysql_query("SELECT * FROM `images` WHERE `id`='$id'");
		while($row = mysql_fetch_assoc($query))
		{
			$imageData = $row["image"];
		}
		header("content-type: image/jpeg");
		echo $imageData;
	}
	
	else
	
	{
		echo "Error!";
	}
?> 
<div id="user-gallery">
			<h2>Gallery</h2>
			
						
			<div class="img">
			  <a href="scripts/show_image.php?id=2" data-lightbox="image-1">
				<img src="scripts/show_image.php?id=2" width="125px" height="71px">
				</a>
			</div>
			<div class="img">
			  <a href="scripts/show_image.php?id=2" data-lightbox="image-1">
				<img src="scripts/show_image.php?id=2" width="125px" height="71px">
				</a>
			</div>
			<div class="img">
			 <a href="scripts/show_image.php?id=2" data-lightbox="image-1">
				<img src="scripts/show_image.php?id=2" width="125px" height="71px">
				</a>
			</div>
			<div class="img">
			  <a href="scripts/show_image.php?id=2" data-lightbox="image-1">
				<img src="scripts/show_image.php?id=2" width="125px" height="71px">
				</a>
			</div>
		</div>
Link to comment
https://forums.phpfreaks.com/topic/289237-grab-new-id-on-recently-uploaded/
Share on other sites

 

 

I want to be able to grab any new images uploaded and display them right away on the front page, at the moment I can grab the id of each but that won't update the gallery. Once 4 images are uploaded, the next one to be uploaded pushes the last out of the gallery.

So you want to display the 4 most recent images uploaded?

 

You'd use a SELECT query, ordering the results by id in descending order and then apply LIMIT of 4, example query

SELECT * FROM images ORDER BY id DESC LIMIT 4

Applying the query to the code

<div id="user-gallery">
    <h2>Gallery</h2>
    
<?php

    $result = mysql_query('SELECT id FROM images ORDER BY id DESC LIMIT 4'); // grab the 4 most recent images from database

    while($row = mysql_fetch_assoc($result))
    {
?>
    <div class="img">
      <a href="scripts/show_image.php?id=<?php echo $row['id'] ?>" data-lightbox="image-1">
        <img src="scripts/show_image.php?id=<?php echo $row['id] ?>" width="125px" height="71px">
        </a>
    </div>
<?php
    }
?>
</div>
Edited by Ch0cu3r

I can only get one image to display using;

<?php 

	mysql_connect("localhost","","");
	mysql_select_db("moduni_images");
	
	if(isset($_GET['id']))
	{
		$id = mysql_real_escape_string($_GET['id']);
		$query = mysql_query("SELECT * FROM `images` ORDER BY `id` DESC LIMIT 4");
		while($row = mysql_fetch_assoc($query))
		{
			$imageData = $row["image"];
		}
		header("content-type: image/jpeg");
		echo $imageData;
	}
	
	else
	
	{
		echo "Error!";
	}
?> 
Edited by Azercii

You need to retrieve the image where the image id matches $_GET['id']!  ::)

<?php 

	mysql_connect("localhost","","");
	mysql_select_db("moduni_images");
	
	if(isset($_GET['id']))
	{
		$id = mysql_real_escape_string($_GET['id']);
		$query = mysql_query("SELECT * FROM `images` WHERE id = " . intval($_GET['id']));
		header("content-type: image/jpeg");
		echo $row["image"];
                exit;
	}
	else
	{
		echo "Error!";
	}

[phpBB Debug] PHP Warning: in file /home/moduni/public_html/index.php on line 296:mysql_fetch_assoc() expects parameter 1 to be resource, boolean given

 

 

I'm just getting the hang of PhP haha could you break it down a little more? :)

Added comments to show_image.php

<?php 

    // connect to database
    mysql_connect("localhost","","");
    mysql_select_db("moduni_images");
    
    // grab the id query string paramter
    if(isset($_GET['id']) && ctype_digit($_GET['id']))
    {
        // sanitize the id query string param
        $id = intval($_GET['id']);

        // select the image from the images table where the image id matches $id
        $query = mysql_query("SELECT * FROM `images` WHERE id = $id");

        // output the jpeg image content type header
        header("content-type: image/jpeg");

        // output the image binary
        echo $row["image"];

        // stop script execution
        exit;
    }
    else
    {
        echo "Error!";
    }

 

I can only get one image to display using;

<?php 

	mysql_connect("localhost","","");
	mysql_select_db("moduni_images");
	
	if(isset($_GET['id']))
	{
		$id = mysql_real_escape_string($_GET['id']);
		$query = mysql_query("SELECT * FROM `images` ORDER BY `id` DESC LIMIT 4");
		while($row = mysql_fetch_assoc($query))
		{
			$imageData = $row["image"];
		}
		header("content-type: image/jpeg");
		echo $imageData;
	}
	
	else
	
	{
		echo "Error!";
	}
?> 

 

You're overwriting $imageData on each loop through the 4 returned rows from the database and only outputting the results after the loop. Are you actually storing the image in the database, or a path to the file on the server? I'm not sure how the browser's going to respond to trying to write the image header for each of the images, but you'd need to put the lines

header("content-type: image/jpeg");
echo $imageData;

before the closing curly brace of your while() loop. Also, if you're trying to display 4 images, why do you care if $_GET['id'] is set? If you're only trying to display the selected image (the image corresponding to 'id' in $_GET['id']), the user Ch0cu3r's code.

Would uploading to the server and adding the file path, name, and desc to the database be any easier to work with?

That's how I would handle it, yes. Something along the lines of the following:

$query = mysql_query("SELECT	 id
				,location
				,description
				,name
		      FROM `images` ORDER BY `id` DESC LIMIT 4");
while($row = mysql_fetch_assoc($query))
{
	echo "<img src='{$row['location']}' alt='{$row['description']}' name='image_{$id}' id='image_{$row['id']}' title='{$row['name']}' />\n";
}

Of course, I'd also recommend you use either the PDO or MySQLi libraries instead of mysql_* functions as those are well and truly deprecated and slated to be removed from the language soon.

There are some fundamental issues, including several security holes.

 

Accepting any image type is not a good idea, because some of them are much more than just a harmless collection of pixels. For example, an SVG “image” is actually a full-blown XML document which can contain arbitrary XHTML content including scripts. If you let people upload such files, that's like allowing them to place arbitrary HTML files in your document root. This is not just a cross-site scripting vulnerability. You've basically turned your whole site into a JavaScript playground.

 

Then you insert the raw content of $_SERVER['PHP_SELF'] into your document, probably assuming that it only contains a harmless file path. But Apache actually allows the client to append arbitrary content to the real path. So, for example, they could access your script with this URL:

https://yoursite.com/upload.php/"><script>... some malicious JavaScript code ...</script>

This gets inserted into the page, and the user ends up running the appended JavaScript code.

 

You also have no image validation whatsoever. You accept anything as long as the user-provided MIME type starts with “image”. That means instead of uploading images, people might as well submit text or code or whatever. I'm not saying that validation helps (it doesn't), but it might be a good idea to at least do some basic checks like running the image through getimagesize().

 

Long story short:

  • Escape everything, even if you think it's harmless. Don't make assumptions about whether or not a value can be used for an attack.
  • Reject everything unless you know how to handle it. Which image types do you know? JPEG, PNG and GIF? Great, then accept those three types and reject everything else. Don't just accept the whole “image” media type. I don't even know all the subtypes in there. Do you?

I also wouldn't store the images in the database unless you have a specific reason for that. It bloats the database, makes the images difficult to access and increases the response time. Why not just store the images as actual files?

I'm gonna need to read up some more on this before it's even usable lol

 

Just to make sure I am heading in the right direction;

 

I want a user to upload his/her image, the gallery then grabs the most recent and displays them in descending order. By adding $title to the database, would I be able to display a caption overlay on the img with the users inputted information?

 By adding $title to the database, would I be able to display a caption overlay on the img with the users inputted information? 

 

 

You can easily do that in HTML, but it won't be directly in the image. So, if somebody saves the image, the text won't be saved with it.

 

If you want to add text directly to the picture, you'll need to use an image library (gd or imagemagick). It's easy, the only thing is that you need to be sure that the server where you are hosting your website has that kind of library installed. You could make an easy test. Check this function:

http://www.php.net//manual/en/function.imagettftext.php

 

Here's a tutorial on image manipulation and how to add text to an image:

http://blog.themeforest.net/tutorials/fun-with-the-php-gd-library-part-1/

 

 

Edit: Like Jacques1 said, fix your upload first. The last thing you want is a big ball of code that doesn't work at all ;)

Edited by mogosselin
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.