PHP - One Last Tweak For My Photo Upload Script
I have this script that I am using to upload new video galleries to a website. The script allows the user to upload an image that will display when they click on the gallery. As of now the image gets uploaded and a thumbnail is created automatically and stored in the appropriate places. The original image however remains its original dimensions. How would I tweak this script to resize the original image to MAX_WIDHT = 400px and MAX_HEIGHT = 750px along with keeping the create thumbnail feature?
Code: [Select] <?php require_once('Connections/DBConnect.php'); ?> <?php session_start(); if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "uploadvideo")) { // make the gallery name available for the result message $video = $_POST['videocaption']; // define a constant for the maximum upload size define ('MAX_FILE_SIZE', 256000); if (array_key_exists('upload', $_POST)) { // define constant for upload folder define('UPLOAD_DIR', 'C:/wamp/www/test/videos/video_photos/'); // replace any spaces in original filename with underscores // at the same time, assign to a simpler variable $file = str_replace(' ', '_', $_FILES['videophotoname']['name']); // convert the maximum size to KB $max = number_format(MAX_FILE_SIZE/1024, 1).'KB'; // create an array of permitted MIME types $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'); // begin by assuming the file is unacceptable $sizeOK = false; $typeOK = false; // check that file is within the permitted size if ($_FILES['videophotoname']['size'] > 0 && $_FILES['videophotoname']['size'] <= MAX_FILE_SIZE) { $sizeOK = true; } // check that file is of an permitted MIME type foreach ($permitted as $type) { if ($type == $_FILES['videophotoname']['type']) { $typeOK = true; break; } } if ($sizeOK && $typeOK) { switch($_FILES['videophotoname']['error']) { case 0: // define constants define('THUMBS_DIR', 'C:/wamp/www/test/videos/video_photos/thumbs/'); define('MAX_WIDTH', 150); define('MAX_HEIGHT',225); // process the uploaded image if (is_uploaded_file($_FILES['videophotoname']['tmp_name'])) { $original = $_FILES['videophotoname']['tmp_name']; // begin by getting the details of the original list($width, $height, $type) = getimagesize($original); // calculate the scaling ratio if ($width <= MAX_WIDTH && $height <= MAX_HEIGHT) { $ratio = 1; } elseif ($width > $height) { $ratio = MAX_WIDTH/$width; } else { $ratio = MAX_HEIGHT/$height; } // strip the extension off the image filename $imagetypes = array('/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/'); $name = preg_replace($imagetypes, '', basename($_FILES['videophotoname']['name'])); // move the temporary file to the upload folder $moved = move_uploaded_file($original, UPLOAD_DIR.$_FILES['videophotoname']['name']); if ($moved) { $result = $_FILES['videophotoname']['name'].' successfully uploaded; '; $original = UPLOAD_DIR.$_FILES['videophotoname']['name']; } else { $result = 'Problem uploading '.$_FILES['videophotoname']['name'].'; '; } // create an image resource for the original switch($type) { case 1: $source = @ imagecreatefromgif($original); if (!$source) { $result = 'Cannot process GIF files. Please use JPEG or PNG.'; } break; case 2: $source = imagecreatefromjpeg($original); break; case 3: $source = imagecreatefrompng($original); break; default: $source = NULL; $result = 'Cannot identify file type.'; } // make sure the image resource is OK if (!$source) { $result = 'Problem copying original'; } else { // calculate the dimensions of the thumbnail $thumb_width = round($width * $ratio); $thumb_height = round($height * $ratio); // create an image resource for the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); // create the resized copy imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); // save the resized copy switch($type) { case 1: if (function_exists('imagegif')) { $success = imagegif($thumb, THUMBS_DIR.$name.'_thb.gif'); $thumb_name = $name.'_thb.gif'; } else { $success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 50); $thumb_name = $name.'_thb.jpg'; } break; case 2: $success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 100); $thumb_name = $name.'_thb.jpg'; break; case 3: $success = imagepng($thumb, THUMBS_DIR.$name.'_thb.png'); $thumb_name = $name.'_thb.png'; } if ($success) { $insertSQL = sprintf("INSERT INTO tblmembervideo (videophotoname, videothumbname, videodescription, videocaption, modelid, `date`) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_FILES['videophotoname']['name'], "text"), GetSQLValueString($thumb_name, "text"), GetSQLValueString($_POST['videodescription'], "text"), GetSQLValueString($_POST['videocaption'], "text"), GetSQLValueString($_POST['modelid'], "int"), GetSQLValueString($_POST['date'], "date")); mysql_select_db($database_DBConnect, $DBConnect); $Result1 = mysql_query($insertSQL, $DBConnect) or die(mysql_error()); $videoid = mysql_insert_id(); $_SESSION['videoid'] = $videoid; $result .= "$thumb_name created and $video uploaded. Click <a href='addclip.php'>here</a> to add clips."; } else { $result .= 'Problem creating thumbnail'; } // remove the image resources from memory imagedestroy($source); imagedestroy($thumb); } } break; case 3: $result = "Error uploading $file. Please try again."; default: $result = "System error uploading $file. Contact webmaster."; } } elseif ($_FILES['videophotoname']['error'] == 4) { $result = 'No file selected'; } else { $result = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png."; } } } mysql_select_db($database_DBConnect, $DBConnect); $query_rsgetmodel = "SELECT modelid, modelname FROM tblmembermodel"; $rsgetmodel = mysql_query($query_rsgetmodel, $DBConnect) or die(mysql_error()); $row_rsgetmodel = mysql_fetch_assoc($rsgetmodel); $totalRows_rsgetmodel = mysql_num_rows($rsgetmodel); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <div align="center"> <?php // if the form has been submitted, display result if (isset($result)) { echo "<p>$result</p>"; } ?> </div> <form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="uploadvideo" id="uploadvideo"> Select a Photo (thumbnail will automatically be created) for Video:<br /> <input name="MAX_FILE_SIZE" type="hidden" id="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" /> <input type="file" name="videophotoname" id="videophotoname" /> <br /> <br /> Video Caption:<br /> <input type="text" name="videocaption" id="videocaption" /> <br /> <br /> Video Description:<br /> <textarea name="videodescription" id="videodescription" cols="35" rows="3"></textarea> <br /> <br /> Model:<br /> <select name="modelid" id="modelid"> <?php do { ?> <option value="<?php echo $row_rsgetmodel['modelid']?>"><?php echo $row_rsgetmodel['modelname']?></option> <?php } while ($row_rsgetmodel = mysql_fetch_assoc($rsgetmodel)); $rows = mysql_num_rows($rsgetmodel); if($rows > 0) { mysql_data_seek($rsgetmodel, 0); $row_rsgetmodel = mysql_fetch_assoc($rsgetmodel); } ?> </select> <br /> <br /> <input type="submit" name="upload" id="upload" value="Add Video" /> <input name="date" type="hidden" id="date" value="<?php echo date ("Y-m-d H:m:s"); ?>" /> <input type="hidden" name="MM_insert" value="uploadvideo" /> <br /> </form> </body> </html> <?php mysql_free_result($rsgetmodel); ?> [CODE/] Similar TutorialsI have a PHP comments filtration/validation script incorporated into my PHP/mysql custom built blog (under development).
This script uses REGEX to evaluate the format of user created comments. This function is supposed to accomplish the following tasks: All code except those in the whitelist must be wrapped in the permitted bbcode tags. The bbcode tags can not be empty The bbcode tags must be used in pairs other forms of bbcode tag must be rejected except if wrapped in the permitted bbcode tag user can not post only code, some descriptive text must be added to explain code. this text can be before or after the code. posted comment string must satisfy minimum and maximum length criteria I shall provide the developer with my current PHP script so he may understand how to lay the script out. If your are good at REGEX, contact me. Thanks. Hey guys, I am a newb but trying to figure out how I can upload multiple associated photo files. My code is working for one photo, however I would like to have multiple photos that are associated uploaded at the same time. I would like the photos save in a format such as: photo_filename1 = 100, photo_filename2 = 100_a I am using the following code with no luck, not sure how I can work this. Any help is much appreciated!!! Thanks in advance. <code> <?php include("config.inc.php"); // initialization $result_final = ""; $counter = 0; // List of our known photo types $known_photo_types = array( 'image/pjpeg' => 'jpg', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/bmp' => 'bmp', 'image/x-png' => 'png' ); // GD Function List $gd_function_suffix = array( 'image/pjpeg' => 'JPEG', 'image/jpeg' => 'JPEG', 'image/gif' => 'GIF', 'image/bmp' => 'WBMP', 'image/x-png' => 'PNG' ); // Fetch the photo array sent by preupload.php $photos_uploaded1 = $_FILES['photo_filename1']; $photos_uploaded2 = $_FILES['photo_filename2']; // Fetch the photo caption array $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded1) ) { if($photos_uploaded1['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded1['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename1`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded1['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename1='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded1['tmp_name'][$counter], $images_dir."/".$filename); // Let's get the Thumbnail size $size = GetImageSize( $images_dir."/".$filename ); if($size[0] > $size[1]) { $thumbnail_width = 100; $thumbnail_height = (int)(100 * $size[1] / $size[0]); } else { $thumbnail_width = (int)(100 * $size[0] / $size[1]); $thumbnail_height = 100; } // Build Thumbnail with GD 1.x.x, you can use the other described methods too $function_suffix = $gd_function_suffix[$filetype]; $function_to_read = "ImageCreateFrom".$function_suffix; $function_to_write = "Image".$function_suffix; // Read the source file $source_handle = $function_to_read ( $images_dir."/".$filename ); if($source_handle) { // Let's create an blank image for the thumbnail $destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height ); // Now we resize it ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] ); } // Let's save the thumbnail $function_to_write( $destination_handle, $images_dir."/tb_".$filename ); ImageDestroy($destination_handle ); // $result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } //file2 while( $counter <= count($photos_uploaded2) ) { if($photos_uploaded2['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded2['type'][$counter], $known_photo_types)) { $result_final2 .= "File ".($counter+1)." is not a photo<br />"; } else { mysql_query( "INSERT INTO gallery_photos(`photo_filename2`) VALUES('0')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded2['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id."_1.".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename2='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded2['tmp_name'][$counter], $images_dir."/".$filename); $result_final2 .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />"; } } $counter++; } // Print Result echo <<<__HTML_END <html> <head> <title>Photos uploaded</title> </head> <body> $result_final $result_final2 </body> </html> __HTML_END; ?> </code> Hey Guys, I have a php script that update's franchise information using a mysql table. Note: Ter = Territory, ie. the territory that franchise covers. <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo Upload //This is the directory where images will be saved $target = "images/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $photo =($_FILES['photo']['name']); //Pause Photo Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '{$_POST['photo']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo Upload //Writes the photo to the server move_uploaded_file($_FILES['photo']['tmp_name'], $target); //End of Photo Upload echo (mysql_affected_rows()) ? "Edited Branch.<br />" : "Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> In phpmyadmin I can see my table and it has the correct image name displayed in the photo column. So you would assume its worked. But when I look in the 'images/' location no image has been uploaded. So I think there is an error with the upload part but cant figure out whats wrong. Cheers, S I have used the same method for uploading photos for ages but feel there may be a better way. For both methods, please assume all uploads are large digital camera uploads of a few megabytes and thousands of pixels wide (as you would expect from large digital camera images). CURRENT METHOD (1) receive uploaded file and use ImageMagick to convert to 4 file sizes, then store these file sizes (also set so ImageMagick reduces the quality to something like a setting of 80 out of 100 which will further reduce file size. - file sizes (widths): 800 240 120 60 (mobile phones etc.) (2) Based on the type of size and view required I then use <img src="/photos/240/file.jpg to display (240 being the required image size of course) POSSIBLE BETTER METHOD (1) Use ImageMagick to reduce to 800 wide as will never display bigger than this anyway, reduce quality also. But don't resize further and only need one file. (2) Use PHP commands to display an image, and set height/width/quality then. Eg: <img src="showImage.php?file=file.jpg&width=240&quality=60 So both would do the same thing but the second seems better as you don't need to create 4 images for every photo upload. Why make lots of thumbnails when you can make one and then get PHP to create at the time of display? Although I suppose if you regularly displayed these images in a search result then PHP would need to do that extra processing on every search. Creating all 4 at the time of upload only requires the one bit of processing. Have I just found the answer? I am creating a system for my students. I teach Photography and I want to do more online integration for my class. As of right now I have a whole system in which the students have their on accounts on my site. Now the challenging part for me. I need students to upload photos to me, and I will critique them. My questions for this forum a 1. Should I have a line of code that creates a folder per user to upload photos to? 2. Should I have the photos stored in the SQL database? 3. Are there any scripts out there that can be easily adapted for this idea? Adam Still working on the same project. I had a function to upload a photo and you could use it as a profile picture. Now I wanted to expand on it and decided you can upload more than one photo, creating a gallery. I figured I could use the same script to create two images (one original size and one thumbnail for browsing) and went about it in two different ways, both failed miserably. First I figured my upload code could take the indata and make TWO photos at once with different name. I guess it can only keep on image in mind at once - or I did something else wrong. I used the same code to create $user.jpg and $user_tn.jpg and move them to the user's image folder. So try number two was to make two folders for the photo, one named after the user (for thumb) and another in a folder named big. That isn't working for me either. Anyone who likes to chime in with ideas or facepalms is very welcome. Here is the generic code I set out with: Code: [Select] if ($view == $user) { mkdir("grafik/users/$user"); mkdir("grafik/users/$user/big/"); if (isset($_FILES['image']['name'])) { $saveto = "grafik/users/$user/big/$user.jpg"; move_uploaded_file($_FILES['image']['tmp_name'], $saveto); $typeok = TRUE; switch($_FILES['image']['type']) { case "image/gif": $src = imagecreatefromgif($saveto); break; case "image/jpeg": case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break; case "image/png": $src = imagecreatefrompng($saveto); break; default: $typeok = FALSE; break; } if ($typeok) { list($w, $h) = getimagesize($saveto); $max = 200; $tw = $w; $th = $h; if ($w > $h && $max < $w) { $th = $max / $w * $h; $tw = $max; } elseif ($h > $w && $max < $h) { $tw = $max / $h *$w; $th = $max;} elseif ($max < $w) { $tw = $th = $max;} $tmp = imagecreatetruecolor($tw,$th); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h); imageconvolution($tmp, array( array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1) ), 8, 0); imagejpeg($tmp, $saveto); imagedestroy($tmp); imagedestroy($src); } } echo <<<_END <div id='main'> <form method='post' action='profile.php' enctype='multipart/form-data'> Image: <input type='file' name='image' size='14' maxlength='32' /> <input type='submit' value='Save Profile' /> </form> </div> _END; } It is the page in minimalist form and it still contains the big folder version. Thanks for putting up with my nooby questions. Hello: I wanted to learn how to add a file browse/save and send photo to a contact form. Form works fine, but I am trying to add this so a user can upload and send a photo of his or her artwork along with the contact information. Can someone tell me how this work? My other attempts failed so I'm trying to start with a clean form. This is the code I currently have: Code: [Select] <?php $error = NULL; $myDate = NULL; $FullName = NULL; $Address = NULL; $City = NULL; $State = NULL; $Zip = NULL; $Phone = NULL; $Email = NULL; $Website = NULL; $Comments = NULL; if(isset($_POST['submit'])) { $myDate = $_POST['myDate']; $FullName = $_POST['FullName']; $Address = $_POST['Address']; $City = $_POST['City']; $State = $_POST['State']; $Zip = $_POST['Zip']; $Phone = $_POST['Phone']; $Email = $_POST['Email']; $Website = $_POST['Website']; $Comments = $_POST['Comments']; if(empty($FullName)) { $error .= '<div style=\'margin-bottom: 6px;\'>- Enter your Name.</div>'; } if(empty($Email) || !preg_match('~^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$~',$Email)) { $error .= '<div style=\'margin-bottom: 6px;\'>- Enter a valid Email.</div>'; } if($error == NULL) { $sql = sprintf("INSERT INTO myContactData(myDate,FullName,Address,City,State,Zip,Phone,Email,Website,Comments) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')", mysql_real_escape_string($myDate), mysql_real_escape_string($FullName), mysql_real_escape_string($Address), mysql_real_escape_string($City), mysql_real_escape_string($State), mysql_real_escape_string($Zip), mysql_real_escape_string($Phone), mysql_real_escape_string($Email), mysql_real_escape_string($Website), mysql_real_escape_string($Comments)); if(mysql_query($sql)) { $error .= '<div style=\'margin-bottom: 6px;\'>Thank you for contacting us. We will reply to your inquiry shortly.<br /><br /></div>'; mail( "mt@gmail.com", "Contact Request", "Date Sent: $myDate\n Full Name: $FullName\n Address: $Address\n City: $City\n State: $State\n Zip: $Zip\n Phone: $Phone\n Email: $Email\n Website: $Website\n Comments: $Comments\n", "From: $Email" ); unset($FullName); unset($Address); unset($City); unset($State); unset($Zip); unset($Phone); unset($Email); unset($Website); unset($Comments); } else { $error .= 'There was an error in our Database, please Try again!'; } } } ?> <form name="myform" action="" method="post"> <input type="hidden" name="myDate" size="45" maxlength="50" value="<?php echo date("F j, Y"); ?>" /> <div id="tableFormDiv"> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">* - Required</span></span> <span class="floatFormLeft"> </span></fieldset> <?php echo '<span class="textError">' . $error . '</span>';?> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">*</span> Full Name:</span> <span class="floatFormLeft"><input type="text" name="FullName" size="45" maxlength="50" value="<?php echo $FullName; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Address:</span> <span class="floatFormLeft"><input type="text" name="Address" size="45" maxlength="50" value="<?php echo $Address; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">City:</span> <span class="floatFormLeft"><input type="text" name="City" size="45" maxlength="50" value="<?php echo $City; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">State:</span> <span class="floatFormLeft"><input type="text" name="State" size="45" maxlength="50" value="<?php echo $State; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Zip:</span> <span class="floatFormLeft"><input type="text" name="Zip" size="45" maxlength="50" value="<?php echo $Zip; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Phone:</span> <span class="floatFormLeft"><input type="text" name="Phone" size="45" maxlength="50" value="<?php echo $Phone; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth"><span class="textErrorItalic">*</span> Email:</span> <span class="floatFormLeft"><input type="text" name="Email" size="45" maxlength="50" value="<?php echo $Email; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Website:</span> <span class="floatFormLeft"><input type="text" name="Website" size="45" maxlength="50" value="<?php echo $Website; ?>" /></span></fieldset> <fieldset><span class="floatLeftFormWidth">Comments:</span> <span class="floatFormLeft"><textarea name="Comments" cols="40" rows="10"><?php echo $Comments; ?></textarea></span></fieldset> </div> <input type="submit" name="submit" value="Submit" class="submitButton" /><br /> </form> Thanks very much! (1) What does this actually do? (compress it?) $image = imagecreatefromjpeg("image.jpg"); header('Content-Type: image/jpeg'); imagejpeg($image); By using this rather than displaying by using www.site.com/image.jpg it reduces file size of an image from 2.5mb to 0.5mb !! (2) ImageMagick can't get these results. Am I doing something wrong? If I change the pixel size of an image in ImageMagick then I can reduce its file size, but (1) above reduces file size regardless of changing pixel size. Hi, I am working on a registration login system and after a person registers and logs in, they will get the option to upload a profile picture. The picture and registration info will need to be in two different tables. I want to know the best way to associate the two (registration info and photo) so that I know who's picture goes with what registration info? I thought about IP address, but a user might register on one computer and login and upload a photo on another computer. Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks Hi all, i've set this script for my gallery, it works, it display me the name of the albums, but when i click to see the pictures inside, the page is blank, and also don't appear the "Back to the albums" link, i can't find the error in the code... Code: [Select] <html> <head> <script type="text/javascript" src="../lightbox2.05/js/lightbox.js"> </script> </head> <body> <?php $page = $_SERVER['PHP_SELF']; //settings $column = 5; //directories $base = "carrelli_noleggio"; $thumbs = "thumbs"; // get album $get_album = $_GET['album']; //if no album selected if (!$get_album) { echo "<b>Select an album:</b><p />"; //find each album and display as links $handle = opendir($base); while (($file = readdir($handle))!==FALSE) { if (is_dir($base."/".$file) && $file != "." && $file != ".." && $file != $thumbs) { echo "<a href='$page?album=$file'>$file</a><br />"; } } closedir($handle); } else { //check if album exist, and additional security checks if (!is_dir($base."/".$get_album) || strstr($get_album,".") !=NULL || strstr($get_album,"/") !=NULL || strstr($get_album,"\") !=NULL) { echo "Album doesn't exist."; } else { $x = 0; echo "<b>$get_album</b><p />"; $handle = opendir($base."/".$get_album); while (($file = readdir($handle)) !== FALSE) { if ($file != "." && $file != "..") { echo "<table style='display:inline;'><tr><td><a href='$base/$get_album/$files' ref='lightbox'<img src='$base/$thumbs/$file' height='100' width'100'></a></td></tr></table>"; $x++; if ($x==$column) { echo"<br />"; $x = 0; } } } closedir($handle); echo "<p /><a href='$page>Back to albums</a>"; } } ?> </body> </html> HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hi i have found this code : <?php if (isset($_POST['submit_bilde'])) { $error = 'Wrong image file..'; define( 'THUMBNAIL_IMAGE_MAX_WIDTH', 250 ); define( 'THUMBNAIL_IMAGE_MAX_HEIGHT', 250 ); function generate_image_thumbnail( $source_image_path, $thumbnail_image_path ) { list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $source_image_path ); switch ( $source_image_type ) { case IMAGETYPE_GIF: $source_gd_image = imagecreatefromgif( $source_image_path ); break; case IMAGETYPE_JPEG: $source_gd_image = imagecreatefromjpeg( $source_image_path ); break; case IMAGETYPE_PNG: $source_gd_image = imagecreatefrompng( $source_image_path ); break; } if ( $source_gd_image === false ) { return false; } $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH; $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT; $source_aspect_ratio = $source_image_width / $source_image_height; $thumbnail_aspect_ratio = $thumbnail_image_width / $thumbnail_image_height; if ( $source_image_width <= $thumbnail_image_width && $source_image_height <= $thumbnail_image_height ) { $thumbnail_image_width = $source_image_width; $thumbnail_image_height = $source_image_height; } elseif ( $thumbnail_aspect_ratio > $source_aspect_ratio ) { $thumbnail_image_width = ( int ) ( $thumbnail_image_height * $source_aspect_ratio ); } else { $thumbnail_image_height = ( int ) ( $thumbnail_image_width / $source_aspect_ratio ); } $thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height ); imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height ); imagejpeg( $thumbnail_gd_image, $thumbnail_image_path, 100 ); imagedestroy( $source_gd_image ); imagedestroy( $thumbnail_gd_image ); return true; } define( 'UPLOADED_IMAGE_DESTINATION', 'annonsebilder/orginaler/' ); define( 'THUMBNAIL_IMAGE_DESTINATION', 'annonsebilder/thumbs/' ); function process_image_upload( $field ) { $temp_image_path = $_FILES[ $field ][ 'tmp_name' ]; $temp_image_name = $_FILES[ $field ][ 'name' ]; list( , , $temp_image_type ) = getimagesize( $temp_image_path ); if ( $temp_image_type === NULL ) { return false; } switch ( $temp_image_type ) { case IMAGETYPE_JPEG: break; default: return false; } $uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name; move_uploaded_file( $temp_image_path, $uploaded_image_path ); $random_digit=rand(0000000000000,9999999999999); $thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace( '{\\.[^\\.]+$}', '.jpg', $annonse_ref.'_'.$random_digit.'.jpg' ); $result = generate_image_thumbnail( $uploaded_image_path, $thumbnail_image_path ); return $result ? array( $uploaded_image_path, $thumbnail_image_path ) : false; } for ( $i = 1; $i <= 5; $i++ ) { if ( $_FILES[ 'Image' . $i ][ 'error' ] == 0 ) { $result = process_image_upload( 'Image' . $i ); } } if ( $result === false ) { echo $error; } else { //THIS ECHO SHIT IS KILLIN' ME!!! echo '<br />1: '.$result['1'] ; echo '<br />2: '.$result['2']; echo '<br />3: '.$result['3']; echo '<br />4: '.$result['4']; echo '<br />5: '.$result['5']; } } if (!isset($_POST['submit_bilde'])) { ?> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="Image1"><br> <input type="file" name="Image2"><br> <input type="file" name="Image3"><br> <input type="file" name="Image4"><br> <input type="file" name="Image5"><br><br> <input type="submit" value="GOOOOOOOO!!!!" name="submit_bilde"> </form> <?}?> and if you look in the code there is a part where i want to echo the uploaded files' path's.. I only se one of those 5 files listet in the "echo"-thing :p Can someone please, please, please help me to echo ALL the 5 images path?? I currently have the following script used on my site to upload files. When the linked web page executes it, however, I receive the infamous Parse Error - Unexpected '<' in x:/xxxx. The problem lies in Line 11 where I attempt to define a command that will display a message box to the user upon successful file upload. The syntax is not correct and I was hoping someone would be able to help me with it. Here is the contents of the PHP file. <?php // Where the file is going to be placed $target_path = $_SERVER['DOCUMENT_ROOT'] . "/file_uploads/"; /*Add the original filename to our target path. Result is "uploads/filename.extension"*/ $target_path=$target_path.basename($_FILES['file']['name']); //Move file to upload directory if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { echo <script type="text/javascript">alert("Upload was successful. Thank you for your contribution")</script>; } else{ echo "There was a problem submitting the file. Plese try again!"; } ?> Thank you in advance for any help. After days of agony, I finally figured out a way to display my blog posts masonry style.
However, I now want to find out if I can make it look exactly (or close to) the static design that I had before which is this :
http://pier36nyc.com/events/
How my dynamic masonry looks like right now on my localhost:
http://postimg.org/image/uy5jb4zax/
This is the code for the masonry:
<script> Hey guys!! i'm after a bit of help with a script i am using for simple image upload to server. At the moment the script works fine and will allow upload of JPG files, i want to extend on this to allow GIF and PNG files to be uploaded aswell. This is the script i am using... <?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 600Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 600000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! You can use the following link in the IMS:" .$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 600Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } // $sessionid=session_id() //$newname=$_SESSION['session_name'] header( 'Location: success.php?newname1='.$filename ) ; ?> Any help would be appriciated!! ta!! jonny Hello, I'm planning on making a website where people are able to upload files and directly link to them. Ideally, I want to keep the same file names that the people use when they upload the file. I was planning on keeping the directory that stored all of the files outside of the www directory and disable execute permissions. However, how would I avoid file overwriting with the same file name? Hi All Not so much help as here is a handy class for uploading images Please feel free to find security bugs and let me know. Also feel free to use it if you want. http://onlyican.com/test_samples/bl_upload_img.phps To use the class, simply use the following require_once('bl_upload_img.php'); $objUploadImg = new UploadImg(); //Set values here if you wish such as $objUploadImg->setFormField('myFormField'); // The Name from <input type="file" name="myFormField" /> $objUploadImg->setSaveDirMain($_SERVER['DOCUMENT_ROOT'].'/MyImageFolder'; //Make sure to set the permissions //You can change most settings, just look at the function setDetaultValues() to get the function name //Now upload the image if($objUploadImg->uploadImage()){ $strFileName = $objUploadImg->getFileNameMain(); }else{ echo 'Error uploading Image<br />'.$objUploadImg->getErrorMessage(); } hello i am adding an image upload script, so users can upload a image with the recipe they are adding, but my script seems to not work, these are the files. add_recipe.php <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta name="Description" content="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form enctype="multipart/form-data" action="include/recipe.php" method="post"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"></th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="prep" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="cook" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> Choose a picture to upload: <input name="uploaded_file" type="file" /></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> <tr> <td> </td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipe.php (upload form script) <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; mysql_real_escape_string($user); //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); $uploaded_file=$_POST['files']['uploaded_file'] //Сheck that we have a file if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/upload/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } header("Location: ../recipe_added.php"); //} ?> im getting a warning saying 'Warning: mkdir() [function.mkdir]: File exists in /home/multisea/public_html/BSGN/secure_upload.php on line 5' if i execute the script below Code: [Select] <?php $secure_folder = "upimg/$rand/$time"; $rand=rand(0000000000,9999999999); $time=time(); mkdir("$secure_folder", 0777); echo "secure folder made successfully... not done yet so dont close this window..."; $target = "$secure_folder"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; if ($uploaded_size > 1500000) { echo "Your file is too large.<br>"; $ok=0; } if ($ok==0) { echo "sorry your file was not uploaded..."; } else {if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {echo "the file ". basename( $_FILES['uploadedfile']['name']). "hasbeen uploaded the link to your file is http://multi-search.org/BSGN/$secure_folder/". basename( $_FILES['uploaded']['name'])."<br />"; } else {echo "sorry, there was a problem uploading your file."; } } ?> |