PHP - Trouble With Dir Management And File Uploading
Trying to a. check if dir exists if not create it, and b. save an uploaded file to that directory. Nothing however is working but I'm pulling no errors, heres the code:
$test_pic = $_POST['test_pic']; // I've also tried $test_pic = $_FILES["test_pic"]; : with no success if (is_uploaded_file($test_pic)) { if (!file_exists("tests/uploads/" . $test_name . "/")) { $create_test_folder = (mkdir("tests/uploads/" . $test_name)); if (!$create_test_folder) { echo "cant create folder"; die; } } $target_path = ("tests/uploads/" . $test_name . "/" . $test_name . "_1"); if (($_FILES["test_pic"]["type"] == "image/gif") || ($_FILES["test_pic"]["type"] == "image/jpeg") || ($_FILES["test_pic"]["type"] == "image/jpg") || ($_FILES["test_pic"]["type"] == "image/png") && ($_FILES["test_pic"]["size"] < 50000)) { if (!copy($test_pic, $target_path)) { echo "cant copy picture"; die; } } else { echo "file type or size bad"; die; } } and I understand its not at all public-safe but I'm just wanting to get it to work before I throw in the security. Thanks for the help! Similar TutorialsI am very new to php and am trying to create a simple application that uploads a PDF file to a database. I have one field for the Volume Number and on file field for the PDF to be uploaded. My issue is i can't get the PDF to upload or insert the name of the pdf (eg volume1.pdf) into the data base. I would also like to point out that I know i have a low post count, but i only seek help when i truly need it and have exhausted all other resources... Here is what i have, please go easy on me this is my first round at php: Code: [Select] <?php if(isset($_POST['submit'])){ $vol_num = $_POST['vol_num']; $pdf = $_FILES['pdf']['name']; $path = '../pdf/'.$_FILES['pdf']['name']; move_uploaded_file($_FILES["pdf"]["tmp_name"], $path); mysql_query("INSERT INTO volumes set vol_num='$vol_num', vol_link='$pdf'") or die (mysql_error()); echo "<script>location.href='add_volume.php'</script>"; } ?> what am i doing wrong here? Thanks in advance Hi, I am very new to PHP, I have managed to create a basic database with a table of users, and a form for logging in. Is there a way to create an 'area' where the users that are logged in can view, upload and download files. For example, a file storage area just like dropbox? If so, can anyone share some basic code or links to tutorials to achieve this please. Afterwards, I would then like to set permissions for each of the users to only access certain folders within that 'storage area'. I realise there are many websites like dropbox and box.net, but I would like to code my own version. Thanks in advance Hi. This is my first post, so feel free to lecture me on forum etiquette and conventions. I'm trying to create a form, several items of which are file upload <input>s. Here is the relevant code from the form. <label for="facefile">Filename:</label> <input type="file" name="facefile" id="facefile" /> This form has an action="validateform.php". In the file for validateform.php I can't seem to reference "facefile". I just try doing <?php echo($_FILES["facefile"]["name"]); ?> And I get Notice: Undefined index: facefile in validateform.php on line 1 Hey 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); } ?>
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 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); 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 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? 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! please just deleting this post I think i figured it out 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? 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 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(); ?> 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 currently racking my brains trying to work this out. I am creating a basic CMS system and one of the functions is to give them the option of adding pictures to their gallery however at the moment the uploaded file is not uploading...at all, the FILES array seems to have no recollection of it actually being posted. The script is meant to: 1. User types in specific details on the form and selects the picture for upload. 2. The script then validates the given details and checks the uploaded file is in fact a image. 3. The script then moves the uploaded file to the storage location on the server. 4. Some basic SQL is then run to transfer the given details and the storage location to the database. Here is the main script: <?php require_once('../includes/Sentry.php'); $theSentry = new Sentry(); $loc = "http://" . $HTTP_HOST . $PATH_INFO; if (!$theSentry->checkLogin(4) ){ header("Location: login.php?loc=".$loc.""); die(); } // Get the PHP file containing the DbConnector class require_once('../includes/DbConnector.php'); require_once('../includes/Validator.php'); // Create an instance of DbConnector $connector = new DbConnector(); global $HTTP_POST_FILES; // Check whether a form has been submitted. If so, carry on if ($HTTP_POST_VARS){ // Validate the entries $validator = new Validator(); $validator->validateTextOnly($HTTP_POST_VARS['title'],'Picture Title'); $validator->validateTextOnly($HTTP_POST_VARS['alttext'],'Alt Text'); $validator->validateFile($HTTP_POST_FILES['uploaded_file'],'Uploaded File'); // Check whether the validator found any problems if ( $validator->foundErrors() ){ echo '<center>There was a problem with: <br/><br/>'.$validator->listErrors('<br></center'); // Show the errors, with a line between each }else{ $target_path = "../images/Pictures/".basename( $_FILES['uploaded_file']['name']).""; if (!file_exists($target_path)) { if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploaded_file']['name']). " has been uploaded"; 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 />"; } else{ echo "<center>There was an error uploading the file, please try again! <br/><br/></center>"; } } else{ echo "<center>This file already exists, please rename file and try again. </center>"; } // Create an SQL query (MySQL version) // The 'addslashes' command is used 5 lines below for added security // Remember to use 'stripslashes' later to remove them (they are inserted in front of any // special characters $insertQuery = "INSERT INTO cmspictures (Title,Alt Text,uploaded_file) VALUES (". "'".$HTTP_POST_VARS['title']."', ". "'".$HTTP_POST_VARS['alttext']."', ". $target_path."')"; // Save the form data into the database if ($result = $connector->query($insertQuery)){ // It worked, give confirmation echo '<center><b>Picture added to the database</b></center><br /><br />'; echo "<center><b>File Name:</b> ".$_FILES['uploaded_file']['name'].""; }else{ // It hasn't worked so stop. Better error handling code would be good here! exit('<center>Sorry, there was an error saving to the database</center>'); } } } ?> <body> <form name="addPicture" method="post" action="newPicture.php" formenctype="multipart/form-data"> <p> Title: <input name="title" type="text" id="title" /> </p> <p> Alternative Text (If the picture fails to show e.g. Image of Cat): <input name="alttext" type="text" id="altext" /> </p> <p> Image File: <input name="uploaded_file" id="uploaded_file" type="file" /> </p> <p align="center"> <input type="submit" name="Submit" value="Upload Picture"> </p> </form> And here is the validation script: <?php require_once 'SystemComponent.php'; class Validator extends SystemComponent { var $errors; // A variable to store a list of error messages // Validate something's been entered // NOTE: Only this method does nothing to prevent SQL injection // use with addslashes() command function validateGeneral($theinput,$description = ''){ if (trim($theinput) != "") { return true; }else{ $this->errors[] = $description; return false; } } // Validate text only function validateTextOnly($theinput,$description = ''){ $result = ereg ("^[A-Za-z0-9\ ]+$", $theinput ); if ($result){ return true; }else{ $this->errors[] = $description; return false; } } // Validate text only, no spaces allowed function validateTextOnlyNoSpaces($theinput,$description = ''){ $result = ereg ("^[A-Za-z0-9]+$", $theinput ); if ($result){ return true; }else{ $this->errors[] = $description; return false; } } // Validate Filenames function validateFile($theinput,$description = ''){ $allowedextensions = array("jpg", "png", "gif", "bmp", "tif", "JPG", "PNG", "GIF", "BMP", "TIF"); $file_ext = substr($theinput, strripos($theinput, '.')+1); if (in_array($file_ext, $allowedextensions)) { return true; }else{ $this->errors[] = "<center>You can only upload picture files with the extensions .jpg, .png, .bmp, .tif<br/> Yours was: ".$file_ext."</center>"; return false; } } // Validate email address function validateEmail($themail,$description = ''){ $result = ereg ("^[^@ ]+@[^@ ]+\.[^@ \.]+$", $themail ); if ($result){ return true; }else{ $this->errors[] = $description; return false; } } // Validate numbers only function validateNumber($theinput,$description = ''){ if (is_numeric($theinput)) { return true; // The value is numeric, return true }else{ $this->errors[] = $description; // Value not numeric! Add error description to list of errors return false; // Return false } } // Validate date function validateDate($thedate,$description = ''){ if (strtotime($thedate) === -1 || $thedate == '') { $this->errors[] = $description; return false; }else{ return true; } } // Check whether any errors have been found (i.e. validation has returned false) // since the object was created function foundErrors() { if (count($this->errors) > 0){ return true; }else{ return false; } } // Return a string containing a list of errors found, // Seperated by a given deliminator function listErrors($delim = ' '){ return implode($delim,$this->errors); } // Manually add something to the list of errors function addError($description){ $this->errors[] = $description; } } ?> Any help in resolving this issue would be greatly appreciated. mrenigma 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 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 |