PHP - About Uploading A Photo
I let my members to upload their photos,
I m using the script I coded which checks the file extension, if the file extension is "jpg" ( if ($this->url['type'] == "image/jpg")) and less than 600kb it uploads. Otherwise it gives you a warning.. What I wonder is, do I face any unwanted results about this later ? Like someone uploads a virus or script then execute it and do something ? Similar Tutorialswhat is the simple way to upload a photo to mysql or store in a dir, and update the database with the new url? adding photo,Array ( [name] => profilepic.jpeg [type] => image/jpeg [tmp_name] => C:\xampp\tmp\phpB923.tmp [error] => 0 [size] => 152127 ) Hi, We have been using this code for ages, but suddenly for some reason we cannot upload an image using the code below. When we try to Print_r the $profilephoto variable, I get this error. The filename is correct, but what is that [error]?? And how do I resolve it? Oddly it does upload it locally, but LIVE, it won't This is the code. if (isset($updatephoto)) { echo "adding photo,"; print_r($profilephoto); define ("MAX_SIZE","5000"); function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } $errors=0; if($_SERVER["REQUEST_METHOD"] == "POST") { $image =$_FILES["profilephoto"]["name"]; $uploadedfile = $_FILES['profilephoto']['tmp_name']; if ($image) { $filename = stripslashes($_FILES['profilephoto']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { echo "Unknown Extension..!"; } else { $size=filesize($_FILES['profilephoto']['tmp_name']); if ($size > MAX_SIZE*1024) { echo "File Size Excedeed..!!"; } if($extension=="jpg" || $extension=="jpeg" ) { $uploadedfile = $_FILES['profilephoto']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); } else if($extension=="png") { $uploadedfile = $_FILES['profilephoto']['tmp_name']; $src = imagecreatefrompng($uploadedfile); } else { $src = imagecreatefromgif($uploadedfile); echo $scr; } list($width,$height)=getimagesize($uploadedfile); $newwidth=600; $newheight=($height/$width)*$newwidth; $tmp=imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); $pic=($_FILES['profilephoto']['name']); $random = (rand()%99999999); $newname="$random"."$pic"; $filename = "images/profiles/". $newname; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); }} } $query = ("UPDATE users SET profilephoto =:newname WHERE id =:userid"); $result = $pdo->prepare($query); $result->execute(array(':userid' => $userid, ':newname' => $newname)); echo "<script> window.location.replace('/profile/') </script>";}
I wonna to upload photo with js and ajax.. i can do inserting something in mysql, but i dont know how to do with files :/ Form: Code: [Select] <form enctype="multipart/form-data" method="get"> <center> <label>Title: <input type="text" name="s_name" value="" style="width:250px" /></label> <label>Image: <input type="file" name="s_image" style="width:250px" /></label> <input class="button" type="submit" name="s_add" value="Add" style="width:100px" OnClick="save();" /> </center> </form> This is js code: Code: [Select] function save() { col = document.getElementById("new"); if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { col.innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","sources/save.php?i dont know what to insert here,true); xmlhttp.send(); } this is save.php: Code: [Select] <?php $allowed_size = 204800; $name = $_GET['name']; $name = $_GET['image']; $date = time(); if (save_img($up_imgfile, $up_imgname, $allowed_size)) { $query = "INSERT INTO table (name, image, date) VALUES ('{$name}', '{$image}', '$date')"; $result = mysql_query($query, $connection); if ($result) { echo "<p class='warn-green'>$season_name has been successful added</p>"; } else { echo "<p class='warn-red'>Error: $season_name is not added, try again.</p>"; } } } ?>save_img() is php function to upload photo and make thumb.. How can i do this thing to do this function, but i need this: $up_imgname = $_FILES['s_image']['name']; $up_imgfile = $_FILES['s_image']['tmp_name']; Becouse of that i cant do this, how can i get temp name, image name of uploaded file ? I'm having a problem understanding how to import more than one photo in a list of up to 20 photos. I can only import 1 photo from a comma delimited csv with a pipe between each photo url. <? function getImg($value,$userid, $stocknum){ $photoStr = ''; if($value !=''){ $photoURLs = explode('|', $value); for($i=0; $i<count($photoURLs);$i++){ $url = $photoURLs[$i]; $j = $i+1; if (@copy($url, "../upload/".$userid."/".$userid."_".$stocknum."_".$j.".jpg")) { $photoStr .= $userid."_".$stocknum."_".$j.".jpg|"; } } } return $photoStr; } ?> And after csv and sql <? if($img){ $img = rtrim($img, '|'); $imgArray = explode('|', $img); $imgIndex = 1; foreach ($imgArray AS $imgItem){ $db->query("UPDATE `stockitem` SET img".$imgIndex."= '$imgItem' where stocknum='$stocknum'","" , __FILE__, __LINE__); $imgIndex++; } } ?> Any help would be appreciated. Hi all, i was wondering if someone could point me in the right direction on how to create the following. After someone uploaded a photo than Cut out only his head in a fixed square say 90x120 pix (of a larger picture). I have seen some on the internet but most of them use flash and i rather use javascript or no javascript at all. Can this be done with GD library for instance where you just give the coordinates and the size of a square. (if this can be done automated i love to hear it) I have seen one where someone should pinpoint the eyes. IF someone has experience with this or a general idea on what techniques to use let me know I bet there are loads of way to do this but the most light weight technique would be great. Something like the attached image i am in the process of creating an auction site. However the images do not show , just the placeholder. Can anyone indicate where I have gone wrong ?
i am using this script to enter the items into the Database
html>
<link rel="stylesheet" type="text/css" href="style.css">
if(isset($_GET["item"]))
if($_GET["item"]=="duplicate")
else if($_GET["item"]=="successful")
}
echo "<label for='item_name' class='label'>Item Name:</label>";
echo "</form>";
</body>
This script displays the items :
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<body> session_start();
if(!isset($_SESSION["username"]))
else
$DBHOST = "localhost";
while($row = $result->fetch_assoc())
$iid = $row["item_id"];
$conn->close();
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> hello all, i have a photo uploader that clients use. i want this to be able to put clients photos in there own folder within a specified path. $(function() { $('#custom_file_upload').uploadify({ 'uploader' : '/uploadify.swf', 'script' : 'uploadify.php?user=<?php echo("$logged[ip]"); ?>', 'cancelImg' : '/cancel.png', 'folder' : '/wuploads/{$logged('email')}', 'multi' : true, 'auto' : true, 'fileExt' : '*.ZIP;*.zip;*.rar', 'queueID' : 'custom-queue', 'queueSizeLimit' : 1000, 'simUploadLimit' : 1000, 'removeCompleted': true, 'onSelectOnce' : function(event,data) { $('#status-message').text(data.filesSelected + ' files have been added to the queue.'); }, 'onAllComplete' : function(event,data) { $('#status-message').text(data.filesUploaded + ' files uploaded, ' + data.errors + ' errors.'); } }); }); i have tried the code above with 'folder' : '/wuploads/{$logged('email')}', but this doesnt seem to work, im new to php and tried a few different combinations but it wont budge! thanks, gavin G'day, on the home page of a website i'm building, i'm wanting to have a random photo that looks at all the subfolders of the gallery directory, but the best I can achieve is just one subfolder. Here is the code, if anyone can assist, that'll be appreciated. <?php function getRandomFromArray($ar) { mt_srand( (double)microtime() * 1000000 ); $num = array_rand($ar); return $ar[$num]; } function getImagesFromDir($path) { $images = array(); if ( $img_dir = @opendir($path) ) { while ( false !== ($img_file = readdir($img_dir)) ) { // checks for gif, jpg, png if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) { $images[] = $img_file; } } closedir($img_dir); } return $images; } $root = ''; // If images not in sub directory of current directory specify root //$root = $_SERVER['DOCUMENT_ROOT']; $path = 'gallery/topic1/'; // Obtain list of images from directory $imgList = getImagesFromDir($root . $path); $img = getRandomFromArray($imgList); ?> <center><a href="?GoTo=Photo Gallery"><img src="<?php echo $path . $img ?>" alt="" height="267" width="400"/></a></center> 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 Hi, I am making login page with database and php. I need to be able when the person clicks theogin button to take photo of the person and add it to that same database based on the info entered.
I am doing this to know if that person that logged in is the person in reality.
Is it possible 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> 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? Hai i got a site where i take the details of the visitors that enter my office premises. Now what i wanted is to add the photo of the visitor into that. i have a webcam with me through which i can take pictures. I dont have an idea how to do this on the website. I need some one to help me on this.. I dont know really where to start.. Any help would be greately appreciatd.. Hello, can you help me on my news article? I would like to be able to add photo on the article. Below is my codes Quote ======= html ======= <?php include_once ('post_news.php'); ?> <form Action="add_news.php" Method="post"> <input name="postdate" type="text" id="postdate"> <input name="title" type="text" id="title"> <textarea name="newstext" cols="60" rows="15" id="newstext"></textarea> <input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset"> </form> ============== php - post_news.php ============== <?php ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); if (isset ($_POST['submit'])) { require_once ('inc/dbConfig.php'); // Define the query. $query = "INSERT INTO news (id, postdate, title, newstext) VALUES (0,'{$_POST['postdate']}', '{$_POST['title']}','{$_POST['newstext']}')"; // Execute the query. if (@mysql_query ($query)) { print "<p>Data has been added.</p>"; } else { print "<p>Could add the entry because: <b>" . mysql_error() . "</b>. The query was $query.</p>"; } mysql_close(); } ?> ===== db structure ====== id int(10) unsigned NOT NULL auto_increment, postdate timestamp(14), title varchar(50) NOT NULL, newstext text NOT NULL, PRIMARY KEY (id), KEY postdate (postdate) Hope you guys can help me. Thanks! This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=317400.0 Hello: I am working with a script that I am using to make a player roster - the user can add a photo, player title, number, years played, and a bio. The data comes from a submit form, then goes to the code below to process everything. It works fine if a photo is added, but if a photo is not added, the script does not work. Any idea why, and how I can fix it? Code: [Select] <?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' ); $photos_uploaded = $_FILES['photo_filename']; $player_title = $_POST['player_title']; $player_number = $_POST['player_number']; $years_played = $_POST['years_played']; $photo_caption = $_POST['photo_caption']; while( $counter <= count($photos_uploaded) ) { if($photos_uploaded['size'][$counter] > 0) { if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types)) { $result_final .= "File ".($counter+1)." is not a photo<br />"; } else { //mysql_query( "INSERT INTO gallery_photos(`photo_filename`,`player_title`,`player_number`,`years_played`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); mysql_query( "INSERT INTO gallery_photos(`photo_filename`,`player_title`,`player_number`,`years_played`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($player_title[$counter])."', '".addslashes($player_number[$counter])."' , '".addslashes($years_played[$counter])."', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" ); $new_id = mysql_insert_id(); $filetype = $photos_uploaded['type'][$counter]; $extention = $known_photo_types[$filetype]; $filename = $new_id.".".$extention; mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" ); // Store the orignal file copy($photos_uploaded['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; //} { //$thumbnail_width = 690; //$thumbnail_height = (int)(500 * $size[1] / $size[0]); $old_width = $size[0]; $old_height = $size[1]; $thumbnail_width = 690; $thumbnail_height = ($old_height * $thumbnail_width / $old_width); } else { $thumbnail_width = (int)(690 * $size[0] / $size[1]); $thumbnail_height = 500; } // 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 ); $destination_handle = imagecreatetruecolor( $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."' style='margin-right: 20px; width: 100px;' />"; } } $counter++; } // Print Result echo <<<__HTML_END $result_final __HTML_END; ?> Thanks! 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/] Hi everyone! I'm trying to create a form with an upload photo bit in it. The photo i know, has to be saved on the server somewhere. Iv'e created an images folder both in my host's control pannel and in my dreamwever files and FTP'd it to the server. I've tried both ways of sending the test .jpg to each folder but i'm getting the desgined mySQL error. What's going worng here? Code: [Select] <?php //This is the directory where images will be saved $target = "/images/COMPANIES"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $company_name=$_POST['company_name']; $basicpackage_description=$_POST['basicpackage_description']; $location=$_POST['location']; $postcode=$_POST['postcode']; $upload=($_FILES['photo']['name']); // Connects to your Database mysql_connect("******host", "****username", "****password") or die(mysql_error()) ; mysql_select_db("****DB") or die(mysql_error()) ; //Writes the information to the database mysql_query("INSERT INTO `Companies` VALUES ('$company_name', '$basicpackage_description', '$location', '$postcode', '$upload')") ; //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> Thanks |