PHP - Upload File Using Form And Add Path And Other Details To Database.
Hi,
I have a form that allows a user to enter details and also to upload a image. The form works great and inserts into the database if i dont include the file input. What i would like happen is: The user enters details and selects a file The file then gets uploaded to ../images and the path is then written to bedroom1 variable The addresses and the bedroom1 variable that now holds the uploaded file path e.g. images/test.jpg is written to the database Form Code: [Select] <form action="admin.php" method="POST"> <table> <tr><td> Address 1: </td><td> <input type="text" name="address1" id="address1" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> Address 2: </td><td> <input type="text" name="address2" id="address2" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> County: </td><td> <input type="text" name="county" id="county" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> Bedroom 1: </td><td> <input type="file" name="bedroom1" id="bedroom1" input name="uploadedfile"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> <input type="submit" name="submitaddapartment" value="Add" id="registerbutton"> </td></tr> </table </form> And the php code to add it to the database Code: [Select] <?php //get variables $submitaddapartment = $_POST['submitaddapartment']; $address1 = strip_tags($_POST['address1']); $address2 = strip_tags($_POST['address2']); $county = strip_tags($_POST['county']); $bedroom1 = strip_tags($_POST['bedroom1']); if ($submitaddapartment) //if submit button was pressed { if ($address1&&$address2&&$county&&$bedroom1&&) //if fields arn't blank { include 'dbase.php'; //connect to database if ((($_FILES["bedroom1"]["type"] == "image/gif") || ($_FILES["bedroom1"]["type"] == "image/jpg") || ($_FILES["bedroom1"]["type"] == "image/pjpeg")) && ($_FILES["bedroom1"]["size"] < 20000000)) { if ($_FILES["bedroom1"]["error"] > 0) { echo "Return Code: " . $_FILES["bedroom1"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["bedroom1"]["name"] . "<br />"; echo "Type: " . $_FILES["bedroom1"]["type"] . "<br />"; echo "Size: " . ($_FILES["bedroom1"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["bedroom1"]["tmp_name"] . "<br />"; if (file_exists("../images/" . $_FILES["bedroom1"]["name"])) { echo $_FILES["bedroom1"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["bedroom1"]["tmp_name"], "/" . $_FILES["bedroom1"]["name"]); echo "Stored in: " . "../images/" . $_FILES["bedroom1"]["name"]; $bedroom1=".'images/.' $_FILES["bedroom1"]["name"]"; } } } else { echo "Invalid file"; } mysql_query ("INSERT INTO user VALUES(NULL,'$address1','$address2','$county','$bedroom1')"); } else { } } ?> Any help would be greatly appreciated. Thanks Fred Similar Tutorials<td><label for='images'> <b>File to upload:</b> </label></td> <td><input type='file' name = 'drama_image' '<?php echo $row['drama_image']; ?>'/></ </tr> <?php $target_path = "images/"; $target_path = $target_path . basename( $_FILES['images']['name']); if(move_uploaded_file($_FILES['images']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['images']['name']). " has been uploaded"; } else{ echo $row['drama_image']; } ?> ['drama_image'] is the name of the file I wanna echo it out in the box of file upload so when I save , the default picture will still be there instead of being overwritten as the box does not have any value in it. Hello freaks! Im new to this forum, but im not all that new to PHP and MySQL. Although there's been some years since the last time I used it, so don't go all freaky on me if I dont do this right Let's go on-topic: Im in progress of making an internal web-page for me and my colleagues to make things a bit easier for us. I am making an database of our different projects, and I need some help with the input form - as I need to upload an image to the server, and store the path in the MySQL database. In my input form, I need to store information from text fields, and I need to upload an image to the server and store the path in the database. Before I can even start to code this (although I have coded the input forum without the upload), I need to know what would be the best way to do this. I guess there are several ways.. What would the expert do (That's you right?)? Should I have the information input, and image upload in the same form, or should I make a second form (maybe on a different page) for the upload? Is it necessary with two tables, one for the info and one for the image path, and then tie them together with the imageID, or is it fine to use just one table? Any thoughts would be appreciated! <!-- TechThat --> Is there a way to get the source path for an uploaded file? It seems that's a function of the browser and the two I've tried FF and Safari don't return it in $_FILES['file']['name']. Hi Guys, I need help for in storing data from PHP from array in mysql. I'm very new to PHP/Mysql and have started learing it just few weeks back. I'm tryting to build a website for myself. I'm having tough time trying to insert the data from Form in mysql. I have a form where user update the company name and insert there product name with there image. I want to rename the image with the corresponding text field value and insert the upload path in the table. my FORM Code: [Select] <!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> <style type="text/css"> body,td,th { color: #000; font-family: Tahoma, Geneva, sans-serif; font-size: 80%; } body { background-color: #9CF; } table { background: #CCF; } th { font: bold normal 16px/normal "Times New Roman", Times, serif; text-transform: capitalize; color: #00F; background: #FFC; } td { font: bold 14px Georgia, "Times New Roman", Times, serif; text-transform: capitalize; color: #3A00FF; background: #FF9; } </style> </head> <body> <form action="upload-file1.php" method="post" enctype="multipart/form-data" name="form"> <strong>Company Name:</strong> <input name="product" type="text" /> <br /> <table> <tr bgcolor="#FF9900"> <th colspan="3" bgcolor="#CCFFFF">filter </th> <th colspan="5" bgcolor="#CCFFFF">heater</th> </tr> <tr><td>filter1</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater1: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter2</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater2: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter3</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater3: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter4</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater4: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> <tr><td>filter5</td><td><input name="filter[]" type="text" id="filter"/> <td><input name="img_filter[]" type="file" /></td><td>heater5: </td> <td><input name="heater[]" type="text" id="heater"/></td> <td><input name="img_heater[]" type="file" /></td> </tr> </table> <br /> <br /> <input name="submit" type="submit" value="submit" /> </form> </body> </html> my PHP Code Code: [Select] <?php require("connect.php"); ?> <?php $product = $_POST['product']; echo $product; if(isset($_POST["submit"])){ $sql = "INSERT INTO company (product) VALUES ('$product')"; $query = mysql_query($sql) OR DIE(mysql_error()); $comp_id = mysql_insert_id(); echo $sql; } ?> <?php function filter() { if(isset($_POST['submit'])) { foreach($_POST['filter'] as $key => $val) { if(trim($val) != '') $filter[] = $val; } $total_records_filter = count($filter); for($i = 0; $i < $total_records_filter; $i++) { $prod_val = $filter[$i]; $sql_prod = "INSERT INTO filter(filter_id, filter) VALUES('', '$prod_val')"; echo $sql_prod.'<br>'; mysql_query($sql_prod) OR die(mysql_error()); } } } filter(); function heater() { if(isset($_POST['submit'])) { foreach($_POST['heater'] as $key => $val) { if(trim($val) != '') $heater[] = $val; } $total_records_heater = count($heater); for($i = 0; $i < $total_records_heater; $i++) { $dir_val = $heater[$i]; $sql_dir = "INSERT INTO heater(heater_id, heater) VALUES('', '$dir_val')"; echo $sql_dir.'<br>'; mysql_query($sql_dir) OR die(mysql_error()); } } } heater(); ?> <?php mysql_close($link)?> My Table structure company comp_id int(5) PK product varchar(50) No filter filter_id int(5) PK filter varchar(25) No filter_path varchar(100) No heater heater_id int(5) PK heater varchar(25) No heater_path varchar(100) No company_filter id int(5) PK comp_id int(5) PK FK (From company table) filter_id int(5) PK FK (From filter table) company_heater id int(5) PK comp_id int(5) PK FK (From company table) heater_id int(5) PK FK (From heater table) Regards BW Hi All, I've searched long and hard accross the web for an answer to this and finnally given in and requesting help. Here's what i have, i have a database setup and working fine. What i would like to do is for an administrator to be able to update my users details. It may sound odd, why don't you let your users update their own details? Well the administrators are dispatchers if you like, and my users are the 'dispatchees', for want of a better word. So i would like my administrators to be able to dispatch my users with routes and my users be able to see the routes that have been dispatched to them. I've setup a login area and a page that pulls there routes off the database, depending on their login details, i.e. jack will see his routes and jill will see her's independantly. This works by me editing the appropriate columns/rows of my database using phpmyadmin. What i'd like now is for administrators (who are directed to a seperate page, with more controls) to be able to do the same as me (updating the database) but by using a php form/script. I'd like to be able to select the routes from a second table on the same database if possible, to try and keep everything tidy. So my dispatcher would select Route001 from a drop down list, this would fill in the text fields next to the route field with From To, so my dispatcher would know what route001 actually is from/ too, choose a username (now being driven from my other table) and hit dispatch. My user would login to their area, hit view dispatched routes and it would display Route 001 with the correct information. The login area was a downloaded script i modified to suit and is called Login-Redirect_v1.31_FULL Many thanks in advance, hope you can sort of understand what i want Josh PHP/MySQL ability:Novice hi- i'm trying to browse for a CSV file and then upload it to my mysql database. i found the code below and not working. i don't get any errors. the connection to the database is ok bcz i get the existing results but not the ones from the CSV file added to the db.. any ideas? Code: [Select] <?php ob_start(); require_once('../../connections/congif.php'); mysql_select_db($dbname, $db); $sql_get_project="SELECT * FROM gifts_tbl ORDER BY autoID DESC LIMIT 25"; $get_project = mysql_query($sql_get_project, $db) or die(mysql_error()); $row_get_project = mysql_fetch_assoc($get_project); //database connect info here //check for file upload if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){ //upload directory $upload_dir = "csv_dir/"; //create file name $file_path = $upload_dir . $_FILES['csv_file']['name']; //move uploaded file to upload dir if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) { //error moving upload file echo "Error moving file upload"; } //open the csv file for reading $handle = fopen($file_path, 'r'); //turn off autocommit and delete the product table mysql_query("BEGIN"); while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) { //Access field data in $data array ex. $name = $data[0]; //Use data to insert into db $sql = sprintf("INSERT INTO gifts_tbl (player_id) VALUES ('%s)", mysql_real_escape_string($name) ); mysql_query($sql) or (mysql_query("ROLLBACK") and die(mysql_error() . " - $sql")); } unlink($file_path); } ob_flush(); ?> <!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>Gifts</title> </head> <body> <h1>Testing for CSV upload</h1> <form action="" method="post"> <input type="file" name="csv_file"> <input type="submit" name="csv_submit" value="Upload CSV File"> </form> <h2>Results</h2> <?php do { ?> <ul> <li><?php echo $row_get_project['player_id']; ?></li> </ul> <?php } while ($row_get_project = mysql_fetch_assoc($get_project)); ?> </body> </html> i need to upload files to a different folder dependint on option in form, make thumbnails, and store title and src for image and thumb in database table dependant on category. i think i'm pretty close, but there's still something wrong. Here is my upload form : Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Photo: <input type="file" name="photo"><br> Category: <select name="cat"> <option value="weddings">Weddings</option> <option value="music">Music</option> <option value="portraits">Portraits</option></select> Title: <input type="text" name="title"><br> <input type="submit" value="Upload photo"> </form> form processed by upload.php : Code: [Select] <?php require "db.php"; //Get form info $name=$_POST['name']; $title=$_POST['title']; $category=$_POST['cat']; $pic=($_FILES['photo']['name']); //set target dir source file width height $target = $cat."/"; $src = $target . basename( $_FILES['photo']['name']); $destination = $cat."/thumbs"; $thumbsrc = $destination . basename( $_FILES['photo']['name']); $width = 200; $height = 200; header("content-type: image/jpeg"); $src_img = imagecreatefromjpeg("$src"); $srcsize = getimagesize("$dest"); $dst_img = imagecreatetruecolor($width, $height); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $srcsize[0], $srcsize[1]); imagejpeg($dst_img); //Unstert into db mysql_query("INSERT INTO `$category` VALUES ('$name', 'Stitle', '$src, $thumbsrc')") ; //move photo if(move_uploaded_file($_FILES['photo']['tmp_name'], $fulltarget)) { //Ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //not ok echo "Sorry, there was a problem uploading your file."; } ?> call a script from main page Code: [Select] <div class="gallery"> <?php include "weddings/get.php" ?> </div> <div class="gallery"> <?php include "music/get.php" ?> </div> get.php displays links Code: [Select] <?php include "db.php"; $cat = weddings; $q = "SELECT id, title, src, thumbsrc FROM $cat"; $result = $mysqli->query($q) or die(mysqli_error($mysqli)); if ($result) { echo "<ul id='photos'> \n"; while ($row = $result->fetch_object()) { $title = $row->title; $src = $row->src; $thsrc = $row->thumbsrc; $id = $row->id; echo "<a href='$src' class="lightbox" rel="$cat" title="$name - $title"><img src='$thsrc' id='$id' alt='$name' /></a>": } echo "</ul>"; } ?> I think i'm going along the right sort of path, but i'm not sure.
I have a form on which the filepond plugin send the file manually
Look here if(empty($_POST['image'])) { echo 'add file!'; } $myimage = $_POST['image']; $myimage = str_replace('data:image/png;base64,', '', $myimage); $myimage = str_replace(' ', '+', $myimage); $decode = base64_decode($myimage); $myfile = $_SERVER['DOCUMENT_ROOT'].'/mages/' . uniqid() . '.png'; //now put the file file_put_contents($myfile, $decode);
I tried to add a second file upload to my previously properly functioning form, but after adding it, now when I submit the form, it submits the data twice. It appears to be submitting the file right on the first insert, but on the second insert, the second image is not inserted, but just blank. Can anyone help me figure out why? I must have done something wrong in my insert statement or second file statement. Here is the page itself which contains the form: http://midwestcreativeconsulting.com/jhrevell/add/ And below is my insert page: Code: [Select] <?php $dbhost = 'localhost'; $dbuser = 'username'; $dbpass = 'password'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'jhrevell_jewelry'; mysql_select_db($dbname); $name = $_POST['name']; $metal = $_POST['metal']; $desc = $_POST['desc']; $item_no = $_POST['item_no']; $cut = $_POST['cut']; $color = $_POST['color']; $carats = $_POST['carats']; $clarity = $_POST['clarity']; $size = $_POST['size']; $type = $_POST['type']; $other = $_POST['other']; $total = $_POST['total']; $certificate = $_POST['certificate']; $value = $_POST['value']; //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 "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 />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} // IMAGE 2 // //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file2"]["error"] > 0) { echo "Return Code: " . $_FILES["file2"]["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 />"; if (file_exists("upload/" . $_FILES["file2"]["name"])) { echo $_FILES["file2"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file2"]["tmp_name"], "upload/" . $_FILES["file2"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image2 = $_FILES["file2"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} echo '<script language="Javascript">'; echo 'window.location="http://midwestcreativeconsulting.com/jhrevell/collections"'; echo '</script>'; ?> Can anyone see what could be causing it to insert the record twice? Having some issues getting this to work properly... I keep getting my own error message I know where it fails, but I can't seem to figure out why it fails. The test file I'm using is an MP3 file, which is why I'm here asking if anyone other than I can shed some experienced light on this :p Code: [Select] File Upload Failed! No File Exists!The file type or extension you are trying to upload is not allowed! You can only upload MP3 files to the server! My upload form looks like: <?php session_start(); define('PITCHFORK', true); if(!isset($_SESSION['USERS_AUTHENTICATED'])) { die("You must be logged in to do that"); } if(isset($_POST['upload'])) { include("config.php"); include("classes/class.media.upload.php"); $file = $_GET['file']; $upload = new Upload; $upload->doAudio($file); } ?> <!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>PITCHFORK Login</title> <link rel="stylesheet" href="style/login.css" type="text/css" media="all"> <meta name="robots" content="noindex,nofollow"> </head> <body> <div id="login"><h1><a title="A SpaazZ Industries Concept"></a></h1> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label>File (one at a time for now)<br> <input name="file" id="user_login" class="input" size="20" tabindex="10" type="file" /> </label> </p> <p> </p> <?php if(isset($_SESSION['errMessage'])) { echo("<div id=\"login_error\"><strong>ERROR</strong>:<br />"); echo($_SESSION['errMessage']); unset($_SESSION['errMessage']); echo("</div>"); } ?> <p class="submit"> <input name="upload" id="submit" class="button-primary" value="Upload File" tabindex="100" type="submit"> </p> </form> </div> </body> </html> My Upload Class looks liks: <?php // TO DO : ERROR HANDLING // AJAX INTERFACING session_start(); define('PITCHFORK', true); class Upload { // The path to local (relivent to the user uploading - on their computer) file var $file; public function doAudio($file) { $target_path = $_SESSION['USERS_Media_Folder']."/"; // Set at login in class.users.php $flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload. $filename = $_FILES[$file]['name']; $filesize = $_FILES[$file]['size']; $mimetype = $_FILES[$file]['type']; $filename = htmlentities($filename); $filesize = htmlentities($filesize); $mimetype = htmlentities($mimetype); $target_path = $target_path . basename( $filename ); if($filename != ""){ echo "Beginning upload process for file named: ".$filename."<br>"; echo "Filesize: ".$filesize."<br>"; echo "Type: ".$mimetype."<br><br>"; } //First generate a MD5 hash of what the new file name will be //Force a MP3 extention on the file we are uploading $hashedfilename = md5_file($filename); $hashedfilename = $hashedfilename.".mp3"; //Check for empty file if($filename == ""){ $_SESSION['errMessage'] .= "No File Exists!"; $flag = $flag + 1; } //Now we check that the file doesn't already exist. $existname = $target_path.$hashedfilename; if(file_exists($existname)) { if($flag == 0) { $_SESSION['errMessage'] .= "Your file already exists on the server! Please choose another file to upload or rename the file on your computer and try uploading it again!"; } $flag = $flag + 1; } //Whitelisted files - Only allow files with MP3 extention onto server... $whitelist = array(".mp3"); foreach ($whitelist as $ending) { if(substr($filename, -(strlen($ending))) != $ending) { $_SESSION['errMessage'] .= "The file type or extention you are trying to upload is not allowed! You can only upload MP3 files to the server!"; $flag++; } } //Now we check the filesize. If it is too big or too small then we reject it //MP3 files should be at least 1MB and no more than 6.5 MB if($filesize > 6920600) { //File is too large if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too large! Your file can be up to 6.5 MB in size only. Please upload a smaller MP3 file or encode your file with a lower bitrate."; } $flag = $flag + 1; } if($filesize < 1048600) { //File is too small if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too small! Your file has been marked as suspicious because our system has determined that it is too small to be a valid MP3 file. Valid MP3 files must be bigger than 1 MB and smaller than 6.5 MB."; } $flag = $flag + 1; } //Check the mimetype of the file if($mimetype != "audio/x-mp3" and $mimetype != "audio/mpeg") { if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload does not contain expected data. Are you sure that the file is an MP3?"; } $flag = $flag + 1; } //Check that the file really is an MP3 file by reading the first few characters of the file $f = @fopen($_FILES[$file]['tmp_name'],'r'); $s = @fread($f,3); @fclose($f); if($s != "ID3") { if($flag == 0){ $_SESSION['errMessage'] .= "The file you are attempting to upload does not appear to be a valid MP3 file."; } $flag++; } //All checks are done, actually move the file... if($flag == 0) { if(move_uploaded_file($_FILES[$file]['tmp_name'], $target_path)) { //Change the filename to MD5 hash and FORCE a MP3 extention. if(@file_exists($target_path.$filename)) { //Rename the file to an MD5 version rename($target_path.$filename, $target_path.$hashedfilename); echo "The file ". basename( $filename ). " has been uploaded. Your file is <a href='$target_path$hashedfilename'>here</a>."; } else{ echo "There was an error uploading the file, please try again!"; } } else { echo "There was an error uploading the file, please try again!"; } } else { echo "File Upload Failed!<br>"; if($error != "") { echo $error; } } } // Close function doAudio } // Close Class audioUpload ?> At the moment I am creating a search function for my website. The approach I have in mind is a pseudo-PHP database. To give an example: A HTML form will submit the results to a PHP file. HTML FORM - Colour: Black PHP RESULT PAGE - if ($_POST['color'] == 'Black') {readfile("./products/black/*.html");} HTML FORM - Price: <$50 PHP RESULT PAGE - if ($_POST['Price'] == '<$50') {readfile("./products/less50/*.html");} The problem here is if there is an item that is black and costs less than $50, then its going to be listed twice. There is probably some code I can write to ommit the listing of duplicate entries, but it is probably going to be messy, so I am wondering if its better to use a centralized MySQL database, rather than a pseudo-PHP database? I've never used MySQL and don't know much about it and this is my first real attempt at using PHP. 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'");
I've looked over it a couple times and I still get the error. Here's the code <?php require('header.php'); require('links.php'); $name = mysql_real_escape_string($_POST['file']); $url = mysql_real_escape_string($_POST['file']); $filename = $_FILES['file']['name']; $temp = $_FILES['file']['tmp_name']; $error = $_FILES['file']['error']; $sql = "insert into books set name='$name', url='$url'"; if(isset($_POST['submit'])) { if($error > 0) { die("Error uploading file! Code $error."); }else{ move_uploaded_file($temp,"/center/resources/books/".$filename); mysql_query($sql); } } ?> <form method='post' enctype='multipart/form-data'> Book Name<input type="text" name="name"></br> File<input type="file" name="file"></br> <input type="submit" name="submit" value="Upload"> </form> I have been spending the majority of this week figuring out why my files are not showing up at my upload location that I set up in my newly created simple upload form. It just seems like php doesn't like me at all. Here is what my code looks like below. Code: [Select] <?php if (move_uploaded_file($_FILES['thefile']['name'], $upload_file)) $destination = "/www/zymichost.com/m/t/l/mtlproductions/htdocs/"; $upload_file = $destination . basename($_FILES['thefile']['name']);{ echo "Your file has been uploaded successfully!"; }/* else { echo "Your file did not upload successfully. Check to make sure your file meets the requirements and then try again."; print_r($_FILES);}*/?> I have the orange marked areas commented out due to the unexpected T_ELSE error thing. What do I do to get my files to show up at my upload location when I use my upload form? Thanks! Hi! So I'm working for someone, and they want me to fix this error in a PHP file.. Here is the code: <?php include_once('config.php'); $online = mysql_query("SELECT * FROM bots WHERE status LIKE 'Online'"); $offline = mysql_query("SELECT * FROM bots WHERE status LIKE 'Offline'"); $dead = mysql_query("SELECT * FROM bots WHERE status LIKE 'Dead'"); $admintrue = mysql_query("SELECT * FROM bots WHERE admin LIKE 'True'"); $adminfalse = mysql_query("SELECT * FROM bots WHERE admin LIKE 'False'"); $windows8 = mysql_query("SELECT * FROM bots WHERE so LIKE '%8%'"); $windows7 = mysql_query("SELECT * FROM bots WHERE so LIKE '%7%'"); $windowsvista = mysql_query("SELECT * FROM bots WHERE so LIKE '%vista%'"); $windowsxp = mysql_query("SELECT * FROM bots WHERE so LIKE '%xp%'"); $unknown = mysql_query("SELECT * FROM bots WHERE so LIKE 'Unknown'"); $totalbots = mysql_num_rows(mysql_query("SELECT * FROM bots")); $onlinecount = 0; $offlinecount = 0; $deadcount = 0; $admintruecount = 0; $adminfalsecount = 0; $windows8count = 0; $windows7count = 0; $windowsvistacount = 0; $windowsxpcount = 0; $unknowncount = 0; while($row = mysql_fetch_array($online)){ $onlinecount++; } while($row = mysql_fetch_array($offline)){ $offlinecount++; } while($row = mysql_fetch_array($dead)){ $deadcount++; } while($row = mysql_fetch_array($admintrue)){ $admintruecount++; } while($row = mysql_fetch_array($adminfalse)){ $adminfalsecount++; } while($row = mysql_fetch_array($windows8)){ $windows8count++; } while($row = mysql_fetch_array($windows7)){ $windows7count++; } while($row = mysql_fetch_array($windowsvista)){ $windowsvistacount++; } while($row = mysql_fetch_array($windowsxp)){ $windowsxpcount++; } while($row = mysql_fetch_array($unknown)){ $unknowncount++; } $statustotal = $onlinecount + $offlinecount + $deadcount; $admintotal = $admintruecount + $adminfalsecount; $sototal = $windows7count + $windowsvistacount + $windowsxpcount + $unknowncount; ?> Can anyone tell me the error here, can how to fix it? Hi all I have a script that I have patched together and got to work in pieces. I'm up to the last part. I have the form working and emailing. It also will upload an image by itself and put it in a folder. Now i just need to tie those together and have the image put in the email as an attachment then deleted from server. I have it at a stage where it sends me the users details.. and it tries to send the photo but it comes through as junk txt. I think its the MIME encoding stuff that I have wrong.. not sure? Here's what I have so far. Code: [Select] $attachment = $path_of_uploaded_file; $fileatt = $attachment; // Path to the file $fileatt_type = "application/octet-stream"; // File Type $start= strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1; $fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); fclose($file); $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers = "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; $email_message .= "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $data = chunk_split(base64_encode($data)); $email_message .= "--{$mime_boundary}\n" . "Content-Type: {$fileatt_type};\n" . " name=\"{$fileatt_name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "--{$mime_boundary}--\n"; // create email headers $headers .= 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); Thanks Wolfsta I want to let users select and upload a file. The select form and upload sritp work when they are on different pages, but I want them on the same page with the upload script executing only if the form has been submitted. Here the upload form <!--select the file --> <form enctype="multipart/form-data" action="manage_files.php" method="POST">Please choose a file to upload: <input name="uploaded" type="file" /><input type="submit" value="Upload" /></form> ... and here's the upload code... <!--upload the file --> <?php if (isset($_POST['submit'])) { $target = "safes/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition //if ($uploaded_size > 350000) //{ //echo "Your file is too large.<br>"; //$ok=0; //} //if (!($uploaded_type=="application/zip")) { //echo "You may only upload ZIP files.<br>"; //$ok=0; //} //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } } ?> What am I missing? Thanks for any help! I have an excel file that has several columns with different data and I need to create a form that can upload this excel file and insert the data from the columns into its conrresponding data columns in a mysql database. I know how to create the form but I have no idea how to get the file and tell it to input each cell of data into its corresponding field in the mysql database. Does anyone know how to do this? Any help would be appreciated. Thanks, I'm trying to add a file size limit to my upload form-code (below) I have a PHP script that uploads images to a folder on my server (attachments folder). Currently the folder sits within my webroot and is publicly accessible (I have to use chmod 777 due to permissions issue). So, I created the "attachments" folder outside of my webroot (so that it is not publicly accessible), but I do not know how to set the path in the PHP code to upload it to that "attachments" folder outside of the webroot. As you see in the snippet of PHP code below, the code currently uploads the the "attachments" folder within the www (webroot) directory. How do I make it upload to the "attachments" folder OUTSIDE of the www (webroot) directory? foreach($files[$form] as $file){ $str = $file[1]; if (eval("if($str){return true;}")) { $_values[$file[0]] = $_FILES[$file[0]]["name"]; $dirs = explode("/","attachments//"); $cur_dir ="."; foreach($dirs as $dir){ $cur_dir = $cur_dir."/".$dir; if (!@opendir($cur_dir)) { mkdir($cur_dir, 0777);}} $_values[$file[0]."_real-name"] = "attachments/".date("YmdHis")."_".$_FILES[$file[0]]["name"]."_secure"; copy($_FILES[$file[0]]["tmp_name"],$_values[$file[0]."_real-name"]); @unlink($_FILES[$file[0]]["tmp_name"]); }else{ $flag=true; if ($_isdisplay) { //$ExtFltr = $file[2]; //$FileSize = $file[4]; if (!eval("if($file[2]){return true;}")){echo $file[3];} if (!eval("if($file[4]){return true;}")){echo $file[5];} $_ErrorList[] = $file[0]; } } } |