Member Avatar for Member #596162

I've been searching the net for a strait answer on how to do this.
My website is based on an affiliate platform. PHP image upload.

Examples:
My site: www.mysite.com
There Site:

My members have the exact web page I have except, they have there own Unique URL.

All I want to do is allow my members to upload a picture of themselves from the members area, which will display on there page when there Unique URL is shown.

What I'm looking for is something kind of like what myspace has. You upload an image from your user panel, and it displays on your unique myspace URL.

If someone can point me towards a good tutorial, or give me some info. I know its not a hard thing to do, but I know theres security issues when dealing with anything being uploaded to your server, I dont want to take any chances.

Thanks in advance!

Dani AI

Generated

Short answer: let members upload images into a protected images folder, save a safe filename in the users table, and read that field on the member page. was right to suggest adding an image column to your users table — store only the filename or thumbnail path there, not the raw binary. In phpMyAdmin you can add the column with a single statement such as:

ALTER TABLE users ADD COLUMN image VARCHAR(255) DEFAULT NULL;

Do this once, then update that column when a logged-in member completes an upload.

Important checklist and integration notes (addresses points from and ):

  • Always require the user to be authenticated (use the session user id) before accepting an upload. Use that id to name the file (eg. user123.jpg) so names cannot collide or be abused.
  • Validate the file server-side: check the real MIME type (finfo or equivalent) and/or getimagesize, enforce a strict whitelist of image formats, and enforce file-size and pixel-dimension limits. Do not rely on the extension alone (as pointed out).
  • Rename uploads and strip user-supplied filenames. Reject anything that looks like PHP, HTML or other executable content. Set uploaded files to safe permissions (eg. 0644) and make the upload folder owned by the webserver user (www-data/apache) with 0755/0750 — do not leave it 0777 (see ).
  • Use parameterized queries (PDO or mysqli prepared statements) when you UPDATE the image column; avoid deprecated mysql_* calls. When displaying the image, escape the filename for HTML.

Troubleshooting and extras:

  • If uploads silently fail, check upload_max_filesize, post_max_size and file_uploads in php.ini and inspect the upload error code.
  • Consider creating a resized thumbnail on upload (GD or ImageMagick) and serve that on profile pages to avoid huge images.
  • Log failures and test with a small set of test files. Following the above will give you the MySpace-style result you want while keeping the site secure.

Recommended Answers

All 12 Replies

http://www.tizag.com/phpT/fileupload.php

One of the things I would do for security reasons do a check on the file extensions.

list($name, $extension) = explode(".", $filename);
if(strtolower($extension) == "gif" || strtolower($extension) == "jpg" || strtolower($extension) == "png") {
echo "Your a good person!";
} else {
echo "You bad, bad person. You may spend some time in jail because I will report you to the authorities!";
}

Forgive me for my lame attempt of my programmer humor.

I also want to point out a rather cool way of designing a user interface that can upload a file using Ajax. I am not sure if this code works(The link below) but Ajax can be seamless meaning the user will not even notice that there is something going on in the background and you won't even have to reload the page for any reason just parts of it.

This is what i suggest you could use as a upload page (named image_upload.php), you just need to insert what the max file size is,where the images should be stored (which folder) and which extensions are allowed:

if (!$_POST['uploadbutton']) {
?>
The image needs to be under 2,5MB and 850x850:<br />
<b>.jpg/.jpeg/.bmp/.gif/.pdf/.png</b><br />
Hij zal worden geupload in de map <b><i>fotos</i></b>.<br /><br />
<form enctype="multipart/form-data" action="image_upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2500000" />
Choose a image to upload: <input name="file" type="file" /><br />
<input type="submit" name="uploadbutton" value="Upload Foto" />
</form>
<?php
} else {
// ==============
// Configuration
// ==============
$uploaddir = "fotos"; // Where you want the files to upload to - Important: Make sure this folders permissions is 0777!
$allowed_ext = "jpg, gif, png, pdf, bmp, jpeg"; // These are the allowed extensions of the files that are uploaded
$max_size = "2500000"; // 50000 is the same as 50kb
$max_height = "850"; // This is in pixels - Leave this field empty if you don't want to upload images
$max_width = "850"; // This is in pixels - Leave this field empty if you don't want to upload images 
// Check Entension
$extension = pathinfo($_FILES['file']['name']);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for($i = 0; $i < count($allowed_paths); $i++) {
 if ($allowed_paths[$i] == "$extension") {
 $ok = "1";
 }
}

// Check filesize
if ($ok == "1") {
if($_FILES['file']['size'] > $max_size)
{
print "Het bestand is te groot!";
exit;
}

// Check height and width
if ($max_width && $max_height) {
list($width, $height, $type, $w) = getimagesize($_FILES['file']['tmp_name']);
if($width > $max_width || $height > $max_height)
{
print "De hoogte of breedte van het bestand is/zijn te groot";
exit;
}
}

// Uploads when the program isnt exited
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
move_uploaded_file($_FILES['file']['tmp_name'],$uploaddir.'/'.$_FILES['file']['name']);
}
echo "The image is uploaded.";
} else {
echo "Incorrect extension!";
}
}
?>

$uploaddir = "fotos"; // Where you want the files to upload to - Important: Make sure this folders permissions is 0777!

The directory really shouldn't have 777 permissions. Why not give the directory normal permissions, and just chown it and the upload script to the webserver user??

R

The directory really shouldn't have 777 permissions. Why not give the directory normal permissions, and just chown it and the upload script to the webserver user??

R

Because php needs to have atleast permission 0777, so it is possible to upload a file into the folder so it can be accessed, else it will return a error that the folder doesnt have the permission and the file can't be uploaded.

~Graphix

You're incorrect. Give the target directory ownership to your webserver user (e.g. www-data), and likewise the upload script ownership to your webserver user and it will work without the need for 777 permissions.

If you use 777, anyone can delete your directory.

R.

Member Avatar for Member #596162

I'm a little confused with all this. I'm a Novice when it comes to PHP.
I want know how my members can upload an image of themselves from the members area that will show up in a pre-determined spot when there Unique URL is brought up. Just like myspace... When you go to a myspace members page a picture that they uploaded from the user panel comes up.

How does the picture being uploaded from the members area end up on the main page that has there unique URL?

Ok, leaving the permission issue, you have to add a new column to the table "users" named "image", here should be the file name of the image.

How the member sets his image:

<?php
if (!$_POST['uploadbutton']) {
?>
The image needs to be under 2,5MB and 850x850:<br />
<b>.jpg/.jpeg/.bmp/.gif/.pdf/.png</b><br />
Hij zal worden geupload in de map <b><i>fotos</i></b>.<br /><br />
<form enctype="multipart/form-data" action="image_upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2500000" />
Choose a image to upload: <input name="file" type="file" /><br />
<input type="submit" name="uploadbutton" value="Upload Foto" />
</form>
<?php
} else {
// ==============
// Configuration
// ==============
$uploaddir = "fotos"; // Where you want the files to upload to
$allowed_ext = "jpg, gif, png, pdf, bmp, jpeg"; // These are the allowed extensions of the files that are uploaded
$max_size = "2500000"; // 50000 is the same as 50kb
$max_height = "850"; // This is in pixels - Leave this field empty if you don't want to upload images
$max_width = "850"; // This is in pixels - Leave this field empty if you don't want to upload images 
// Check Entension
$extension = pathinfo($_FILES['file']['name']);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for($i = 0; $i < count($allowed_paths); $i++) {
 if ($allowed_paths[$i] == "$extension") {
 $ok = "1";
 }
}

// Check filesize
if ($ok == "1") {
if($_FILES['file']['size'] > $max_size)
{
print "Het bestand is te groot!";
exit;
}

// Check height and width
if ($max_width && $max_height) {
list($width, $height, $type, $w) = getimagesize($_FILES['file']['tmp_name']);
if($width > $max_width || $height > $max_height)
{
print "De hoogte of breedte van het bestand is/zijn te groot";
exit;
}
}

// Uploads when the program isnt exited
if(is_uploaded_file($_FILES['file']['tmp_name']))
{
move_uploaded_file($_FILES['file']['tmp_name'],$uploaddir.'/'.$_FILES['file']['name']);
}
echo "The image is uploaded.";
} else {
echo "Incorrect extension!";
}
$image = mysql_real_escape($_FILES['file']['name']);
$user = mysql_real_escape($_SESSION['user']);
$query = "UPDATE users SET image='$image' WHERE user='$user'";
$result = mysql_query($query)
 or die("<br />There was a problem setting the image as your profile-image");
if ($result) {
echo "The image has been set as your profile-image";
}
}
?>

This is the code in the profile:

<?php
$user = $_SESSION['user'];
$query = "SELECT * FROM users WHERE user='$user'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo "<img src=\"images/".$row['image']."\" />";
?>

I suggest you investigate this code and see wether you find it appropiate.

~Graphix

Member Avatar for Member #596162

How do I make this code work with myAdminphp? All of my members variables are setup this way( IP, user name, ID, email, etc.) How can I use the variables I have set, to allow my members to upload an image that will show when there URL is clicked on?

My above example shows that you just simply let him upload the file (see script) and then you store the img-filename into the database. Then in the profile you get the filename from the database and put the foldername infront of it. (for example: the URL to the file is www.example.com/images/myProfilePicture.jpg and when your profileview.php is in the same folder () it automaticly redirects the img with images/myProfilePicture.jpg as source to www.example.com/images/myProfilePicture.jpg )

Member Avatar for Member #596162

So Graphix... How do I setup up the mySQL database for this to work. I should of asked this earlier, but forgot. Let me get this right... I put all of this on the page I want my members to upload from-

<?php
if (!$_POST) {
?>
The image needs to be under 2,5MB and 850x850:<br />
<b>.jpg/.jpeg/.bmp/.gif/.pdf/.png</b><br />
Hij zal worden geupload in de map <b><i>fotos</i></b>.<br /><br />
<form enctype="multipart/form-data" action="image_upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="2500000" />
Choose a image to upload: <input name="file" type="file" /><br />
<input type="submit" name="uploadbutton" value="Upload Foto" />
</form>
<?php
} else {
// ==============
// Configuration
// ==============
$uploaddir = "fotos"; // Where you want the files to upload to
$allowed_ext = "jpg, gif, png, pdf, bmp, jpeg"; // These are the allowed extensions of the files that are uploaded
$max_size = "2500000"; // 50000 is the same as 50kb
$max_height = "850"; // This is in pixels - Leave this field empty if you don't want to upload images
$max_width = "850"; // This is in pixels - Leave this field empty if you don't want to upload images
// Check Entension
$extension = pathinfo($_FILES);
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
for($i = 0; $i < count($allowed_paths); $i++) {
if ($allowed_paths[$i] == "$extension") {
$ok = "1";
}
}

// Check filesize
if ($ok == "1") {
if($_FILES > $max_size)
{
print "Het bestand is te groot!";
exit;
}

// Check height and width
if ($max_width && $max_height) {
list($width, $height, $type, $w) = getimagesize($_FILES);
if($width > $max_width || $height > $max_height)
{
print "De hoogte of breedte van het bestand is/zijn te groot";
exit;
}
}

// Uploads when the program isnt exited
if(is_uploaded_file($_FILES))
{
move_uploaded_file($_FILES,$uploaddir.'/'.$_FILES);
}
echo "The image is uploaded.";
} else {
echo "Incorrect extension!";
}
$image = mysql_real_escape($_FILES);
$user = mysql_real_escape($_SESSION);
$query = "UPDATE users SET image='$image' WHERE user='$user'";
$result = mysql_query($query)
or die("<br />There was a problem setting the image as your profile-image");
if ($result) {
echo "The image has been set as your profile-image";
}
}
?>

and than this were I want the image to display -

<?php
$user = $_SESSION;
$query = "SELECT * FROM users WHERE user='$user'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo "<img src=\"images/".$row."\" />";
?>

I'm not PHP literate so I dont know a lot about it. My membership code was bought from someone, so I didnt have to write any code.

How do the images get into the mySQL database? The way its setup is - each member has his/her own id, user name, IP, etc. When the pictures uploaded do I just use the Id # or what, I'm not real sure.

Member Avatar for Member #596162

How do I incorporate the above code into the code below?

<?php

session_start();

include "../memheader.php";
include "../config.php";
include "../style.php";

if( session_is_registered("ulogin") )
   	{  // members only stuff!

		include("navigation.php");
		
		 echo "<font size=2 face='$fonttype' color='$fontcolour'><p><center>";
        echo "<br><H2><center>Upload Your Image</H2>";
		
		<font size=3 face="<? echo $fonttype; ?>">
<p><b><center><FONT COLOR="#FF0000">You 
must be logged in to access this site. Please <a href="../index.php">click here</a> 
to login.</FONT></p></b></font> <? }

include "../memfooter.php";
mysql_close($dblink);
?>

Well i dont know what kind of login system you have, but i mostly use this:

<?php
if ($_SESSION['auth'] == "yes") { // this has been set at login.php
... The code if you are logged in
} else {
echo "You are not logged in, please click <a href="....">Here</a>";
}
?>

But as always i dont know how your programs look like and how they work, so this might not be compatible with the code that already exits, i think you should overthink this issue and then decide what you think is good for your site :)

~Graphix

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.