PHP - Photo Upload Direction And Support Please
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 Similar TutorialsHey 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? 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> 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/] 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 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."; } }
I want to create a shopping cart system for my website, but a simple shopping cart. I don't want a registration form or anything like that, just a way to add or delete a product..... so, how am I going to achieve this? I don't know! I don't know what I am even suppose to be looking for. Though, I do suspect I need to learn something called "PHP sessions" to store a cookie on someones computer to keep the shopping cart active. I use MySQL for my database, so I am guessing I will need to also create some form of temporary storage table as well. To be honest, I am shitting myself and have feared this task for over a month, but I am brave and going to take the plunge. In my head I can picture the process actually being very simple: a cookie is stored on someones computer > adding to cart simply is a HTML form that PHP then adds to MySQL > on purchase PHP calls the data from MySQL and forwards it to the payment gateway API. ... but I am only asking for advice on the PHP session and storing the cart in MySQL... The payment API will be a simple matter of PHP pulling information from MySQL and forwarding it to the API. Can someone please point me to the right.... concept... or something? I have not coded much for a while, and when I did it was minimal. I played with PHP5 and MySQL a little, but that was a couple of years ago. The last website I built was in 2004 and it was tables upon tables in html. I am starting to learn all over again, can anyone recommend a good starting place or book for what might as well be a beginner. Thanks Bill H guys, I have created a quiz, however what i would like to do is have something that keeps an eye on the quiz. For example if someone is taking the quiz however get 4 incorrect answers in a row then it will abort the quiz. is it something like a for loop for example.... im not sure? The code i already got is a basic quiz however im just looking on expaning it more. Thanks for any help, i appreciate it! Code: [Select] <?php session_start(); $_SESSION['dclty'] = $_POST['dclty']; ?> <?php if ($_SESSION['dclty'] == "beg") ?> <script> window.open("extrahelp.php", height=300,width=300); </script> <?php if ($_SESSION['dclty'] == "int") ?> <script> window.open("pointers.php", height=300,width=300); </script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Forensics E-learning Package</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div id="wrapper"> <div id="header"> <div id="toplinks"> </div> </div> <div id="menu"> <ul> <li><a class="selected" href="home.html">Home</a></li> <li><a href="initialquiz.php">Initial Quiz</a></li> <li><a href="about.php">About</a></li> </ul> </div> <div id="content"> <div id="main"> <h1>Initial Quiz</h1><BR /> <form name="Forensics Test" method="post" action="detection.php"> <h1>Protection</h1> <hr /> <b>1. What does an IDS do? <BR /><BR /></b> <UL> <? if($attempted == true && !isset($q1)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q1" id="q1a" value="1" />An IDS evaluates a suspected intrusion once it has taken place and signals an alarm<BR><? if($q1 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q1" id="q1b" value="2">An IDS blocks intrusions before it happens and signal an alarm<BR><? if($q1 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q1" id="q1c" value="3">An IDS blocks all intrusions before it happens and monitors the network, however does not signal an alarm.<BR><? if($q1 == "1"){echo "checked=\"checked\"";} ?></UL><hr /> <b>2. What does a Firewall do?<BR /><BR></b> <UL> <? if($attempted == true && !isset($q2)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q2" id="q2a" value="1">Firewalls limit access once the intrusion is within a network and then signals an alarm.<BR><? if($q2 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q2" id="q2b" value="2">Firewalls limit access between networks to prevent intrusion and do not signal an attack.<BR><? if($q2 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q2" id="q2c" value="3">Firewalls limit access to a network and prevent all intrusions. An alarm to the user is raised.<br><? if($q2 == "1"){echo "checked=\"checked\"";} ?></UL><hr /> <p><b>3. What does Tripwire do?</b> </p> <UL> <? if($attempted == true && !isset($q3)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q3" id="q3a" value="1">Tripwire does not protect from intrusions however signals an alarm to the user that network intrusions are occurring.<BR><? if($q3 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q3" id="q3b" value="2">Tripwire does not perform system integrity checks in terms of file change, however does prevent access to a network unless otherwise stated.<BR><? if($q3 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q3" id="q3c" value="3">Tripwire helps identify changes in files. Tripwire records a set of information about all the important files in your server in case of a change.</p><? if($q3 == "1"){echo "checked=\"checked\"";} ?> <BR> </UL><hr /> <p><b>4. What type of files does a traditional anti-virus protect you from?</b> </p> <UL> <? if($attempted == true && !isset($q4)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q4" id="q4a" value="1">Viruses and tracking cookies<BR><? if($q4 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q4" id="q4b" value="2">Rootkits and Viruses<BR><? if($q4 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q4" id="q4c" value="3">Worms and Rootkits<BR><? if($q4 == "1"){echo "checked=\"checked\"";} ?> </UL><hr /> <p><b>5. What does an Anti-root kit protect you from?</b> </p> <UL> <? if($attempted == true && !isset($q5)) { echo 'bgcolor="#FFFFCC"'; } ?> <input type="radio" name="q5" id="q5a" value="1">Anti-rootkit protects from only viruses, key loggers and backdoors.<BR><? if($q5 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q5" id="q5b" value="2">Anti-rootkit protects from viruses, backdoors, spyware and key loggers as a collection.<BR><? if($q5 == "1"){echo "checked=\"checked\"";} ?> <input type="radio" name="q5" id="q5c" value="3">Anti-rootkit protects from only viruses and backdoors.<BR><? if($q5 == "1"){echo "checked=\"checked\"";} ?> </UL> <HR><BR /><BR /> <input type="submit" value="Go to Next Section" /> </form> </div> <div id="right"> <h2>Right Menu</h2> <div class="rightitem"> <ul> <li><a class="selected" href="home.html">Home</a></li> <li><a href="initialquiz.php">Initial Quiz</a></li> <li><a href="about.php">About</a></li> </ul> </div> </div> </div> <div class="clearbottom"></div> <div id="footer"> <p id="legal"> </p> </div> </div> </div> </body> </html> I'm just starting to research xml and I need to know if there's a specific name I should be looking for. I'm trying to read data from an xml file which is easy when all the tags are different but I've got a test file of students where alot of the data is the same. For instance: <STUDENTS> <STUDENT> <FIRSTNAME>Micheal</FIRSTNAME> <LASTNAME>Dorne</LASTNAME> <GRADE>10</GRADE> <MATHSCORE>89</MATHSCORE> <TEACHER>Flinn</TEACHER> </STUDENT> <STUDENT> <FIRSTNAME>Terry</FIRSTNAME> <LASTNAME>Williams</LASTNAME> <GRADE>11</GRADE> <MATHSCORE>78</MATHSCORE> <TEACHER>Edwards</TEACHER> </STUDENT> <STUDENT> <FIRSTNAME>Kimberly</FIRSTNAME> <LASTNAME>Jenson</LASTNAME> <GRADE>10</GRADE> <MATHSCORE>92</MATHSCORE> <TEACHER>Flinn</TEACHER> </STUDENT> </STUDENTS> I've reached a point where I need to acquire data from an xml file structured similar to this and need to know where to start. I could be looking for all the data on one specific student or acquiring a list of all student names that have the same teacher for example. I'd appreciate it if someone could point me the right direction with this. Thanks. Hi guys, I, not sure if this post belongs here as I have no idea what the cause of my problem is. However I'm hoping i can post the problems i have and one of you guys might be able to point me in the right direction as to where the problem is. Anyway up until a few days ago i had a system set up using php and mysql for customers to login to there accounts, buy and sell items etc. Every time a client would buy or sell an item a conformation email would automatically be generated and sent out with all the correct info already saved in the email. This system would also save the buy or sell information and a system administrator could login and view this info. The problem I have right now is that, none of this information is being saved any more, and the emails are not being generated. A client can do anything they want but no details are being saved. This problem just came out of nowhere, one day its was working fine, as it has been for well over a year now and then BANG! Its not working any more. Another strange thing is that I cant even seem to login into the administrator area on any other browser than firefox? I have really no idea why that is. I would also like to add that I have made no changes to the php code or the sql data prior to this problem. and lastly I think i should mention that this same system is on another completely different server, and the system has the exact same problem. If anybody has any clues to this one, or point me in the right direction I would be most grateful, as it has me completely stumped. Thank you very much in advance. So i've been wanting to expand my php horizons if you will and finally break of my fear of OOP. Here's a simple connection script i built, however i'm kind of stuck on a part of it. user passes username/password. i instantiate the mysqlcon class and call the connect function. the connect function attempts a connection to the database. if successful, pass on the username and password to the authenticator class. call the authenticate function. select user based on username/passwrod criteria. if found return "Confirmed" otherwise "Denied" here's my issue, i'm assuming that my Code: [Select] return $this->ok variable is returned back to the mysqlcon class. however how can i return that variable once more back outside of the object class so that i can continue with my script assuming authentication was confirmed. Here's my code... thanks for the help! <?php ## OOP PRACTICE ## class mysqlcon { function connect($user,$pass) { //Note: Connect to the database $db = mysql_connect("localhost", "usr","psw") or die(mysql_error()); if(mysql_select_db("database",$db) or die(mysql_error())) { $auth = new authenticator(); $auth->authenticate($user,$pass); } } } class authenticator { var $ok = "Confirmed"; var $ex = "Denied"; function authenticate($user,$pass) { //Note: User user and pass variables to check for user in table $qry = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'"; $sql = mysql_query($qry) or die(mysql_error()); $cnt = mysql_num_rows($sql); if($cnt > 0) { return $this->ok; } else { return $this->ex; } } } $con = new mysqlcon(); $con->connect($_POST['username'],$_POST['password']); ?> PS: the classes are in class.php and the instantiation are in index.php. I just placed them together for easy of viewing. I've been at this for days, and the more I read the more confusing it gets. What I want to achieve is: I have a XHTML form with 5 user input fields - These a name subject cust_email telephone details I need to create a PHP script that will on user click - submit a email that has this format (secured if possible: From= cust_email Subject= "Customer requested information on" +subject eMail body= name + "requests information on" + subject /n + details /n + "Contact information" /n +telephone +email. So the body would look some how like this: Jane Smith requests information on Botox Hello I'm interested in botox injections please contact me with pricing and availability. Thank you. Contact information. (888)555-1212 Jsmith@hotmail.com Can you or anyone of the users in this wonderful forum HELP. I'm a print designer and I can assist you guys with anything you may need in print. But web is all to new and I'm struggling. Thank you, thank you very much. I am starting a project that will encompass the following- A forum script that will later be tied into it's own custom content management system. But I have some questions before I get too deep into starting: 1. What is the "most" secure way to code a forum system? 2. Shall I rely on 1 person to code or open it to the public to help too (open source)? 3. Which features of forum scripts do you like and why? 4. How should the plugin system (hooks) be designed? 5. Template system - what is the easiest way to make theming simple? These are just some of the basics that I am pondering at the moment. I know these may sound noobish but I would rather start this project the right way, instead of having it coded wrong etc.....and having to re-do everything down the road. Alright I didn't really know what to name the thread but w/e. I'm working on writing a blog, just for the purpose of something to apply what I'm learning it's not for production. I need someone to point me in the general direction of how the front page would look where after a post is made its on top and the older posts are below it: -- new post -- old post -- old post I don't want the code just a general direction of how I should go about it. Thanks much. Hello, I defnitely don't consider myself a coder but have been installing and troubleshooting pre-made php scripts for a few years now and figure now is a good time to learn as I'm quite sick of having to rely on outsourced help I am currently trying to create a simple (hope so) script that will run on a cron every other minute to insert a specific piece of data each time a new member joins and it should only insert the data once based on criteria. Here's what I'm trying to do exactly with a php script check members table if field signup_date is TODAY's Date and if user_balance field is 0.00 then alter/update user_balance field 25.00 Now, I've hit a bit of a roadblock with getting the MySQL query format correct. The SIGNUP_DATE field in the database is DATETIME format and the like with wildcard thing isn't working for me. Is there anyone who can point me in the right direction with the proper wildcard date format? It'd be a great help. Anything at all is massively appreciated. Here's the code I have so far...the echo is in there so I can see if it's working correctly. I'm pretty sure I haven't got the right function to display the result of the query either but I think I can figure that out pretty easily. Code: [Select] <?php $today = date("Y-m-d"); mysql_connect("localhost", "DBUSER", "DBUSER") or die(mysql_error()); mysql_select_db("DBNAME") or die(mysql_error()); $sql1 = mysql_query("SELECT USER_NAME FROM members WHERE SIGNUP_DATE LIKE '$today%"); if($sql1 == false) { user_error("Query failed: " . mysql_error() . "<br />\n$query"); } elseif(mysql_num_rows($sql1) == 0) { echo "<p>Sorry, no rows were returned by your query.</p>\n"; } $memberseligible = mysql_fetch_array($sql1); echo "$memberseligible"; ?> OK guys so I have my final project for school due next quarter and Its a database management application. I'm dont the upload edit delete scripting but now I need to do the search feature on the front end. I have a basic understanding of the search abilities in PHP but what i'd love to do is create something like Istockphoto.com and many other inventory sites that allow for a "search" field and also a filter. I'd assume there needs to be global variables that will set and adjust the query as things are checked or filled out. does anyone know of any examples/tutorials/demos that I can browse to start figuring this out? Thanks |