PHP - File Uploading
Hi,
I have a system that uses PHP to create a Word Doc as information is extracted from a table using this code: Code: [Select] header("Content-type: applicaton/save"); header("Content-Disposition: attachment; filename="FILE NAME".doc"); header("Pragma: no-cache"); header("Expires: 0"); This part of the system I'm trying to implement is working fine. However, what I would ideally like for it to do (and at this point I understand that it sounds a bit pointless) is to save that downloaded file onto a specified folder location on the server directory i.e. to the uploads folder. This will enable all users of the system to then download / view these files as required. I'm not sure whether this is possible or not but and help would be greatly appreciated. Thanks in advance, Ben Similar TutorialsHey all So have been working on a file upload script, it was uploading the file but also adding the path name instead of NULL to mysql when no image was to upload, that is now fixed however now it won't upload the actual image to the directory. I tried undoing the mysql changes but it still won't upload the image to the directory. Am testing on my own computer using xampp so no file permission issues, plus it was working before. Any help much appreciated. Thanks <?php $product_code = mysqli_real_escape_string($conn, $_POST['product_code']); $product_name = mysqli_real_escape_string($conn, $_POST['product_name']); $category = mysqli_real_escape_string($conn, $_POST['category']); $filter = mysqli_real_escape_string($conn, $_POST['filter']); $description = mysqli_real_escape_string($conn, $_POST['description']); $specification = mysqli_real_escape_string($conn, $_POST['specification']); $price = mysqli_real_escape_string($conn, $_POST['price']); $target_dir = "../images/products/"; if (!isset ($_FILES["img1"]["name"])) { $target_file1 = NULL; } else { if (!empty($_FILES["img1"]["name"])) { $target_file1 = $target_dir . basename($_FILES["img1"]["name"]); } else { $target_file1 = NULL; } } if (!isset ($_FILES["img2"]["name"])) { $target_file2 = NULL; } else { if (!empty($_FILES["img2"]["name"])) { $target_file2 = $target_dir . basename($_FILES["img2"]["name"]); } else { $target_file2 = NULL; } } if (!isset ($_FILES["img3"]["name"])) { $target_file3 = NULL; } else { if (!empty($_FILES["img3"]["name"])) { $target_file3 = $target_dir . basename($_FILES["img3"]["name"]); } else { $target_file3 = NULL; } } if (!isset ($_FILES["img4"]["name"])) { $target_file4 = NULL; } else { if (!empty($_FILES["img4"]["name"])) { $target_file4 = $target_dir . basename($_FILES["img4"]["name"]); } else { $target_file4 = NULL; } } $uploadOk = 1; $imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION)); $imageFileType2= strtolower(pathinfo($target_file2,PATHINFO_EXTENSION)); $imageFileType3 = strtolower(pathinfo($target_file3,PATHINFO_EXTENSION)); $imageFileType4 = strtolower(pathinfo($target_file4,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check1 = getimagesize($_FILES["img1"]["tmp_name"]); $check2 = getimagesize($_FILES["img2"]["tmp_name"]); $check3 = getimagesize($_FILES["img3"]["tmp_name"]); $check4 = getimagesize($_FILES["img4"]["tmp_name"]); if($check1 !== false) { echo "File is an image - " . $check1["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file1)) { echo "Sorry, image one already exists."; $uploadOk = 0; } if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg" && $imageFileType1 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1."; $uploadOk = 0; } if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image one."; } } echo '<br />'; if($check2 !== false) { echo "File is an image - " . $check2["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file2)) { echo "Sorry, image two already exists."; $uploadOk = 0; } if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg" && $imageFileType2 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img2."; $uploadOk = 0; } if (isset ($target_file2)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img2"]["tmp_name"], $target_file2)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image two."; } } } echo '<br />'; if($check3 !== false) { echo "File is an image - " . $check3["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file3)) { echo "Sorry, image three already exists."; $uploadOk = 0; } if($imageFileType3 != "jpg" && $imageFileType3 != "png" && $imageFileType3 != "jpeg" && $imageFileType3 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img3."; $uploadOk = 0; } if (isset ($target_file3)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img3"]["tmp_name"], $target_file3)) { echo "The file ". htmlspecialchars( basename( $_FILES["img3"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image three."; } } } echo '<br />'; if($check4 !== false) { echo "File is an image - " . $check4["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file4)) { echo "Sorry, image four already exists."; $uploadOk = 0; } if($imageFileType4 != "jpg" && $imageFileType4 != "png" && $imageFileType4 != "jpeg" && $imageFileType4 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img4."; $uploadOk = 0; } if (isset ($target_file4)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img4"]["tmp_name"], $target_file4)) { echo "The file ". htmlspecialchars( basename( $_FILES["img4"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image four."; } } } } echo '<br />'; $image1 = basename($target_file1); $image2 = basename($target_file2); $image3 = basename($target_file3); $image4 = basename($target_file4); // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')"; if (mysqli_query($conn, $sql)) { echo "Product Added successfully, Now on to the Sizes"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } ?>
i am using the fancy upload script for post attachments on my forum. the problem is that when a user starts a new post and adds an attachment the attachment is uploaded before the post is complete. so how would i associate the attachment with the post that they are going to post when i have no post id to go off? i had tried not uploading the files straight away and instead populate an input box with the filenames but i cant figure it out with this script. Anyone got any other options or ideas? ok im stuck again and need help. I have gotten rid of the attachment system(too many issues) on ASF and decided to replace it with my own. The problem is that the original new post form is sent to php via jQuery. Obv i cannot do this with files so the attachment section needs to be a seperate form. Now i have no issues with sending files to the folder and sending their name to the database but i need to send multiple. so far when the user selects a file it will add the name of it to a hidden input element and each one that is added to that element is seperated with | . then in the php i would use explode on this element to get an array of the file names. but this only helps when sending to the database and not when moving files. I also dont want a page refresh when uploading files. No other file upload systems out there will work because they upload the file as soon as you press submit, but then how do i add the post id to the attachments row in the database? ok i added this script in the bottom of my other uploader script.
what i wanted to do was, to upload an imagefile to an folder called uploads
and in the same time add the name of the file to an database called uploads,
together with the next id of another database
i dont get any error msg, the page is just blank.
<?php include 'sqlconnect.php'; $result = mysql_query(" SHOW TABLE STATUS LIKE 'aktiviteter' "); $data = mysql_fetch_assoc($result); $next_increment = $data['Auto_increment']; $sql = sprintf( "INSERT INTO aktiviteter (`title`, `firma`, `beskrivelse`, `information`, `pris`, `varighed`, `antal`, `adresse`, `by`, `postnummer`, `telefon`, `email`, `hjemmeside`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", mysqli_real_escape_string($con, $_POST['title']), mysqli_real_escape_string($con, $_POST['firma']), mysqli_real_escape_string($con, $_POST['beskrivelse']), mysqli_real_escape_string($con, $_POST['information']), mysqli_real_escape_string($con, $_POST['pris']), mysqli_real_escape_string($con, $_POST['varighed']), mysqli_real_escape_string($con, $_POST['antal']), mysqli_real_escape_string($con, $_POST['adresse']), mysqli_real_escape_string($con, $_POST['by']), mysqli_real_escape_string($con, $_POST['postnummer']), mysqli_real_escape_string($con, $_POST['telefon']), mysqli_real_escape_string($con, $_POST['email']), mysqli_real_escape_string($con, $_POST['hjemmeside']) ); if (!mysqli_query($con, $sql)) { die('Error: ' . mysqli_error($con)); } echo "Aktiviteten er uploaded"; if(isset($_POST['upload'])) { $allowed_filetypes = array('.jpg','.jpeg','.png','.gif'); $max_filesize = 10485760; $upload_path = 'uploads/'; $targetId = $next_increment $filename = $_FILES['billede']['name']; $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); if(!in_array($ext,$allowed_filetypes)) die('The file you attempted to upload is not allowed.'); if(filesize($_FILES['billede']['tmp_name']) > $max_filesize) die('The file you attempted to upload is too large.'); if(!is_writable($upload_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); if(move_uploaded_file($_FILES['billede']['tmp_name'],$upload_path . $filename)) { $query = "INSERT INTO uploads (name, target) VALUES ($filename, $targetId)"; mysql_query($query); echo 'Your file upload was successful!'; } else { echo 'There was an error during the file upload. Please try again.'; } } mysqli_close($con); Hi, really need some extra brains to help me with this one! I have a form with only 1 text box (input type=text) in this textbox I enter a local path on my computer to a specific folder. in this folder I have few files, each has a set name that I know in advance. what I want to do is to be able to upload all those files in my local folder to the server, without making the user click browes and pick them 1 by 1. I searched and searched but I see it's not as simple as I thought cuz I can't just set the value of the input file.. since my page has a form eitherway I thought of maybe doing something sneaky and hiding the input files and some how passing them the path of each file (the folder path will be taken from the not hidden textbox) and the file name is known to me so I can add those 2 somehow.. I can't find a way to do that, so I wonder if any of you have an idea? maybe it's possible to set the file path after the form is submited? basicly I think it's possible to give the name of the file, but I also need the temp name of the file ($_FILES['docfile1']['tmp_name']), and this I don't know how to set.. this is my code for uploading a file with <input type=file> Code: [Select] if ($_FILES['docfile1']['name']!='') { $target = 'import/'; $target = $target . basename($_FILES['docfile1']['name']); if ($target =="import/myfile.xlsx"){ if (file_exists($target)) unlink($target); if (move_uploaded_file($_FILES['docfile1']['tmp_name'], $target)) { echo 'success'; }else{ echo 'fail'; } }else{ echo 'fail'; } }desperately need help! I am working on making an album however I am not sure where I am going wrong with my codes. I have an upload and thumbs folder in the albums folder but I keep getting this message.... Warning: mkdir() [function.mkdir]: File exists in /home/ebermy5/public_html/albums/album_func.php on line 44 Warning: mkdir() [function.mkdir]: File exists in /home/ebermy5/public_html/albums/album_func.php on line 45 Warning: Cannot modify header information - headers already sent by (output started at /home/ebermy5/public_html/albums/create_album.php:9) in /home/ebermy5/public_html/albums/create_album.php on line 29 Codes: for line 44 and 45 function create_album($album_name, $album_description){ $album_name = mysql_real_escape_string(htmlentities($album_name)); $album_description = mysql_real_escape_string(htmlentities($album_description)); mysql_query("INSERT INTO `albums` VALUES ('', '".$_SESSION['SESS_ID']."', UNIX_TIMESTAMP(), `$album_name`,`$album_description`)"); mkdir('uploads/'.mysql_insert_id(), 0744); mkdir('uploads/thumbs/'.mysql_insert_id(), 0744); } Code: for line 29 if(isset($_POST['album_name'], $_POST['album_description'])){ $album_name = $_POST['album_name']; $album_description = $_POST['album_description']; $errors = ""; if(empty($album_name) || empty($album_description)){ $errors = 'Album name and description required'; }else{ if(strlen($album_name) > 55 || strlen($album_description) > 255){ $errors = 'One or more fields contains too many characters'; } } if(!empty($errors)){ foreach($errors as $error){ echo $errors, '<br />'; } } else { create_album ($album_name, $album_description); header('Location: albums.php'); exit(); } } I am having trouble getting my upload file to work... Form HTML: Code: [Select] <form action="" method="POST"> <input type="file" name="file" /> <input type='"submit" name="upload" value="Upload" /> </form> PHP: Code: [Select] if($_POST["upload_avatar"]){ $upload_path = "images/users/"; $file = $_FILES["file"]["name"]; $extension_types = array("gif","jpg","jpeg","png"); if($file){ $filename = stripslashes($_FILES["file"]["name"]); $extension = getExtension($filename); $extension = strtolower($extension); $size = filesize($_FILES["file"]["tmp_name"]); if(in_array($extension, $extension_types)){ if($size <= $max_file_size){ $file_search = glob($upload_path . strtolower($username) . '*'); array_map("unlink", $file_search); $file_name = $upload_path . strtolower($username) . "." . $extension; $copied = copy($_FILES["file"]["tmp_name"], $file_name); if (!$copied){ $r_error = "Upload has failed"; } } else{$r_error = "File too big";} } else{$r_error = "Unknown file extension";} } else{$r_error = "No file chosen";} } Every time, it gives me the "No File Chosen" error. It doesn't seem to be actually uploading the file... I hope this isn't just some stupid thing I am looking over, can someone help me? please just deleting this post I think i figured it out I don't know why this image upload code isn't uploading the image file to the uploads/ folder.
Any help will be appreciated.
$allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); $extension = strtolower( end($temp) ); if ( $_FILES["file"]["size"] < 2000000 && in_array($extension, $allowedExts) ) { if ($_FILES["file"]["error"]!= 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; } else { $length = 20; $randomString = substr(str_shuffle(md5(time())),0,$length); $newfilename = $randomString . "." . $extension; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename ); $file_location = '<a href="http://www.--.com/upload/' . $newfilename . '">http://www.--.com/upload/' . $newfilename . '</a>'; } } else { echo "Invalid upload file"; } <form enctype="multipart/form-data" action="uploader.php"> <input type="file" name="file" id="file"> <input type="submit" name="submitted" value="Submit"> </form> Hi All Please can someone help me. I have a CSV file with over 3000 lines. Each one contains the following information Country Insurance Name Mandatory or Optional Description and Coverage Group SIPP Cost Per Day Cost Per Week Cost Per Month Deductable I have written the following script to read line by line, compare the country and insurance with the previous and if it is the same, tag certain parts of each line onto the end of the previous. However, I am getting no output from this, and I keep getting an error saying I am using too much memory or my computer hangs. I am fairly new to php so any pointers would be good. Firstly, does my script look like it should do what I want it to do? If so, any clues how to get around the momory issue. If not, what have I done wrong? Cheers guys <?php //open file paths $handle=fopen("insurances.csv","r"); $handle_out=fopen("insuranceoutput.csv","a"); //writes the first line of the csv file into an array to act as a comparrison if($handle){ $line=fgets($handle); $line_array=explode(",",$line); $full_array=$line_array; fclose($handle); } } if($handle) { while (!feof($handle)) { // read one line into array $line=fgets($handle); $line_array=explode(",",$line); fclose($handle); //test to see if country matches previous while ($line_array[0] == $full_array[0]) { //test to see if insurance matches previous while ($line_array[1] == $full_array[1]) { //write array values 4 - 9 to main array $full_array[]=array("$line_array[4]","$line_array[5]","$line_array[6]","$line_array[7]","$line_array[8]","$line_array[9]"); } } //write to new file when new insurance is found foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } // write to new file if new country is found. foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } } ?> Hello I am new to programming, coding, php... and need some help. I have some code that uploads a file and does some basic checks but I also want it to rename the file possibly adding the time stamp. Heres what I have so far. cheers. $tbl_name="guestbook"; // Table name $email = $_REQUEST["email"]; $name = $_REQUEST["name"]; $comment = $_REQUEST["comment"]; $_FILES["file"]["name"]; $_FILES["file"]["type"]; $_FILES["file"]["size"]; $_FILES["file"]["tmp_name"]; $_FILES["file"]["error"]; $datetime = date("dmy"); $uploaddir = "upload/"; $filename = $_FILES["file"]["name"]; $pathinfo = pathinfo($_FILES['userfile1']['name']); mysql_connect("$host", "$username", "$password")or die("cannot connect server "); mysql_select_db("$db_name")or die("cannot select DB"); $sql="INSERT INTO $tbl_name(name, email, comment, datetime)VALUES('$name', '$email', '$comment', '$datetime')"; $result=mysql_query($sql); if($result){ echo "Successful added update to the Melody Bear Bulletin Board"; echo "<BR>"; echo "<a href='ViewBulletinBoard.php'>View Bulletin Board</a>"; } else { echo "ERROR"; } if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { 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: " . "upload/" . $_FILES["file"]["name"]. "<br>"; } } } else { echo "Invalid file"; } mysql_close(); ?> Sorry for posting this here, but for some reason the "create new topic" in linux subforum doesnt exist. anyways i made a small php script that enables me to retrieve data between two dates. now am stuck on how i should copy it or u0pload it into linux. system tells me i need to upload to /usr/bin/libexec , i am there now but i dont have the slightest idea on how to do that. help is much appreciated. Thanks I am using a script found off the web to upload file and show a ajaxy waiting image. In the code for the actual upload is this code $destination_path = getcwd().DIRECTORY_SEPARATOR; $result = 0; $target_path = $destination_path . basename( $_FILES['myfile']['name']); if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) { $result = 1; } I am running it from domain.com/label/manage/add-file/upload.php and it uploads the file to domain.com/label/manage/add-file/ How can I upload the file to domain.com/files/123/432/ Do I need to modify the destination path? Also do i need to start it from /home/user/......... Thanks I actually have two parts to this post. One which describes just my understanding on how a multipart request should look with a REST API and gives a little context, and the second how to actually implement it using Sympony and api-platform. Part 1 Looking to simultaneously upload a file, some file meta data, and identifier of the uploading user to a REST API, and will do so using a multipart request. Based on swagger, looks like the request should look something like the following: POST /upload HTTP/1.1 Content-Length: 428 Content-Type: multipart/form-data; boundary=abcde12345 --abcde12345 Content-Disposition: form-data; name="id" Content-Type: text/plain 123e4567-e89b-12d3-a456-426655440000 --abcde12345 Content-Disposition: form-data; name="address" Content-Type: application/json { "street": "3, Garden St", "city": "Hillsbery, UT" } --abcde12345 Content-Disposition: form-data; name="profileImage "; filename="image1.png" Content-Type: application/octet-stream {…file content…} --abcde12345-- Background noise... The above example shows three parts which include the text ID, JSON address and octet-stream file. Doing so doesn't make sense to me and I will probably just have two parts for the meta data JSON. Note that potentially, I will be removing the user from the JSON payload and including it in some JWT header. Also, showing resources as links such as /api/users/1 in the request and response JSON is new to me, but I guess makes sense. Regardless, my meta data JSON will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "user": "/api/users/1" } and the response will look like: { "projectId": 1234, "documentDescription": "bla bla bla", "specification": "230903.2.4.D", "uploadAt": "2021-01-27 08:41:17", "fileName": "pressuresensor.pdf". "user": "/api/users/1". "file": "/api/uplodaed_files/1234" } Am I somewhat going down the right path? Part 2 Wow, should have looked into Sympony before now! Entities, validation, the API, etc were a breeze. Still confused with some of the "magic", but understanding what is under the hood more and more. As stated initially, I am utilizing api-platform and am looking at api-platform's file-upload. I guess the first question is whether my POST request with both the file and JSON meta data can be performed in a single request. Per making-a-request-to-the-media_objects-endpoint: QuoteYour /media_objects endpoint is now ready to receive a POST request with a file. This endpoint accepts standard multipart/form-data-encoded data, but not JSON data. What? Am I reading this correct? Do I first need to make a multipart requests using either a standard HTML form or a XMLHttpRequest which just sends the file, receive the document locator, and then send a second request with the location and my meta data? If so, I guess I have enough to go forward. I would rather, however, perform the work in a single request. My previous mentioned swagger multipart-requests shows both in the same request. symfonycasts's api-uploads also describes doing so, but not with api-platform. Is there a way to do so with api-platform? Does it make sense to use api-platform for all other routes but then make a custom route for document with meta data uploads? Any recommendations are much appreciated. Thanks Im trying to use a file upload script i found he http://www.phptoys.com/e107_plugins/content/content.php?content.39 and everything says it works but the file deosnt upload and i get the following in the error log: Quote [20-Jan-2011 20:02:42] PHP Fatal error: Call to a member function Get() on a non-object in /home/mikeh/public_html/test/uploader.php on line 33 [20-Jan-2011 20:03:48] PHP Fatal error: Call to a member function Get() on a non-object in /home/mikeh/public_html/test/uploader.php on line 33 here is some info copied from my hostgator cpanel: Home Directory: /home/mikeh Operating System: Linux CentOS below is the entire source code: <?php /************************************************* * Micro Upload * * Version: 0.1 * Date: 2006-10-27 * * Usage: * Set the uploadLocation variable to the directory * where you want to store the uploaded files. * Use the version which is relevenat to your server OS. * ****************************************************/ //Windows way //$uploadLocation = "/home/mikeh/public_html/test"; //Unix, Linux way $uploadLocation = "/home/mikeh/public_html/test/"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html> <head> <title>MicroPing domain status checker</title> <link href="style/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="main"> <div id="caption">UPLOAD FILE</div> <div id="icon"> </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="fileForm" id="fileForm" enctype="multipart/form-data"> File to upload:<center> <table> <tr><td><input name="upfile" type="file" size="36"></td></tr> <tr><td align="center"><br/><input class="text" type="submit" name="submitBtn" value="Upload"></td></tr> </table></center> </form> <?php if (isset($_POST['submitBtn'])){ ?> <div id="caption">RESULT</div> <div id="icon2"> </div> <div id="result"> <table width="100%"> <?php $target_path = $uploadLocation . basename( $_FILES['upfile']['name']); //die($target_path); if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) { echo "The file: ". basename( $_FILES['upfile']['name']). " has been uploaded!"; } else{ echo "There was an error uploading the file, please try again!"; } ?> </table> </div> <?php } ?> <div> </body> Edit: can be seen/tested at: http://cnotes.ca/test/microUpload.php Hello all, I'm designing an upload file section for a home medical company. So far it has been going great, I am uploading files and they're being successfully inserted into my MYSQL Table. However, my issue is when I download the files they claim to be corrupted and unusable. If I save the PDF files to my desktop they won't open at all, they claim to be corrupted. If I download a JPG and then open it in photshop it warns me the file may be corrupted, knowing it is not I clicked "yes". The jpg actually opens and looks like the image, however about 50 pixels on the bottom get cut off and look like a messy TV screen, if that makes sense. Wondering if anyone has had this similar issue, the uploading part is not the issue - just downloading the files. My Upload Form Code: Code: [Select] <p><a href="upload.php">Upload a File</a> <a href="../admin/admin.php">Back to Control Panel</a></p> <form action="add_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> My Add File Code (This is working fine but may cause issues with downloading?) Code: [Select] <?php // Check if a file has been uploaded if(isset($_FILES['uploaded_file'])) { // Make sure the file was sent without errors if($_FILES['uploaded_file']['error'] == 0) { // Connect to the database $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Gather all required data $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']); $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']); $data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name'])); $size = intval($_FILES['uploaded_file']['size']); // Create the SQL query $query = " INSERT INTO `file` ( `name`, `mime`, `size`, `data`, `created` ) VALUES ( '{$name}', '{$mime}', {$size}, '{$data}', NOW() )"; // Execute the query $result = $dbLink->query($query); // Check if it was successfull if($result) { echo 'Success! Your file was successfully added!'; } else { echo 'Error! Failed to insert the file' . "<pre>{$dbLink->error}</pre>"; } } else { echo 'An error accured while the file was being uploaded. ' . 'Error code: '. intval($_FILES['uploaded_file']['error']); } // Close the mysql connection $dbLink->close(); } else { echo 'Error! A file was not sent!'; } // Echo a link back to the main page echo '<p>Click <a href="upload.php">here</a> to go back</p>'; ?> My List File Code (This is working fine also, but does contain the link that I click when I want to download a file) Code: [Select] <?php $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Query for a list of all existing files $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`'; $result = $dbLink->query($sql); // Check if it was successfull if($result) { // Make sure there are some files in there if($result->num_rows == 0) { echo '<p>There are no files in the database</p>'; } else { // Print the top of a table echo '<table width="100%"> <tr> <td><b>Name</b></td> <td><b>Mime</b></td> <td><b>Size (bytes)</b></td> <td><b>Created</b></td> <td><b> </b></td> </tr>'; // Print each file while($row = $result->fetch_assoc()) { echo " <tr> <td>{$row['name']}</td> <td>{$row['mime']}</td> <td>{$row['size']}</td> <td>{$row['created']}</td> [u][b]<td><a href='get_file.php?id={$row['id']}'>Download</a></td>[/b][/u] </tr>"; } // Close table echo '</table>'; } // Free the result $result->free(); } else { echo 'Error! SQL query failed:'; echo "<pre>{$dbLink->error}</pre>"; } // Close the mysql connection $dbLink->close(); ?> And here is my Get File page. This is where my problem lies. (I think) Code: [Select] <?php // Make sure an ID was passed if(isset($_GET['id'])) { // Get the ID $id = intval($_GET['id']); // Make sure the ID is in fact a valid ID if($id <= 0) { die('The ID is invalid!'); } else { // Connect to the database $dbLink = new mysqli('localhost', 'vzimbel_user', 'webdesign1', 'vzimbel_db'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Fetch the file information $query = " SELECT `mime`, `name`, `size`, `data` FROM `file` WHERE `id` = {$id}"; $result = $dbLink->query($query); if($result) { // Make sure the result is valid if($result->num_rows == 1) { // Get the row $row = mysqli_fetch_assoc($result); // Print headers header("Content-Type: ". $row['mime']); header("Content-Length: ". $row['size']); header("Content-Disposition: attachment; filename=". $row['name']); // Print data echo $row['data']; } else { echo 'Error! No image exists with that ID.'; } // Free the mysqli resources @mysqli_free_result($result); } else { echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; } @mysqli_close($dbLink); } } else { echo 'Error! No ID was passed.'; } ?> Thanks for any help that anyone can provide, this issue is really causing some stress and hurting my sleep at night! Can't figure out why this won't work, it's literally the last step in completing this website. Please let me know if you need any other information regarding this issue. Thanks, - Mike The code works but it puts the files into /uploadir/. The users directories go by their email addresses ($email). when i input this code it only uploads a single column into my database
<html> <head> <title>MySQL file upload example</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html> Hi i have this form which meant to upload the create an album but some how doesnt not work can some1 help please i use 3 files here they are addalbum.php is where is not working the other files are just the database config and functions.php the error messages from the addalbum.php functions addalbum.php require_once '../library/config.php'; require_once '../library/functions.php'; if(isset($_POST['txtName'])) { $albumName = $_POST['txtName']; $albumDesc = $_POST['mtxDesc']; $imgName = $_FILES['fleImage']['name']; $tmpName = $_FILES['fleImage']['tmp_name']; // we need to rename the image name just to avoid // duplicate file names // first get the file extension $ext = strrchr($imgName, "."); // then create a new random name $newName = md5(rand() * time()) . $ext; // the album image will be saved here $imgPath = ALBUM_IMG_DIR . $newName; // resize all album image $result = createThumbnail($tmpName, $imgPath, THUMBNAIL_WIDTH); if (!$result) { echo "Error uploading file"; exit; } if (!get_magic_quotes_gpc()) { $albumName = addslashes($albumName); $albumDesc = addslashes($albumDesc); } $query = "INSERT INTO tbl_album (al_name, al_description, al_image, al_date) VALUES ('$albumName', '$albumDesc', '$newName', NOW())"; mysql_query($query) or die('Error, add album failed : ' . mysql_error()); // the album is saved, go to the album list echo "<script>window.location.href='index.php?page=list-album';</script>"; exit; } <!-- google_ad_section_end --> <FORM enctype="multipart/form-data" action="addalbum.php" method="post"> <P> <LABEL for="firstname">al_name: </LABEL> <INPUT type="text" name="form" id="albumName"><BR> <LABEL for="lastname">al_description: </LABEL> <INPUT type="text" name="form" id="albumDesc"><BR> <LABEL for="email">al_date: </LABEL> <INPUT type="text" id="NOW"><BR> <input type="file" name="newName" class="input"> <p><input type="submit" name="submit" value="Upload" class="submit"></p> </P> </FORM> funtions.php <?php /* Upload an image and create the thumbnail. The thumbnail is stored under the thumbnail sub-directory of $uploadDir. Return the uploaded image name and the thumbnail also. */ function uploadImage($inputName, $uploadDir) { $image = $_FILES[$inputName]; $imagePath = ''; $thumbnailPath = ''; // if a file is given if (trim($image['tmp_name']) != '') { $ext = substr(strrchr($image['name'], "."), 1); // generate a random new file name to avoid name conflict // then save the image under the new file name $imagePath = md5(rand() * time()) . ".$ext"; $result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath); if ($result) { // create thumbnail $thumbnailPath = md5(rand() * time()) . ".$ext"; $result = createThumbnail($uploadDir . $imagePath, $uploadDir . 'thumbnail/' . $thumbnailPath, THUMBNAIL_WIDTH); // create thumbnail failed, delete the image if (!$result) { unlink($uploadDir . $imagePath); $imagePath = $thumbnailPath = ''; } else { $thumbnailPath = $result; } } else { // the image cannot be uploaded $imagePath = $thumbnailPath = ''; } } return array('image' => $imagePath, 'thumbnail' => $thumbnailPath); } /* Create a thumbnail of $srcFile and save it to $destFile. The thumbnail will be $width pixels. */ function createThumbnail($srcFile, $destFile, $width, $quality = 75) { $thumbnail = ''; if (file_exists($srcFile) && isset($destFile)) { $size = getimagesize($srcFile); $w = number_format($width, 0, ',', ''); $h = number_format(($size[1] / $size[0]) * $width, 0, ',', ''); $thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality); } // return the thumbnail file name on sucess or blank on fail return basename($thumbnail); } /* Copy an image to a destination file. The destination image size will be $w X $h pixels */ function copyImage($srcFile, $destFile, $w, $h, $quality = 75) { $tmpSrc = pathinfo(strtolower($srcFile)); $tmpDest = pathinfo(strtolower($destFile)); $size = getimagesize($srcFile); if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg") { $destFile = substr_replace($destFile, 'jpg', -3); $dest = imagecreatetruecolor($w, $h); //imageantialias($dest, TRUE); } elseif ($tmpDest['extension'] == "png") { $dest = imagecreatetruecolor($w, $h); //imageantialias($dest, TRUE); } else { return false; } switch($size[2]) { case 1: //GIF $src = imagecreatefromgif($srcFile); break; case 2: //JPEG $src = imagecreatefromjpeg($srcFile); break; case 3: //PNG $src = imagecreatefrompng($srcFile); break; default: return false; break; } imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]); switch($size[2]) { case 1: case 2: imagejpeg($dest,$destFile, $quality); break; case 3: imagepng($dest,$destFile); } return $destFile; } /* Check if the user is logged in or not */ function checkLogin() { if (!isset($_SESSION['isLogin']) || $_SESSION['isLogin'] == false) { header('Location: login.php'); exit; } } /* Create the link for moving from one page to another */ function getPagingLink($totalResults, $pageNumber, $itemPerPage = 10, $strGet = '') { $pagingLink = ''; $totalPages = ceil($totalResults / $itemPerPage); // how many link pages to show $numLinks = 10; // create the paging links only if we have more than one page of results if ($totalPages > 1) { $self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ; // print 'previous' link only if we're not // on page one if ($pageNumber > 1) { $page = $pageNumber - 1; if ($page > 1) { $prev = " <a href=\"$self?pageNum=$page&$strGet\">[Prev]</a> "; } else { $prev = " <a href=\"$self?$strGet\">[Prev]</a> "; } $first = " <a href=\"$self?$strGet\">[First]</a> "; } else { $prev = ''; // we're on page one, don't show 'previous' link $first = ''; // nor 'first page' link } // print 'next' link only if we're not // on the last page if ($pageNumber < $totalPages) { $page = $pageNumber + 1; $next = " <a href=\"$self?pageNum=$page&$strGet\">[Next]</a> "; $last = " <a href=\"$self?pageNum=$totalPages&$strGet\">[Last]</a> "; } else { $next = ''; // we're on the last page, don't show 'next' link $last = ''; // nor 'last page' link } $start = $pageNumber - ($pageNumber % $numLinks) + 1; $end = $start + $numLinks - 1; $end = min($totalPages, $end); $pagingLink = array(); for($page = $start; $page <= $end; $page++) { if ($page == $pageNumber) { $pagingLink[] = " $page "; // no need to create a link to current page } else { if ($page == 1) { $pagingLink[] = " <a href=\"$self?$strGet\">$page</a> "; } else { $pagingLink[] = " <a href=\"$self?pageNum=$page&$strGet\">$page</a> "; } } } $pagingLink = implode(' | ', $pagingLink); // return the page navigation link $pagingLink = $first . $prev . $pagingLink . $next . $last; } return $pagingLink; } /* Display the breadcrumb navigation on top of the gallery page */ function showBreadcrumb() { if (isset($_GET['album'])) { $album = $_GET['album']; $sql = "SELECT al_name FROM tbl_album WHERE al_id = $album"; $result = mysql_query($sql) or die('Error, get album name failed. ' . mysql_error()); $row = mysql_fetch_assoc($result); echo ' > <a href="index.php?page=list-image&album=' . $album . '">' . $row['al_name'] . '</a>'; if (isset($_GET['image'])) { $image = $_GET['image']; $sql = "SELECT im_title FROM tbl_image WHERE im_id = $image"; $result = mysql_query($sql) or die('Error, get image name failed. ' . mysql_error()); $row = mysql_fetch_assoc($result); echo ' > <a href="index.php?page=image-detail&album=' . $album . '&image=' . $image . '">' . $row['im_title'] . '</a>'; } } } ?> config.php <?php session_start(); // db properties $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $dbname = 'rock'; // an album can have an image used as thumbnail // we save the album image here define('ALBUM_IMG_DIR', 'C:/webroot/image'); // all images inside an album are stored here define('GALLERY_IMG_DIR', 'C:/webroot/gallery/images/gallery/'); // When we upload an image the thumbnail is created on the fly // here we set the thumbnail width in pixel. The height will // be adjusted proportionally define('THUMBNAIL_WIDTH', 100); // make a connection to mysql here $conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error()); mysql_select_db ($dbname) or die ("I cannot select the database '$dbname' because: " . mysql_error()); ?> |