PHP - Simple Php-mysql Upload Script
Hey guys! I'm not that good with PHP, and I really need to finish this script. I'm having a hard time finding the problem..it keeps saying Error, query failed and I've also checked the database info, connectivity info and even tried a connection and database selection verification to see if that was working. Is there any other error you guys can find in the script that may be causing the message?
Edit: The files I want to be able to upload should be pdf's, txts, docs, etc. Would that be possible with this script? Thanks!! Code: [Select] <form method="post" enctype="multipart/form-data"> <table width="350" border="0" cellpadding="1" cellspacing="1" class="box"> <tr> <td width="246"> <input type="hidden" name="MAX_FILE_SIZE" value="104857600"></td> <td width="80"> </td> </tr> </table> <p>Archivo: <input name="userfile" type="file" id="userfile" /> </p> <p>Nomb <label for="name"></label> <input type="text" name="nombrelista" id="nombrelista" /> </p> <p>Password (para luego borrar si necesario): <input type="text" name="pass" id="pass" /> </p> <p> <input name="upload" type="submit" class="box" id="upload" value=" Upload " /> </p> <?php if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $filePass = $_POST['pass']; $nombreLista = $_POST['nombrelista']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); $host_db = "localhost"; $user_db = "melkien_rudesa"; $pass_db = "jorlan2407"; $base_db = "melkien_rudesa"; $link = mysql_connect($host_db, $user_db, $pass_db); if (!$link) { die('Could not connect: ' . mysql_error()); mysql_close($link); } mysql_select_db($base_db, $link) or die(mysql_error()); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $query = "INSERT INTO 'upload'('nombrelista', 'name', 'pass', 'size', 'type', 'content' ) VALUES ('$nombreLista', $fileName', '$filePass', $fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); echo "<br>File $fileName uploaded<br>"; mysql_close($link); } ?> </form> Similar Tutorialsso what i have going on is that i need help writing a basic script to upload original and copy with resize for thumbnail. then also need to rename both image files with content in the form. My server supports GD Library and that imagemagik or whatever it is lol. upload dirs orig: ../media/photos/ thumb: ../media/photos/thumb/ mySQL DB: name: m_photos fields: id(INT) m_cat(varchar) m_sub_cat(varchar) pic(varchar) description(varchar) p_group(varchar) I have the form written up for how it should look like: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> Upload an image for processing<br /> <input type="file" name="Image"><br /> <select name="sub_group"> <option value="Photo Shoot">Photo Shoot</option> <option value="Live Performances">Live Performances</option> <option value="Randoms">Randoms</option> <option value="Fan Photos">Fan Photos</option> </select><br /> Location: <input type="text" name="p_group" /><br /> Date of Pic: <input type="text" name="date" /><br /> Description: <input type="text" name="description" /><br /> <input type="submit" value="Upload"> </form> so what needs to happen is for the file upload name. it needs to grab a count from "p_group" database to give it a starting number in a "00" pattern and then the date of pic needs to go in there next then the p_group name. so when the files gets uploaded it would look something like this after upload. "03 - Oct 21, 2011 - The Mex.jpg" NOTE: all pics must be converted to ".jpg" extension. both the orig and thumb will use that same file name cuz they just go into different dirs re-sizing for the thumbnail should be done by aspect ratio and needs to either be 300px width or 400px height. so if anyone would like to help me out please do. im not the greatest at writing in php yet Hello. i am writing an API for lua... that sends POST requests to a php script. this php script is malfunctioning. below is the code and error. Hello, I am trying to pick up php again and just exercising my skills. So I have it so that it fills my form with the values of what I want to edit, and when I click the edit button, it doesn't edit any of the information. When I echo out $result, I get a MYSQL query string that has the same values as the table, so its not getting the new values that are edited. <?php @mysql_connect('localhost', 'root', '') or die("Could not connect to Mysql Server. " . mysql_error()); @mysql_select_db('tutorials') or die("Could not connect to Database. " . mysql_error()); if(isset($_GET['edit'])) { $id = $_GET['edit']; $query = "SELECT `username`, `password` FROM `users` WHERE `id` = '$id'"; $result = mysql_query($query); $row = mysql_fetch_array($result); $name = $row['username']; $password = $row['password']; } if(isset($_POST['edit'])) { $id = $_GET['edit']; $query = "UPDATE `users` SET `username` = '$name', `password` = '$password' WHERE `id` = '$id'"; $result = mysql_query($query); echo $query; if(!$result) { echo mysql_error(); }else{ echo 'updated post'; } } ?> <form method="POST" action="" > <input type="text" name="name" value="<?php echo $name; ?>" /> First name <br /> <input type="text" name="password" value="<?php echo $password; ?>" /> Last name <br /> <input type="submit" name="edit" value="edit" /> </form> I believe it has something to do with the values of $name and $password in the form conflicting with the first if isset and the second if isset. Thanks for any help possible Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks Hi i have a simple triple upload file script that upload files with its own name it works fine but what i want is to be able to specify the name of the image like file 1 give name (blue) file 2 name (tree) file 3 name (sky) <?php //set where you want to store files //in this example we keep file in folder upload //$HTTP_POST_FILES['ufile']['name']; = upload file name //for example upload file name cartoon.gif . $path will be upload/cartoon.gif $path1= "images/posters/".$_FILES['ufile']['name'][0]; $path2= "images/posters/".$_FILES['ufile']['name'][1]; $path3= "images/posters/".$_FILES['ufile']['name'][2]; //copy file to where you want to store file copy($_FILES['ufile']['tmp_name'][0], $path1); copy($_FILES['ufile']['tmp_name'][1], $path2); copy($_FILES['ufile']['tmp_name'][2], $path3); //$HTTP_POST_FILES['ufile']['name'] = file name //$HTTP_POST_FILES['ufile']['size'] = file size //$HTTP_POST_FILES['ufile']['type'] = type of file echo "File Name :".$_FILES['ufile']['name'][0]."<BR/>"; echo "File Size :".$_FILES['ufile']['size'][0]."<BR/>"; echo "File Type :".$_FILES['ufile']['type'][0]."<BR/>"; echo "<img src=\"$path1\" width=\"150\" height=\"150\">"; echo "<P>"; echo "File Name :".$_FILES['ufile']['name'][1]."<BR/>"; echo "File Size :".$_FILES['ufile']['size'][1]."<BR/>"; echo "File Type :".$_FILES['ufile']['type'][1]."<BR/>"; echo "<img src=\"$path2\" width=\"150\" height=\"150\">"; echo "<P>"; echo "File Name :".$_FILES['ufile']['name'][2]."<BR/>"; echo "File Size :".$_FILES['ufile']['size'][2]."<BR/>"; echo "File Type :".$_FILES['ufile']['type'][2]."<BR/>"; echo "<img src=\"$path3\" width=\"150\" height=\"150\">"; /////////////////////////////////////////////////////// // Use this code to display the error or success. $filesize1=$_FILES['ufile']['size'][0]; $filesize2=$_FILES['ufile']['size'][1]; $filesize3=$_FILES['ufile']['size'][2]; if($filesize1 && $filesize2 && $filesize3 != 0) { echo "We have recieved your files"; } else { echo "ERROR....."; } ////////////////////////////////////////////// // What files that have a problem? (if found) if($filesize1==0) { echo "There're something error in your first file"; echo "<BR />"; } if($filesize2==0) { echo "There're something error in your second file"; echo "<BR />"; } if($filesize3==0) { echo "There're something error in your third file"; echo "<BR />"; } ?> I am using cakephp and i need a quick simple image upload and re-size script, can any one help? Hello Friends, I was trying a simple file upload program But it's giving me notice. Heres the HTML & PHP Code. Code: [Select] <html> <body> <form enctype="multipart/form-data" action="uploadFile.php"method="POST"> Select A File: <input type="file" name=uploadedFile"/> <input type="hidden" name="MAX_FILE_SIZE" value="100000"/> <input type="Submit" value="Upload File"/> </form> </body> </html> Code: [Select] <?php $target_path="uploads/"; $target_path=$target_path.basename($_FILES['uploadedFile']['name']); if(move_uploaded_file($_FILES['uploadedFile']['tmp_name'],$target_path)) { echo "The file ".$_FILES['uploadedFile']['name']." is uploaded successfully"; } else { echo "Error uploading file"; } ?> I get the following notice: Notice: Undefined index: uploadedFile in C:\wamp\www\site\html\uploadFile.php on line 3 Notice: Undefined index: uploadedFile in C:\wamp\www\site\html\uploadFile.php on line 5 Error uploading file I cross checked the name of input tag its fine. any help will be highly appreciated! Hello, im very green to php and I am having trouble creating a simple log in script. Not sure why this is not working, maybe a mysql_query mistake? I am not receiving any errors but nothing gets updated in the members table and my error message to the user displays. any help is appreciated! here is my php: <?php session_start(); $errorMsg = ''; $email = ''; $pass = ''; if (isset($_POST['email'])) { $email = ($_POST['email']); $pass = ($_POST['password']); $email = stripslashes($email); $pass = stripslashes($pass); $email = strip_tags($email); $pass = strip_tags($pass); if ((!$email) || (!$pass)) { $errorMsg = '<font color="#FF0000">Please fill in both fields</font>'; }else { include 'scripts/connect_db.php'; $email = mysql_real_escape_string ($email); $pass = md5($pass); $sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$pass'"); $log_check = mysql_num_rows($sql); if ($log_check > 0) { while($row = mysql_fetch_array($sql)) { $id = $row["id"]; $_SESSION['id']; $email = $row["email"]; $_SESSION['email']; $username = $row["username"]; $_session['username']; mysql_query("UPDATE members SET last_logged=now() WHERE id='$id' LIMIT 1"); }//Close while loop echo "You are logged in"; exit(); } else { $errorMsg = '<font color="#FF0000">Incorrect login data, please try again</font>'; } } } ?> and the form: <?php echo $errorMsg; ?> <form action="log_in.php" method="post"> Email:<br /> <input name="email" type="text" /><br /><br /> Password:<br /> <input name="password" type="password" /><br /><br /> <input name="myBtn" type="submit" value="Log In" /> </form> Hi Guys I'm trying to get clients to: 1. upload an image 2. fill out details 3. submit image and details to me via email 1. Uploading the image is fine, they choose it and it displays on the next page 2. They fill in form details 3. then click submit to send to me - I get all details except the image How do I keep the image variable around to insert it into the details form and email it? The image appears to be displayed on the second page, then the variable disappears (is deleted) and isn't available in step 3 to submit as part of the email. I'm sure it's a simple fix - I'm pretty new with php and I've started kicking things so I thought it was time to ask for help. Upload-image-code <?php if($_FILES) { $img = $_FILES['filename']['img']; switch($_FILES['filename']['type']) { case 'image/jpeg' : $ext = 'jpg'; break; case 'image/png' : $ext = 'png'; break; default: $ext = ''; break; } if ($ext) { $n = "image.$ext"; move_uploaded_file($_FILES['filename']['tmp_name'], $n); echo "<span class='uploaded-photo'>uploaded image '$img' as '$n':</span> <br />"; echo "<img src='$n' />"; } else echo "'$img' is not a supported image file"; } //else echo "<span class='uploaded-photo'>No image has been uploaded</span>"; ?> $n is available to be displayed on page 2 and it works Page 2 contains the rest of the form, but when I submit the form $n isn't available to be sent with the other data (i have tried REQUEST $img as well. Submit form code <?php $name = $_REQUEST['name'] ; $email = $_REQUEST['email'] ; $phone = $_REQUEST['phone'] ; $address = $_REQUEST['address'] ; $pname = $_REQUEST['pname'] ; $pdescription = $_REQUEST['pdescription']; $plow = $_REQUEST['plow'] ; $phigh = $_REQUEST['phigh'] ; $purl = $_REQUEST['purl'] ; $ponline = $_REQUEST['ponline'] ; $n = $_REQUEST['n']; $img = $_REQUEST['img']; if (!isset($_REQUEST['email'])) { echo "we need your name and email address please" ; } elseif (empty($name)){ echo "please enter your name"; } elseif (empty($email)){ echo "please enter your email address"; } elseif (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})", "$email")) { echo"please check your email address - it doesn't appear to be a valid format"; } else { mail( "eamail@address.com", "Subject", "$name\n $email\n $phone\n $address\n $pname\n $pdescription\n $plow\n $phigh\n $purl\n $ponline\n $n\n $img", "$email"); header( "Location: ../index.php" ); } ?> Would really appreciate any help - if you need full code please let me know. Thanks @webecho I currently have the following script used on my site to upload files. When the linked web page executes it, however, I receive the infamous Parse Error - Unexpected '<' in x:/xxxx. The problem lies in Line 11 where I attempt to define a command that will display a message box to the user upon successful file upload. The syntax is not correct and I was hoping someone would be able to help me with it. Here is the contents of the PHP file. <?php // Where the file is going to be placed $target_path = $_SERVER['DOCUMENT_ROOT'] . "/file_uploads/"; /*Add the original filename to our target path. Result is "uploads/filename.extension"*/ $target_path=$target_path.basename($_FILES['file']['name']); //Move file to upload directory if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { echo <script type="text/javascript">alert("Upload was successful. Thank you for your contribution")</script>; } else{ echo "There was a problem submitting the file. Plese try again!"; } ?> Thank you in advance for any help. Hi i have found this code : <?php if (isset($_POST['submit_bilde'])) { $error = 'Wrong image file..'; define( 'THUMBNAIL_IMAGE_MAX_WIDTH', 250 ); define( 'THUMBNAIL_IMAGE_MAX_HEIGHT', 250 ); function generate_image_thumbnail( $source_image_path, $thumbnail_image_path ) { list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $source_image_path ); switch ( $source_image_type ) { case IMAGETYPE_GIF: $source_gd_image = imagecreatefromgif( $source_image_path ); break; case IMAGETYPE_JPEG: $source_gd_image = imagecreatefromjpeg( $source_image_path ); break; case IMAGETYPE_PNG: $source_gd_image = imagecreatefrompng( $source_image_path ); break; } if ( $source_gd_image === false ) { return false; } $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH; $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT; $source_aspect_ratio = $source_image_width / $source_image_height; $thumbnail_aspect_ratio = $thumbnail_image_width / $thumbnail_image_height; if ( $source_image_width <= $thumbnail_image_width && $source_image_height <= $thumbnail_image_height ) { $thumbnail_image_width = $source_image_width; $thumbnail_image_height = $source_image_height; } elseif ( $thumbnail_aspect_ratio > $source_aspect_ratio ) { $thumbnail_image_width = ( int ) ( $thumbnail_image_height * $source_aspect_ratio ); } else { $thumbnail_image_height = ( int ) ( $thumbnail_image_width / $source_aspect_ratio ); } $thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height ); imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height ); imagejpeg( $thumbnail_gd_image, $thumbnail_image_path, 100 ); imagedestroy( $source_gd_image ); imagedestroy( $thumbnail_gd_image ); return true; } define( 'UPLOADED_IMAGE_DESTINATION', 'annonsebilder/orginaler/' ); define( 'THUMBNAIL_IMAGE_DESTINATION', 'annonsebilder/thumbs/' ); function process_image_upload( $field ) { $temp_image_path = $_FILES[ $field ][ 'tmp_name' ]; $temp_image_name = $_FILES[ $field ][ 'name' ]; list( , , $temp_image_type ) = getimagesize( $temp_image_path ); if ( $temp_image_type === NULL ) { return false; } switch ( $temp_image_type ) { case IMAGETYPE_JPEG: break; default: return false; } $uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name; move_uploaded_file( $temp_image_path, $uploaded_image_path ); $random_digit=rand(0000000000000,9999999999999); $thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace( '{\\.[^\\.]+$}', '.jpg', $annonse_ref.'_'.$random_digit.'.jpg' ); $result = generate_image_thumbnail( $uploaded_image_path, $thumbnail_image_path ); return $result ? array( $uploaded_image_path, $thumbnail_image_path ) : false; } for ( $i = 1; $i <= 5; $i++ ) { if ( $_FILES[ 'Image' . $i ][ 'error' ] == 0 ) { $result = process_image_upload( 'Image' . $i ); } } if ( $result === false ) { echo $error; } else { //THIS ECHO SHIT IS KILLIN' ME!!! echo '<br />1: '.$result['1'] ; echo '<br />2: '.$result['2']; echo '<br />3: '.$result['3']; echo '<br />4: '.$result['4']; echo '<br />5: '.$result['5']; } } if (!isset($_POST['submit_bilde'])) { ?> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="Image1"><br> <input type="file" name="Image2"><br> <input type="file" name="Image3"><br> <input type="file" name="Image4"><br> <input type="file" name="Image5"><br><br> <input type="submit" value="GOOOOOOOO!!!!" name="submit_bilde"> </form> <?}?> and if you look in the code there is a part where i want to echo the uploaded files' path's.. I only se one of those 5 files listet in the "echo"-thing :p Can someone please, please, please help me to echo ALL the 5 images path?? Hi can someone pls help, im tryin a tutorial but keep getting errors, this is the first one i get after registering. You Are Registered And Can Now Login Warning: Cannot modify header information - headers already sent by (output started at /home/aretheyh/public_html/nealeweb.com/regcheck.php:43) in /home/aretheyh/public_html/nealeweb.com/regcheck.php on line 46 Code: [Select] <?php // Maximum file size for upload $maxFileSize = 5242880; // If file is too large if(!empty($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $maxFileSize) echo "File too large"; else { if(isset($_POST['submit'])) { // List of acceptable file types $whitelist = array( "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx "application/msword", // .doc, .rtf "text/plain", "image/jpeg", "image/gif", "image/png", "application/pdf", "application/octet-stream", // .rar "application/x-zip" // .zip ); // Is uploaded file type in whitelist array if(!in_array($_FILES['file_upload']['type'], $whitelist)) exit("Bad Filetype"); // Don't allow php files if(preg_match("/\.php.*$/i", $_FILES['file_upload']['name'])) exit("We do not allow uploading PHP files\n"); // Move the file $uploaddir = '../uploads/'; $uploadfile = $uploaddir . "[" . time(). "]." . basename($_FILES['file_upload']['name']); if (move_uploaded_file($_FILES['file_upload']['tmp_name'], $uploadfile)) exit("File is valid, and was successfully uploaded.\n"); else exit("File uploading failed.\n"); } } ?> <html> <head> <title>Upload Test</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $maxFileSize; ?>" /> <input type="file" name="file_upload" /> <input type="submit" name="submit" value="upload" /> <br /> <?php echo "(Max: " . number_format($maxFileSize/1048576,0) . " MB)" ?> </form> </body> </html> Hi All Not so much help as here is a handy class for uploading images Please feel free to find security bugs and let me know. Also feel free to use it if you want. http://onlyican.com/test_samples/bl_upload_img.phps To use the class, simply use the following require_once('bl_upload_img.php'); $objUploadImg = new UploadImg(); //Set values here if you wish such as $objUploadImg->setFormField('myFormField'); // The Name from <input type="file" name="myFormField" /> $objUploadImg->setSaveDirMain($_SERVER['DOCUMENT_ROOT'].'/MyImageFolder'; //Make sure to set the permissions //You can change most settings, just look at the function setDetaultValues() to get the function name //Now upload the image if($objUploadImg->uploadImage()){ $strFileName = $objUploadImg->getFileNameMain(); }else{ echo 'Error uploading Image<br />'.$objUploadImg->getErrorMessage(); } hello i am adding an image upload script, so users can upload a image with the recipe they are adding, but my script seems to not work, these are the files. add_recipe.php <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta name="Description" content="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form enctype="multipart/form-data" action="include/recipe.php" method="post"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"></th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="prep" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="cook" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> Choose a picture to upload: <input name="uploaded_file" type="file" /></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> <tr> <td> </td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipe.php (upload form script) <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; mysql_real_escape_string($user); //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); $uploaded_file=$_POST['files']['uploaded_file'] //Сheck that we have a file if ((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 350000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/upload/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "It's done! The file has been saved as: ".$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 350Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } header("Location: ../recipe_added.php"); //} ?> Hi everyone. I have been looking for a PHP upload script that handles various different document types like PDF, DOC and XLS. So far all I have found is image upload scripts. Can anyone point me in the right direction? I would be most greatful. Thank you! Hey guys!! i'm after a bit of help with a script i am using for simple image upload to server. At the moment the script works fine and will allow upload of JPG files, i want to extend on this to allow GIF and PNG files to be uploaded aswell. This is the script i am using... <?php //?heck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 600Kb $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 600000)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! You can use the following link in the IMS:" .$newname; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: Only .jpg images under 600Kb are accepted for upload"; } } else { echo "Error: No file uploaded"; } // $sessionid=session_id() //$newname=$_SESSION['session_name'] header( 'Location: success.php?newname1='.$filename ) ; ?> Any help would be appriciated!! ta!! jonny hey guys im trying to make a file upload script so that when the user uploads a pic it gets shown in a div...when you add another it is the added by the side of the 1st pic...but some reason when selecting a image nothing shows...
what am i doing wrong?
here is my code below if anyone can tell me what it is wrong im doing...thank you
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script> $( document ).ready(function() { var files = $('.input-file').prop("files"); var file_count = files.length; var names = $.map(files, function(val) { return val.name; }); $('#input-file-button').click(function() { $('.input-file').click(); }); $('.input-file').change(function (){ var file_name = $(this).val(); var file_path = URL.createObjectURL(event.target.files[0]); $('#uploaded-images').append('<div><img src="'+ file_path +'" /></div>' + file_name); }); if (file_count < 1) { $('#uploaded-images').text("No images are selected."); } }); </script> <style> .input-file { display: none; } </style> </head> <body> <div id="uploaded-images"></div> <br /> <input type="file" name="files[]" class="input-file"/><span id='input-file-button'>Upload Photo</span> </body> </html> Hello, I'm planning on making a website where people are able to upload files and directly link to them. Ideally, I want to keep the same file names that the people use when they upload the file. I was planning on keeping the directory that stored all of the files outside of the www directory and disable execute permissions. However, how would I avoid file overwriting with the same file name? |