Solved

upload image and set it as webpage background.

Posted on 2010-09-15
10
461 Views
Last Modified: 2012-05-10
Hi All,

I am developing a website functionality in which user should be able to upload his/her choice of background image for there personalized profile page.

How should i achieve this?
0
Comment
Question by:steve_hawkings
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 11

Expert Comment

by:Manish
ID: 33680739
0
 
LVL 11

Expert Comment

by:Manish
ID: 33680748
I think you can save user uploaded file as username_background file.
In profile page you can use same name to show background as uploaded image.
0
 
LVL 40

Accepted Solution

by:
gurvinder372 earned 125 total points
ID: 33680768
If you are looking for an upload and preview functionality, then you need to take the following steps
1) Do the ajax upload of the file
http://www.finalwebsites.com/forums/topic/php-ajax-upload-example
http://css-tricks.com/ajax-image-uploading/

2) At the server side, save the image at specified location,
http://www.reconn.us/content/view/30/51/ (not sure if it works, haven't tried)

3) In the callback handler of the ajax request made at client, make sure that you use the specified folder location where the images are saved in the server.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Assisted Solution

by:UnicornBoy
UnicornBoy earned 125 total points
ID: 33680910
You can use make it with or without database.

for making this without a DB the simplest solution is to upload users images in a folder for example "users_bgs" and name them exactly the user ID... for example the user with ID = 100 may have a file named 100.jpg in the users_bgs folder that means he/she has an BG and it should be implemented on his/her profile background, and if he/she doesnt have that file it means he/she has no personal background...

by user ID I mean primary key on users table of database or any other identification code you use on your site for user sessions...

make a section for uploading background images for your users use a form like first part of the Code  Snippet that I attached.

then make a upload_bg.php file and inside that use the second part of the code snippet. customize the code in the way you want...

now for the profile pages that the background should be used, use the third part of the Snippet in the <head> section of your html.

<form action="upload_bg.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

-----------------------------------

<?php
if (($_FILES["file"]["type"] == "image/jpeg") && ($_FILES["file"]["size"] < 204800))
  {
  if ($_FILES["file"]["error"] > 0)
    echo "Error: " . $_FILES["file"]["error"];
  else
    move_uploaded_file($_FILES["file"]["tmp_name"], "users_bgs/{$_SESSION['LoggedInUserID']}.jpg");
    echo "Success.";
  }else{
    echo "Invalid file. Not JPEG or more than 200KB.";
  }
?> 

------------------------------------
<style>
body { background-image: url('<?php
echo (file_exists("users_bgs/{$_SESSION['LoggedInUserID']}.jpg") ? "users_bgs/{$_SESSION['LoggedInUserID']}.jpg" : "defaultBG.jpg");
?>'); }
</style>

Open in new window

0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 33690683
Uploading an image is fairly well understood in the technical literature.  Here is a script that shows you how to do that (and even a little more).
<?php // RAY_upload_and_resize_image.php


// UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE


// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{

// IS GD INSTALLED AT ALL?
   if (!function_exists("gd_info"))
   {
      if ($display) echo "<br/>GD NOT INSTALLED\n";
      return FALSE;
   }

// IF GD IS INSTALLED GET DETAILS
   $gd = gd_info();

// IF DISPLAY IS REQUESTED, PRINT DETAILS
   if ($display)
   {
      echo "<br/>GD DETAILS:\n";
      foreach ($gd as $key => $value)
      {
         if ($value === TRUE)  $value = 'YES';
         if ($value === FALSE) $value = 'NO';
         echo "<br/>$key = $value \n";
      }
   }

// RETURN THE VERSION NUMBER
   $gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
   return $gd_version;
}


// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
// IS GD HERE?
   $gdv = get_gd_info();
   if (!$gdv) return FALSE;

// GET AN IMAGE THING
   $source = imagecreatefromjpeg("$image");

// GET THE X AND Y DIMENSIONS
   $imageX = imagesx($source);
   $imageY = imagesy($source);

// IF NO RESIZING IS NEEDED
   if ($imageX <= $width)
   {
      return FALSE;
   }

// THE WIDTH IS TOO GREAT - MUST RESIZE
   $tnailX = $width;
   $tnailY = (int) (($tnailX * $imageY) / $imageX );

// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
   if ($gdv >= 2)
   {
// IF GD IS AT LEVEL 2 OR ABOVE
      $target = imagecreatetruecolor($tnailX, $tnailY);
      imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   } else
   {
// IF GD IS AT A LOWER REVISION LEVEL
      $target = imagecreate($tnailX, $tnailY);
      imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   }
   return $target ;
}
/* ********************************************************************************************* */


// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos    = 'photos';

// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB

// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;

// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
    ?>
    <h2>Upload Photos</h2>

    <!-- NOTE THE USE OF ENCTYPE -->
    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="p" value="1" />
    <!-- MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD -->
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
    <p>
    Find the photo you want to upload and click the "Upload" button below.
    </p>

    <table cellpadding="1" cellspacing="1" border="0">
    <tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
    <tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
    &nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
    </table>
    </form>
    <?php

    die();

} else {

// THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: Upload Photos</h2>\n";
    echo "<p>\n";

// SYNTHESIZE THE NEW FILE NAME
    $f_type  = trim(strtolower(end    (explode( '.', basename($_FILES['userfile']['name'] )))));
    $f_name  = trim(strtolower(current(explode( '.', basename($_FILES['userfile']['name'] )))));
    $my_new  = getcwd() . '/' . $photos . '/' . $f_name . '.' . $f_type;
    $my_file = $photos  . '/' . $f_name . '.' . $f_type;

// TEST FOR ALLOWABLE EXTENSIONS
    if ($f_type != 'jpg')
    {
       die('Sorry, only JPG files allowed');
    }

// IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code != 0)
    {
        $error_message = $errors[$error_code];
        echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
        die('Sorry');
    }

// MOVE THE FILE INTO THE DIRECTORY
    $overwrite    = $_POST['overwrite'];
    $file_size    = number_format($_FILES["userfile"]["size"]);

// IF THE FILE IS NEW
    if (!file_exists($my_new))
    {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
        {
            $upload_success = 1;
        } else
        {
            $upload_success = -1;
        }

// IF THE FILE ALREADY EXISTS
    } else
    {
        echo "<b><i>$my_file</i></b> already exists.\n";

// SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($overwrite))
        {
            $upload_success = 0;

// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        } else
        {
            $now    = date('Y-m-d');
            $my_bak = $my_new . '.' . $now . '.bak';
            if (!copy($my_new, $my_bak))
            {
                echo "<b>Attempted Backup Failed!</b>\n";
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
            {
                $upload_success = 2;
            } else
            {
                $upload_success = -1;
            }
        }
    }

// REPORT OUR SUCCESS OR FAILURE
    if ($upload_success == 2) { echo "It has been overwritten.\n"; }
    if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
    if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }

    if ($upload_success > 0)
    {
        echo "$file_size bytes uploaded.\n";
        chmod ($my_new, 0755);
    }

    echo "</p>\n";

// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
    if ($upload_success > 0)
    {
        if ($imageblob = create_right_size_image($my_new))
        {
            imagejpeg($imageblob, $my_new);
        }
    }

    echo "<p><a href=\"$my_file\">See the file</a></p>\n";
}

Open in new window

0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 33690730
Now to the other part.  You will need a way of identifying the client.  Usually this suggests a login system.  There is an article here that shows how to do that.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

You will need a data base table that associates the client identity with the URL of the file that was uploaded.  See line 219 of the previous code snippet for the way to find this URL.

When you generate the HTML for the page, your PHP code will first look to see if the client is logged in.   If not, you will use a blank image for the background.  If the client is logged in, you will look up the image URL in the data base table and if it there, use that URL to set the background property in the CSS.

You will want to wrap the upload script in an access-controlled page so your uploads can be clearly identified and associated with the client who uploaded the file.

HTH, ~Ray

0
 
LVL 11

Expert Comment

by:Manish
ID: 34203951
Is there any reason my suggestion is not accepted?
0
 

Expert Comment

by:South Mod
ID: 34228580
Restarting Cleanup Volunteer action

SouthMod
Community Support Moderator
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Session time out quickly. 6 27
Find RGB colors from a screen. 2 18
JSON decode 5 19
Do not understand error message 3 25
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
In this tutorial viewers will learn how to embed custom externally-hosted Google Fonts using the Google Font API in CSS Go to the Google Fonts website at google.com/fonts: Browse or search based on font properties or name to find a suitable font for…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question