PHP - Problem With White Spaces On Image File Upload?
Hi im having trouble with uploading images with spaces in as they dont show up in the browser.
Here is the code: Code: [Select] $image = addslashes($_FILES['image']['name']); $target = "images/"; $target = $target . basename( $_FILES['image']['name']); //Writes the photo to the server if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) { Any help would be appreciated. Similar TutorialsThis topic has been moved to PHP Installation & Configuration. http://www.phpfreaks.com/forums/index.php?topic=307015.0 Code: [Select] Address: 351 Hougang Ave 3 (769057) Contact No: 6752 5513 Operating Hours: 8.00am - 9.30pm (Thursday to Tuesday & Public Holidays) Background: Opened to the public on 30 Mar 88 Hi good day, if I paste the above address into one of the mysql field, I found out that I cannot fetch it using php. It give me a blank page. Code: [Select] Address: 351 Hougang Ave 3 (769057) Contact No: 6752 5513 Operating Hours: 8.00am - 9.30pm (Thursday to Tuesday & Public Holidays) Background: Opened to the public on 30 Mar 88 When I sort it together then i can see mysql working, very strange.. Can anyone help? Guys: What is the way to remove white spaces in front of a form entry ? Should I use regular expression for this ? Thanks. Hi I am new to PHP... I wanted to design a banner.. the require data should be entered by user like Name of a banner, Details as well as Image to display on it. I think for this I may need to use file upload option.. I tried this but $Files not working for me... some times its shows diff errors on diff browsers, I am new to PHP I dont know what is the prob. I dont have any code on this... if anyone have any tutorial on this, that will be the gr8 help as I am trying to solve this from last 1 and 1/2 week.. I used http://www.tizag.com/phpT/fileupload.php its showing error msg There was an error uploading the file, please try again! Thanks in adavnce I have a flash application that calls php script to do the image file upload and save the image in jpg format in thumbnail size. I swear it worked at one time, and then as I tried to figure out how to covert other image formats that are not currently built-in in php library (createimagefrom... functions), I played around with it a little bit, then it doesn't upload file any more!!! What I got, is that NONE of the image files is saved in my designated image folders, subsequently the flash application comes up with a broken image link. PLEASE HELP! MANY THANKS! Here's the relevant flash code: Code: [Select] private function uploadFiles():void { var curTime:Date = new Date(); timeStamp = curTime.valueOf().toString(); var variables:URLVariables = new URLVariables("timeStamp=" + timeStamp); var request:URLRequest = new URLRequest(ModelLocator.getInstance().serverPath+"uploadArtImages.php"); request.method = URLRequestMethod.POST; request.data = variables; file.upload(request); Application.application.showLoading(); } Here's my php script: (it's really a simple script, a big chunk of it is just some functions that does error checking and image conversions) <?php $timeStamp = $_POST['timeStamp']; $file = $_FILES['Filedata']; $tempFile = $file['tmp_name']; $fileName = $file['name']; $fileSize = $file['size']; $errorCode = 0; //0: success $allowedExtensions = array("jpg", "bmp", "png", "gif", "tif", "ps", "eps", "pdf"); $mime = array('image/gif' => 'gif', 'image/jpeg' => 'jpg', 'image/png' => 'png', 'application/x-shockwave-flash' => 'swf', 'image/psd' => 'psd', 'image/bmp' => 'bmp', 'image/tiff' => 'tif', 'image/jp2' => 'jp2', 'image/iff' => 'iff', 'image/vnd.wap.wbmp' => 'bmp', 'image/xbm' => 'xbm', 'image/vnd.microsoft.icon' => 'ico'); public function imagecreatefrombmp($p_sFile) { // Load the image into a string $file = fopen($p_sFile,"rb"); $read = fread($file,10); while(!feof($file)&&($read<>"")) $read .= fread($file,1024); $temp = unpack("H*",$read); $hex = $temp[1]; $header = substr($hex,0,108); // Process the header // Structu http://www.fastgraph.com/help/bmp_header_format.html if (substr($header,0,4)=="424d") { // Cut it in parts of 2 bytes $header_parts = str_split($header,2); // Get the width 4 bytes $width = hexdec($header_parts[19].$header_parts[18]); // Get the height 4 bytes $height = hexdec($header_parts[23].$header_parts[22]); // Unset the header params unset($header_parts); } // Define starting X and Y $x = 0; $y = 1; // Create newimage $image = imagecreatetruecolor($width,$height); // Grab the body from the image $body = substr($hex,108); // Calculate if padding at the end-line is needed // Divided by two to keep overview. // 1 byte = 2 HEX-chars $body_size = (strlen($body)/2); $header_size = ($width*$height); // Use end-line padding? Only when needed $usePadding = ($body_size>($header_size*3)+4); // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption // Calculate the next DWORD-position in the body for ($i=0;$i<$body_size;$i+=3) { // Calculate line-ending and padding if ($x>=$width) { // If padding needed, ignore image-padding // Shift i to the ending of the current 32-bit-block if ($usePadding) $i += $width%4; // Reset horizontal position $x = 0; // Raise the height-position (bottom-up) $y++; // Reached the image-height? Break the for-loop if ($y>$height) break; } // Calculation of the RGB-pixel (defined as BGR in image-data) // Define $i_pos as absolute position in the body $i_pos = $i*2; $r = hexdec($body[$i_pos+4].$body[$i_pos+5]); $g = hexdec($body[$i_pos+2].$body[$i_pos+3]); $b = hexdec($body[$i_pos].$body[$i_pos+1]); // Calculate and draw the pixel $color = imagecolorallocate($image,$r,$g,$b); imagesetpixel($image,$x,$height-$y,$color); // Raise the horizontal position $x++; } // Unset the body / free the memory unset($body); // Return image-object return $image; } function ValidateImageFile($input_file, &$width, &$height, &$type) { global $allowedExtensions; global $mime; global $errorCode; $errorCode = 0; //reset $width = 0; $height = 0; $type = 0; $file_info = getimagesize($input_file['tmp_name']); if(!$file_info || empty($file_info)) { // No Image? //$error = "The uploaded file doesn't seem to be an image."; $errorCode = 1; return FALSE; } else { // An Image? check extension // Get File Extension (if any) $file_name = $input_file['name']; $dotExt = strrchr($file_name, "."); if (!$dotExt) { //no extension found $errorCode = 2; return FALSE; } else { $ext = strtolower(substr($dotExt, 1)); $ext = ($ext == 'jpeg') ? 'jpg' : $ext; //convert jpeg to jpg $ext = ($ext == 'tiff') ? 'tif' : $ext; if(!in_array($ext, $allowedExtensions)) { //has extension, but invalid //$error .= "You must upload a file with one of the following extensions: ".$exts; $errorCode = 2; return FALSE; } else { $file_mime = $file_info['mime']; //if($ext == 'jpc' || $ext == 'jpx' || $ext == 'jb2') { // $extension = $ext; //} else { // $extension = ($mime[$file_mime] == 'jpeg') ? 'jpg' : $mime[$file_mime]; //} //if(!$extension) { // $extension = ''; // $file_name = str_replace('.', '', $file_name); //} if (strcmp($mime[$file_mime], $ext)) { $errorCode = 3; return FALSE; //strcmp non zero, mime type doesn't match ext, error! } } } } $width = $file_info[0]; $height = $file_info[1]; $type = $file_info[2]; return TRUE; } // $w_dst = maximum width of thumbnail // $h_dst = maximum height of thumbnail // $n_img = new thumbnail name function ConvertPic($w_dst, $h_dst, $new_img, $file_src, $w_src, $h_src, $type_src) { ini_set('memory_limit', '100M'); // handle large images unlink($new_img); // remove old images if present if ($w_src > $w_dst || $h_src > $h_dst) { $ratio = $w_src/$h_src; if ($w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);} } else { $w_dst = $w_src; $h_dst = $h_src; } switch ($type_src) {case 1: //IMAGETYPE_GIF: // 1: gif -> jpg $img_src = imagecreatefromgif($file_src); break; case 2: //IMAGETYPE_JPEG: // 2: jpeg -> jpg $img_src = imagecreatefromjpeg($file_src); break; //case IMAGETYPE_JPEG2000: // $img_src = imagecreatefromjpeg($file_src); // break; case 3: //IMAGETYPE_PNG: // 3: png -> jpg $img_src = imagecreatefrompng($file_src); break; case IMAGETYPE_WBMP: // wbmp -> jpg $img_src = imagecreatefromwbmp($file_src); break; case IMAGETYPE_XBM: $img_src = imagecreatefromxbm($file_src); break; case IMAGETYPE_BMP: $img_src = imagecreatefrombmp($file_src); break; } $img_dst = imagecreatetruecolor($w_dst, $h_dst); // resample imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src); imagejpeg($img_dst, $new_img); // save new image, always jpg imagedestroy($img_src); imagedestroy($img_dst); } $uploadFileName = ''; if($file['error'] == UPLOAD_ERR_OK) { $width = 0; $height = 0; $type = 0; $dir = "./art_images/"; $dirThumb = "./art_images_thumb/"; if(ValidateImageFile($file, $width, $height, $type)) { # Do uploading here // make a unique filename for the uploaded file and check it is not already // taken... if it is already taken keep trying until we find a vacant one // sample filename: 1140732936-filename.jpg //$now = time(); //$uploadFileName = $now.'-'.$fileName; //while(file_exists($dir.$uploadFileName)) { // $now++; // $uploadFileName = $now.'-'.$fileName; //} $uploadFileName = $timeStamp . '-' . $fileName; unlink($dir . $uploadFileName); //make sure there's no exist file if (!move_uploaded_file($tempFile, $dir . $uploadFileName)) { //echo "cannot move file, nothing uploaded"; $errorCode = 4; } else { ConvertPic(150, 150, $dirThumb . $uploadFileName, $dir . $uploadFileName, $width, $height, $type); //echo $uploadFileName; } } else { //echo "file not valid" . $errorCode; } } else { //echo "upload error"; $errorCode = 5; } ?> files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
Code I'm using if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Successfully uploaded image!"; if (file_exists("img/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "img/" . $_FILES["file"]["name"]); echo "<a href='img/$filename'>Your File</a>; } } } else { echo "Invalid file"; } mysql_query("INSERT INTO $tbl (body, name, subject, ip, timestamp, img) VALUES ('$body', '$name', '$subject', '$ip', '$timestamp', '$imglink')"); mysql_query("INSERT INTO total (ip, subject, name, board) VALUES ('$ip','$subject','$name','$dfg')"); echo "<font color='red'><font size='15'><strong><center>Successfully posted to /$tbl/"; //print("<meta http-equiv='REFRESH' content='0;url=index.php?board=$tbl'>"); If I have the query on the top it runs, and the upload img doesn't && vice versa Going to try and explain this the best I can but I don't really have the best idea on what's happening here. I have a submission form for users to fill out their information and upload an image. I've set the file limit size at 500000 which I assumed would be safe for images at 400k or below. When testing locally, any image that is below that file size gets uploaded successfully. However, when testing on my online host/server.. the submission form and data is successfully entered but the image isn't saved at all. It obviously isn't over the size of the file limit I set because it dooesn't return an error.. it successfuly submits but doesn't save or resize my image. I really have no clue what the problem could be. I went over the variables I set for folder locations to move the image to and everything works fine locally, but once on the host and online, it doesn't happen. Hi guys, with code below i can upload pictures to database, however i need to limit the file upload. I have this code done with help of php freak forum and i am a newbie so can u help me please? thanks in advance if (isset($_POST['register']) && $_POST['register']){ //image1 $nameone=$_FILES['myfileone']['name']; if ($nameone) { $dst_filename = resize_upload_image($_FILES['myfileone'], "images/"); if ($dst_filename !== false) { extract($dst_filename); $image1 = mysql_query ("INSERT INTO img SET image='$img_filename', thumb='$thumb_filename', refimage='$reference'"); } } } ?> <form action='' method='POST' enctype='multipart/form-data'> <p>File: <input type='file' name='myfileone'> Hello Im trying to upload mp3s from a form. In the form I have the MAX_FILE_SIZE set at 90000000 (so big to make sure it wasn't my maths). I have checked with phpinfo() and the max upload is set at 8mb. The mp3s will be between 3-4mb in size. I have uploaded small mp3's successfully (440k) so i know the script is working fine, however when i try to upload one at around 3mb it fails, even tried different file sizes in the same ball park size. I suspect the server is blocking them. Any ideas on a fix? Thank you. No script posted as i say its all working. I've Got here a code.. it can upload pdf file. but it doesnt accept word documents and powerpoints And i dont know the problem.. Here's The code.. Code: [Select] <?php session_start(); if(isset($_SESSION['uname2'])){ if($_POST['lesson']!=""){ if (($_FILES["Mapfile"]["type"] == "application/acrobat") ||($_FILES["Mapfile"]["type"] == "application/x-pdf") || ($_FILES["Mapfile"]["type"] == "application/pdf") || ($_FILES["Mapfile"]["type"] == "text/pdf") || ($_FILES["Mapfile"]["type"] == "application/powerpoint") || ($_FILES["Mapfile"]["type"] == "application/msword") || ($_FILES["Mapfile"]["type"] == "text/x-pdf") && ($_FILES["Mapfile"]["size"] < 50000)) { if ($_FILES["Mapfile"]["error"] > 0) { echo "Error: " . $_FILES["Mapfile"]["error"] . "<br />"; } else { if (file_exists("upload/" . $_FILES["Mapfile"]["name"])) { echo '<script type="text/javascript"> {alert("'.$_FILES["Mapfile"]["name"] .' already exist");} </script>'; echo '<meta http-equiv="REFRESH" content="0;url=uploadlesson.php">'; } else { move_uploaded_file($_FILES["Mapfile"]["tmp_name"], "upload/" . $_FILES["Mapfile"]["name"]); echo '<script type="text/javascript"> {alert("File Uploaded!");} </script>'; echo '<meta http-equiv="REFRESH" content="0;url=uploadlesson.php">'; $host="localhost"; $username="root"; $password=""; $db_name="dbprof"; mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $user = $_SESSION['uname2']; $sql="SELECT * FROM registeredprof where Username = '$user'"; $result=mysql_query($sql) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { $fullname = $row['fullname']; } $title = $_POST['lesson']; $filename = $_FILES['Mapfile']['name']; mysql_query("INSERT INTO lessondb (author, title, filename, status) VALUES ('$fullname', '$title', '$filename', 'offline')"); } } } else { echo '<script type="text/javascript"> {alert("Invalid File! ");} </script>'; echo '<meta http-equiv="REFRESH" content="0;url=uploadlesson.php">'; } } else { echo '<script type="text/javascript"> {alert("Fill out Title!");} </script>'; echo '<meta http-equiv="REFRESH" content="0;url=uploadlesson.php">'; } } ?> Help pls. Hi everybody, I have recently change to a new server, and have some problem with a script for uploading files on my new server. Script is an old which I have updated with new php command, <? not accepted in new server. Scripts shall upload picture to folder in server and write information to database From form script I am saving my upload Code: [Select] <input type="hidden" name="Mode" value="EditMapProperty" /> <input type="hidden" name="Old_Map" value="<?php echo $Property->Get_Map();?>" /> In my php script I do elseif($Mode=="EditMapProperty"): $Map_name = $HTTP_POST_FILES['Map']['name']; $Property=new Property($PropertyID); $ReferenceNo=$Property->Get_ReferenceNo(); if($Map!=""): $DeleteMap=$Dir_MapProperty_Admin."".$Property->Get_Map(); @unlink($DeleteMap); endif; if($Map_name==""): $Map=$Old_Map; else: copy($HTTP_POST_FILES['Map']['tmp_name'], $Dir_MapProperty_Admin."".$ReferenceNo."-".$Map_name); $Map=$ReferenceNo."-".$Map_name; endif; $Property->EditMap($Map); //Update database information echo "<meta http-equiv=\"refresh\" content=\"0;URL=$Redirect2?p=property_details&PropertyID=$PropertyID\">"; () Can any help if there are any PHP problem in this coding. Kind Regards Tom Hi All, I have a code to upload a file to the server. Somehow the files don't get uploaded, although the record is add to the database. I have no clue why it doesn't work. The settings of the folder where the docs goto is set to 777. Code: [Select] <?php $uploaddir = "documents/"; $path = $uploaddir.$document; //This function reads the extension of the file. $allowedExtensions = array("doc", "pdf", "xls"); function isAllowedExtension($fileName) { global $allowedExtensions; return in_array(end(explode(".", $fileName)), $allowedExtensions); } if($document != ""){ //AS LONG AS A FILE WAS SELECTED... //compare the size with the maxim size we defined and print error if bigger $fsize=filesize($_FILES['document']['tmp_name']); if (($fsize/1024) > $poidsMax*1024) { $msgToUser = '<br /><br /><font color="#FF0000">You exceeded the filesize limit. Document did not get posted.</font>'; include_once 'msgToUser.php'; $errors=1; } if(isAllowedExtension($HTTP_POST_FILES['document']['tmp_name'])) { if(copy($HTTP_POST_FILES['document']['tmp_name'], $path)){ //IF IT HAS BEEN COPIED... //GET FILE NAME $theFileName = $HTTP_POST_FILES['document']['name']; //GET FILE SIZE $theFileSize = $HTTP_POST_FILES['document']['size']; if ($theFileSize>999999){ //IF GREATER THAN 999KB, DISPLAY AS MB $theDiv = $theFileSize / 1000000; $theFileSize = round($theDiv, 1)." MB"; //round($WhatToRound, $DecimalPlaces) } else { //OTHERWISE DISPLAY AS KB $theDiv = $theFileSize / 1000; $theFileSize = round($theDiv, 1)." KB"; //round($WhatToRound, $DecimalPlaces) } } else { $msgToUser = '<br /><br /><font color="#FF0000">Ooops something went wrong.</font><p><a href="../index.php">Go Back</a></p>'; include_once 'msgToUser.php'; $errors=1; } } } $name = strip_tags($name, ''); $message = strip_tags($message, ''); $sql = mysql_query("INSERT INTO bulletin_board (posting_date, member_id, title, subject, picture, document) VALUES(now(),'$logOptions_id', '$name','$message', '$image_name', '$theFileName')") or die (mysql_error()); Marco Hello,
I have the following upload script that actually worked until I tried to add file type specifications. I can't figure out what I did wrong. I have been piecing things together so there is no telling what is wrong. Help me please?
<?php $fileName = $_FILES["file1"]["name"]; // The file name $fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["file1"]["type"]; // The type of file it is $fileSize = $_FILES["file1"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true if (!$fileTmpLoc) { // if file not chosen echo "ERROR: Please browse for a file before clicking the upload button."; exit(); } if ($fileType=="image/png" || $fileType=="image/gif" || $fileType=="image/jpg") // checking file type echo "ERROR: Only file types .png, .gif or .jpg may be uploaded"; exit(); } if(move_uploaded_file($fileTmpLoc, "image_uploads/$fileName")){ echo "$fileName upload is complete"; } else { echo "move_uploaded_file function failed"; } ?>Thanks. hello everyone....i am new for this script, hope u guys able to help me. Thank you in advance! im using xampp for localhost, all .php file i place it in xampp\htdocs ( i create a uploads folder outside the htdocs, c:\xampp\uploads) This is the error message i get after i upload the file: Notice: Undefined variable: FILES in C:\xampp\htdocs\upload_file.php on line 15 Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\xampp\htdocs\upload_file.php on line 15 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\xampp\tmp\phpAE.tmp' to '../uploads/' in C:\xampp\htdocs\upload_file.php on line 15 Your file could not be uploaded because: Something unforeseen happened.. following is my upload_file.php script , i highlighted on line 15: <!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>Upload a File</title> </head> <body> <?php ///Script - 11.4 - upload_file.php /* This script displays and handles an HTML form. this script takes a file upload and stored it on the servers */ if(isset($_POST['submitted'])) { //Handle the form //Try to move the upload file: if (move_uploaded_file ($_FILES['thefile']['tmp_name'],"../uploads/{$FILES['thefile']['name']}")){ print '<p>Your file has been uploaded.</p>'; }else { //problem!! print '<p style="color:red;">Your file could not be uploaded because: '; ///print a message based upon the error: switch ($_FILES['thefile']['error']) { case 1: print 'The file exceeds the upload_max_filesize setting in php.ini'; break; case 2: print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form'; break; case 3: print 'The file was only partially uploaded'; break; case 4: print 'No file was uploaded'; break; case 6: print 'The temporary folder does not exist.'; break; default: print 'Something unforeseen happened.'; break; } print '.</p>'; /////complete the paragraph. } // End of move_uploaded_file()IF } // End of submission IF //Leave PHP and display the form: ?> <form action="upload_file.php" enctype="multipart/form-data" method="post"> <p>Upload a file using this form:</p> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> <p><input type="file" name="thefile" /></p> <p><input type="submit" name="submit" value="Upload This File" /></p> <input type="hidden" name="submitted" value="true" /> </form> </body> </html> Hi, I can't believe after more then a year I'm stuck with the simplest upload script. Here's my code: <?php if( isset($_POST['upload']) ){ $uploaddir = "uploads/"; $uploadfile = $uploaddir.$_FILES['fileupload']['name']; if( move_uploaded_file($_FILES['fileupload']['tmp_name'], $uploadfile) ){ echo "Upload OK!"; }else{ echo "Upload FAILED!!!"; } }else{ ?> <form action="<?php $_SERVER['PHP_SELF'] ?>" name="upload" method="post"> <input type="file" name="fileupload" /> <input type="submit" name="upload" value="upload" /> </form> <?php } ?> this is the simplest php upload script that you can find, though the least secure one (it's for a local pc project). When I try to upload any file it gets to my else statement. Anyone an idea why? I don't see it Thanks! I have this code where I add records: Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check for a name: if (empty($_POST['product'])) { $add_cat_errors['product'] = 'Please enter the name!'; } // Check for a description: if (empty($_POST['prod_descr'])) { $add_cat_errors['prod_descr'] = 'Please enter the description!'; } // Check for a category: if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['cat'] = 'Please select a category!'; } // Check for a price: if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) { $add_cat_errors['price'] = 'Please enter a valid price!'; } // Check for a category: if (!isset($_POST['directory']) || !filter_var($_POST['directory'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['directory'] = 'Please select a directory!'; } // Check for an image: if (is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) { $file = $_FILES['image']; $size = ROUND($file['size']/1024); // Validate the file size: if ($size > 512) { $add_cat_errors['image'] = 'The uploaded file was too large.'; } // Validate the file type: $allowed_mime = array ('image/jpeg', 'image/JPG', 'image/jpg'); $allowed_extensions = array ('.jpg', 'jpeg'); $image_info = getimagesize($file['tmp_name']); $ext = substr($file['name'], -4); if ( (!in_array($file['type'], $allowed_mime)) || (!in_array($image_info['mime'], $allowed_mime) ) || (!in_array($ext, $allowed_extensions) ) ) { $add_cat_errors['image'] = 'The uploaded file was not of the proper type.'; } // Move the file over, if no problems: if (!array_key_exists('image', $add_cat_errors)) { // Create a new name for the file: $new_name = (string) sha1($file['name'] . uniqid('',true)); // Add the extension: $new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext); //$new_name = $dir . '/' . $new_name; $dest = "../db/images/$new_name"; // Move the file to its proper folder but add _tmp, just in case: //$dest = "../db/images/$new_name"; $dirs = array('full_heads', 'human_hair', 'lip_tattoos', 'ponytails', 'synthetic_hair'); if (move_uploaded_file($file['tmp_name'], $dest)) { // Store the data in the session for later use: $_SESSION['image']['new_name'] = $new_name; $_SESSION['image']['file_name'] = $file['name']; // Print a message: echo '<h4>The file has been uploaded!</h4>'; } else { trigger_error('The file could not be moved.'); unlink ($file['tmp_name']); } } // End of array_key_exists() IF. } elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file. switch ($_FILES['image']['error']) { case 1: case 2: $add_cat_errors['image'] = 'The uploaded file was too large.'; break; case 3: $add_cat_errors['image'] = 'The file was only partially uploaded.'; break; case 6: case 7: case 8: $add_cat_errors['image'] = 'The file could not be uploaded due to a system error.'; break; case 4: default: $add_cat_errors['image'] = 'No file was uploaded.'; break; } // End of SWITCH. } // End of $_FILES IF-ELSEIF-ELSE. // Check for a stock: if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['stock'] = 'Please enter the quantity in stock!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, dirID, image, stock) VALUES (?, ?, ?, ?, ?, ?, ?)"; // Prepare the statement: $stmt = mysqli_prepare($dbc, $query); // For debugging purposes: // if (!$stmt) echo mysqli_stmt_error($stmt); // Bind the variables: mysqli_stmt_bind_param($stmt, 'ssssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_POST['directory'], $_SESSION['image']['new_name'], $_POST['stock']); // Make the extra variable associations: $name = strip_tags($_POST['product']); $desc = strip_tags($_POST['prod_descr']); // Execute the query: mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK. // Print a message: echo '<h4>The product has been added!</h4>'; // Clear $_POST: $_POST = array(); // Clear $_FILES: $_FILES = array(); // Clear $file and $_SESSION['image']: unset($file, $_SESSION['image']); } else { // If it did not run OK. trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.'); unlink ($dest); } } // End of $errors IF. } else { // Clear out the session on a GET request: unset($_SESSION['image']); } // End of the submission IF. require_once ('./includes/form_functions.inc.php'); ?> <form enctype="multipart/form-data" action="add_product.php" method="post" accept-charset="utf-8"> <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?> Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?> Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT catID, cat FROM category ORDER BY cat ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_cat_errors['cat']; ?> Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?> Directory<br /><select name="directory"<?php if (array_key_exists('directory', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT dirID, directory FROM directory ORDER BY directory ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['directory']) && ($_POST['directory'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('directory', $add_cat_errors)) echo $add_cat_errors['directory']; ?> </select> Image<br /><?php // Check for an error: if (array_key_exists('image', $add_cat_errors)) { echo $add_cat_errors['image'] . '<br /><input type="file" name="image"/>'; } else { // No error. echo '<input type="file" name="image" />'; // If the file exists (from a previous form submission but there were other errors), // store the file info in a session and note its existence: if (isset($_SESSION['image'])) { echo "<br />Currently '{$_SESSION['image']['file_name']}'"; } } // end of errors IF-ELSE. ?> <br /> Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?> <input type="submit" value="Add This Product" class="button" /> </fieldset> </form> What I want to achieve is this; When a record is being inserted, a user will make a selection from the dropdown box with a list of directories. Then, a user will upload an image. When a image is uploaded and a directory is chosen, I want the image to be assigned to a specific directory from the list so when the record is inserted, that image will be placed in the specific directory. How do I achieve this please? Hi Guys, I'm having a problem with some file upload code I wrote and I was wondering if you could help me figure out why it's not working?? Here it is; Code: [Select] if($_POST['photo'] == "") $photo_update = "images/item_pictures/default_item.png"; else { if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 200000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] ."<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; //Check image doesn't exist in first folder then uploads if doesn't. if (file_exists("images/item_pictures/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "images/item_pictures/" . $_FILES["file"]["name"]); echo "Stored in: " . "images/item_pictures/" . $_FILES["file"]["name"]; } //Check image doesn't exist in second*admin*folder then uploads if doesn't. if (file_exists("admin/images/item_pictures/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "admin/images/item_pictures/" . $_FILES["file"]["name"]); $photo_update = "admin/images/item_pictures/" . $_FILES["file"]["name"]; echo "Stored in: " . $uploaded_file; } } } else { echo "Invalid file"; } } Thanks in advance Jacbey I'm trying to upload a file using ajax, but I have some problems. First I'll show the code : HTML Code: [Select] <form id="foto" action="index.php?action=send" method="post" enctype="multipart/form-data"> <fieldset> <label>Kleur</label> <input id="Binded" type="text" value="ffffff" /> <br /> <label>Upload foto</label> <input id="file" type="file" name="upload" id="upload"/> <a href="index.php?action=foto" id="uploaden">uploaden</a> </fieldset> <fieldset id="audioplayer"> <h3>Kies een soundtrack</h3> <ol id="lijst"> <li id="een" class="active"><a href="assets/audio/Gayla_Peevey-I_Want_a_Hippopotamus_For_Christmas.mp3">Gayla Peevey - I Want a Hippopotamus For Christmas</a> <img class="mute" src="assets/images/mute.png" width="30" height="30" alt="mute"/></li> <li id="twee"><a href="assets/audio/SouthFamilyXmas2005-NuttinForChristmas.mp3">South Family - Nuttin for Christmas</a> <img class="mute" src="assets/images/mute.png" width="30" height="30" alt="mute"/></li> <li id="drie"><a href="assets/audio/southpark_merry_christmas.mp3">South Park - Merry Christmas</a> <img class="mute" src="assets/images/mute.png" width="30" height="30" alt="mute"/></li> </li> </ol> <audio id="audio" preload="auto" autobuffer autoplay src="assets/audio/Gayla Peevey - I Want a Hippopotamus For Christmas.mp3"> </audio> </fieldset> <fieldset id="emailen"> <h3>Email een vriend</h3> <br /> <input type="email" name="email" placeholder="Email" required="true" /> <input type="submit" name="verstuur" id="verstuur" value="Verstuur" /> </fieldset> </form> PHP Code: [Select] function getAjaxContent(){ global $smarty; $dir = "uploads"; $tempdir = $_FILES['upload']["tmp_name"]; $realdir = $dir."/".$_FILES["upload"]["name"]; //$fotoTonen = '<img src="'.$realdir.'" alt="foto upload">'; //$toonFoto = true; if(!is_dir($dir)){ mkdir($dir); } move_uploaded_file($tempdir, $realdir); var_dump($_FILES); return $smarty->fetch('kaart-ajax.htm'); }Here I get the error <b>Notice</b>: Undefined index: upload in <b>/Applications/MAMP/htdocs/2011-2012/kerstkaart/includes/index.php</b> on line <b>16</b><br /> and the var_dump gives an empty array AJAX Code: [Select] $('input[name=foto]').change(function(event){ $.ajax({ url:"index.php?action=foto", data: $('input[type=file]').val(), type: "POST", timeout: 3000, error: function(jqXHR, textStatus,errorThrown){ alert("probleem met ajax "+textStatus); }, success: function(data, textStatus, jqXHR){ alert("jaja "+data); canvas.width = canvas.width; context.drawImage(image, 0, 0); image.src = 'uploads/'+data; } }); event.preventDefault(); }); What I try to do here is getting the value of the selected file and redraw my canvas ( HTML5 ) so that the chosen pic is the background. The file i upload to test is a gif of 4KB, so not that big. Can anyone help me with this confusing problem ? Thanks, where is the problem? http://pastebin.com/Smw92nd5 I'm looking for the folder where the uploaded file should be but it doesn't exist, it seems that the condition "if($ext == $need)" is ignored |