PHP - File Upload Form And Script On Same Page Not Working
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! Similar TutorialsI'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> Hello, all: been trying to convert this little single-file upload to multiple by naming each file form-field as "userfile[]" as it's supposed to automatically treat them as an array.. but no luck! Can you guide me as to what am I doing wrong?? appreciate the help! Code: [Select] <?php if (!isset($_REQUEST["seenform"])) { ?> <form enctype="multipart/form-data" action="#" method="post"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> Upload file: <input name="userfile[]" type="file" id="userfile[]"> <input type="submit" value="Upload"> <input type="hidden" name="seenform"> </form> <?php } else { // upload begins $userfiles = array($_FILES['userfile']); foreach ($userfiles as $userfile) { // foreach begins $uploaded_dir = "uploads/"; $userfile = $_FILES['userfile']["name"]; $path = $uploaded_dir . $userfile; if (move_uploaded_file($_FILES['userfile']["tmp_name"], $path)) { print "$userfile file moved"; // do something with the file here } else { print "Move failed"; } } // foreach ends } // upload ends ?> 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); } ?>
I have a form that includes uploading a headshot. This is the form handling f ($_SERVER['REQUEST_METHOD']=='POST'){ $fn = $_POST['fname']; $ln = $_POST['lname']; $ad1 = $_POST['ad1']; $ad2 = $_POST['ad2']; $city = $_POST['city']; $post = $_POST['postcode']; $tel = $_POST['phone']; $email = $_POST['email']; $crole = $_POST['comRole']; $OFA = $_POST['OFA']; $playerType = $_POST['playerType']; $team = $_POST['primaryTeam']; $dob = $_POST['dateOfBirth']; if(!empty($_FILES['fileToUpload'])){ $errors= array(); $file_name = $_FILES['personHeadshot']['name']; $file_size =$_FILES['personHeadshot']['size']; $file_tmp =$_FILES['personHeadshot']['tmp_name']; $file_type=$_FILES['personHeadshot']['type']; $file_ext=strtolower(end(explode('.',$_FILES['personHeadshot']['name']))); $newFileName = $fn."-".$ln.".".$file_ext; $extensions= array("jpeg","jpg","png"); if(in_array($file_ext,$extensions)=== false){ $errors[]="extension not allowed, please choose a JPEG or PNG file."; } if($file_size > 2097152){ $errors[]='File size must be smaller than 2 MB'; } if(empty($errors)==true){ move_uploaded_file($file_tmp,"img/people/".$newFileName); echo "Success"; }else{ print_r($errors); } $personHeadshot = $newFileName; } $stmt = $conn->prepare(" INSERT IGNORE INTO person (fname, lname, committee_role_id, player_type_id, team_id, ad1, ad2, city, postcode, mobile, email, on_field_auth_id, image, dob) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param('ssiiissssssiss', $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA, $personHeadshot, $dob); $stmt -> execute(); header("location: admin-people-list.php"); } I also have this file <?php $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> This was working locally but now i have uploaded it i cannot get it to work. All of the person data gets put into the DB asside from the file name I appreciate you may need more info to help me which i will provide on request I can't seem to get this file system to upload. It's returning an error about directory not writable. I have also verified it's 777 on the server, so I know permissions are right. File Class Code: [Select] <?php /** * Uploader is a file transfer class. it can upload files and images. * It also can resize and crop images. * Works on PHP 5 * @author Alaa Al-Hussein * @link http://www.freelancer-id.com/projects * @version 1.0 * */ class uploader{ /** * Array, The file object as $_FILES['element']. * String, file location. */ public $source; /** * Destination file location as folder. */ public $destDir; /** * Directory for Resized images. */ public $resizeDir; /** * Directory for Cropped images. */ public $cropDir; /** * stores information for uploading file */ private $info = ''; /** * Enabling autoName will generate an auto file name for the uploaded file. */ public $generateAutoName = true; /** * Handles the error when it occurs. */ private $errorMsg = ''; /** * new width for resizing and cropping. */ public $newWidth; /** * new height for resizing and cropping. */ public $newHeight; /** * TOP postion to cropping image. */ public $top = 0; /** * LEFT position for cropping image. */ public $left = 0; /** * JPG quality (0 - 100). used for image resizing or cropping. */ public $quality = 60; public function __construct(){ //nothing } /** * Uploads the file to the server. * @param Array $_FILES[] */ public function upload($source){ if($source != ""){ $this->source = $source; } if(is_array($this->source)){ if($this->fileExists()){ return false; } // Check for auto-name generation. If it's set then generate the name automatically. if ($this->generateAutoName == true) { $this->autoName(); } return $this->copyFile(); } else { return $this->source; } } /** * return the error messages. * @return String messages. */ public function getError(){ return $this->errorMsg; } /** * Get uploading information. */ public function getInfo(){ return $this->info; } /** * Auto Name */ private function autoName() { $num = rand(0, 2000000); $num2 = rand(0, 2000000); $this->source['name'] = $num . $num2 . $this->source['name']; return $this->source; } /** * Get Image Sizes * Returns an array of variables pertaining to properties of the image. * USE THIS ON IMAGES ONLY */ public function getImageSize() { // Get the size information of the provided image. $image_size = getimagesize($this->getTemp()); // Setup the height/width so they can be returned in a readable format $return_array['width'] = $image_size[0]; $return_array['height'] = $image_size[1]; // Return the array of new data. return $return_array; } /** * Copy the uploaded file to destination. */ private function copyFile(){ if(!$this->isWritable()){ $this->errorMsg .= '<div>Error, the directory: ('.$this->destDir.') is not writable. Please fix the permission to be able to upload.</div>'; return false; } if(copy($this->source['tmp_name'],$this->destDir . $this->source['name'])){ // Done. $this->info .= '<div>file was uploaded successfully.</div>'; } else { $this->errorMsg .= '<div>Error, the file was not uploaded correctly because of an internal error. Please try again, if you see this message again, please contact web admin.</div>'; } } /** * Checks if the file was uploaded. * @return boolean */ private function uploaded(){ if($this->source['tmp_name']=="" || $this->source['error'] !=0){ $this->errorMsg .= '<div>Error, file was not uploaded to the server. Please try again.</div>'; return false; } else return true; } /** * Prepares the directory. */ private function preDir(){ if($this->destDir!="" && substr($this->destDir, -1,1) != "/"){ $this->destDir = $this->destDir . '/'; } if($this->resizeDir!="" && substr($this->resizeDir, -1,1) != "/"){ $this->destDir = $this->resizeDir . '/'; } if($this->cropDir!="" && substr($this->cropDir, -1,1) != "/"){ $this->destDir = $this->cropDir . '/'; } } /** * Check if the folder is writable or not. * @return boolean */ private function isWritable(){ $err = false; if(!is_writeable($this->destDir) && $this->destDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->destDir.') is not writeable. File could not be uploaded.</div>'; $err = true; } if(!is_writeable($this->resizeDir) && $this->resizeDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->resizeDir.') is not writeable. File could not be resized.</div>'; $err = true; } if(!is_writeable($this->cropDir) && $this->cropDir!=""){ $this->errorMsg .= '<div>Error, the directory ('.$this->cropDir.') is not writeable. File could not be cropped.</div>'; $err = true; } if($err == true){ return false; } else { return true; } } /** * Checks if the file exists on the server * @return boolean */ private function fileExists(){ $this->preDir(); if(file_exists($this->destDir.$this->source)){ $this->errorMsg .= '<div>Upload error because file already exists.</div>'; return true; } else { return false; } } /** /586742130./8532 Crops image. * @return String fileName or False on error */ public function crop($file='',$width='',$height='',$top='',$left=''){ if($file!=""){ $this->source = $file;} if ($width != '') $this->newWidth = $width; if ($height != '') $this->newHeight = $height; if ($top != '') $this->top = $top; if ($left != '') $this->left = $left; return $this->_resize_crop(true); } /** * Resizes an image. * @return String fileName or False on error */ public function resize($file='',$width='',$height=''){ if($file!=""){ $this->source = $file; } if($width != '') $this->newWidth = $width; if($height != '') $this->newHeight = $height; return $this->_resize_crop(false); } /** * Get the Temp file location for the file. * If the Source was a file location, it returns the same file location. * @return String Temp File Location */ private function getTemp(){ if(is_array($this->source)){ return $this->source['tmp_name']; } else { return $this->source; } } /** * Get the File location. * If the source was a file location, it returns the same file location. * @return String File Location */ private function getFile(){ if(is_array($this->source)){ return $this->source['name']; } else { return $this->source; } } /** * Resize or crop- the image. * @param boolean $crop * @return String fileName False on error */ private function _resize_crop ($crop) { $ext = explode(".",$this->getFile()); $ext = strtolower(end($ext)); list($width, $height) = getimagesize($this->getTemp()); if(!$crop){ $ratio = $width/$height; if ($this->newWidth/$this->newHeight > $ratio) { $this->newWidth = $this->newHeight*$ratio; } else { $this->newHeight = $this->newWidth/$ratio; } } $normal = imagecreatetruecolor($this->newWidth, $this->newHeight); if($ext == "jpg") { $src = imagecreatefromjpeg($this->getTemp()); } else if($ext == "gif") { $src = imagecreatefromgif ($this->getTemp()); } else if($ext == "png") { $src = imagecreatefrompng ($this->getTemp()); } if($crop){ //$pre = 'part_'; //We want to overwrite file, so comment this out. if(imagecopy($normal, $src, 0, 0, $this->top, $this->left, $this->newWidth, $this->newHeight)){ $this->info .= '<div>image was cropped and saved.</div>'; } $dir = $this->cropDir; } else { //$pre = 'thumb_'; //We want to overwrite file, so comment this out. if(imagecopyresampled($normal, $src, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height)){ $this->info .= '<div>image was resized and saved.</div>'; } $dir = $this->resizeDir; } if($ext == "jpg" || $ext == "jpeg") { imagejpeg($normal, $dir . $pre . $this->getFile(), $this->quality); } else if($ext == "gif") { imagegif ($normal, $dir . $pre . $this->getFile()); } else if($ext == "png") { imagepng ($normal, $dir . $pre . $this->getFile(),0); } imagedestroy($src); return $src; } } /* Examples Section */ /* Let me explain first how to manage an image to be uploaded and then to be cropped or resized. <?php $uploader = new uploader(); // Setting properties then Uploading the image $uploader->source = $_FILES['field_image']; $uploader->destDir = "images/"; $uploader->upload(); // ===================== // Or you may use this too $uploader->destDir = "images/"; $uploader->upload($_FILES['field_image']); ?> Note: upload() returns the file name uploaded. To get error messages, use this code: <?php echo $uploader->getError(); // This function will return all errors occured while uploading the image. But it's not printing it to print it where ever you want. ?> And to get Information messages use this code: <?php echo $uploader->getInfo(); // This function will return all information to let the user print it where ever he wants. ?> After uploading this image, we may resize it. To do that use the following code: <?php $uploader->newWidth = 75; // in Pexels. $uploader->newHeight = 75; $uploader->resizeDir = "images/resized/"; $uploader->resize(); ?> You may also use this syntax: <?php // $uploader->resize($file,$width,$height); // $file could has a value of "" (nothing), in this case we use the last uploader file. // if the $file has a String value (file url) it will resize this new file. $uploader->resizeDir = "images/resized/"; $uploader->resize('',75,75); // Or you may upload and resize in the same line: $uploader->resizeDir = "images/resized/"; $uploader->resize($uploader->upload(),75,75); ?> Crop this image after uploading it: <?php $uploader->cropDir = "images/cropped/"; $uploader->newWidth = 75; $uploader->newHeight = 75; $uploader->top = 20; // Default is ZERO.. This used to set the cropping top location from the original image. $uploader->left = 40; // Default is ZERO.. This used to set the cropping left location from the original image. $uploader->crop(); // You may also use this: // $uploader->crop($file,$width,$height,$top,$left); $uploader->cropDir = "images/cropped/"; $uploader->crop('',75,75,20,40); ?> */ ?> Upload Function Code: [Select] <?php /* END STANDARD FUNCTIONS */ /* General function to deal with image uploads site_wide. */ function upload_image($file, $dir, $table, $fieldname, $id, $exists, &$data) { // Get image information if ($file['tmp_name'] != '' && $file['name'] != '') { if ($exists == 1) { // Delete Associated Image $imageSQL = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '" . $id . "'"; $imageQuery = mysql_query($imageSQL); while($row = mysql_fetch_array($imageQuery, MYSQL_ASSOC)) { if ($row[$fieldname] != '') { $tmpdirectory = '../assets/' . $dir . '/'.$row[$fieldname]; if (file_exists($tmpdirectory)) { unlink($tmpdirectory); } } } } $directory = '../assets/' . $dir . '/'; // Default DIR // Upload $uploader = new uploader; $uploader->destDir = $directory; $uploader->generateAutoName = true; $file_name = $uploader->upload($file); $image_sizes = $uploader->getImageSize(); echo $uploader->getInfo(); } // Check if image was uploaded and if so database name. if ($uploader->source['name'] != '') { $data[$fieldname] = $uploader->source['name']; }else { if ($exists == 1) { $tmpSelect = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '".$id."'"; $tmpQuery = mysql_query($tmpSelect); if ($row = mysql_fetch_array($tmpQuery, MYSQL_ASSOC)) { $data[$fieldname] = $row[$fieldname]; }else { $data[$fieldname] = NULL; } }else { $data[$fieldname] = NULL; } } } ?> Code to call function Code: [Select] <?php // Upload all images $picture_1 = $_FILES['picture_one']; if ($picture_1['tmp_name'] != '' && $picture_1['name'] != '') { $functions->upload_image($picture_1, 'product_pictures', 'products', 'picture_1', $product_id, $exists, &$data); } ?> At this point I have done all of the debugging I can and it's not working out. Any advice is appreciated. Hi Guys, I found this upload script a while ago and I'm sure the last time I used it, it worked perfectly but for some reason '$path1' keeps returning as blank. I'm not very good with file uploads, can anyone help me out please? Code: [Select] if ($_POST['customBackground']) { $path1= '/upload/' . date(U). $HTTP_POST_FILES['customBackground']['name'][0]; if(empty($path1)) { $message = '<p class="red size10font">Background field cannot be blank!</p>';} else { //copy file to where you want to store file copy($HTTP_POST_FILES['customBackground']['tmp_name'][0], $path1); } } The field it is being populated from is <input class="fullwidth biggun" name="customBackground" type="file" id="customBackground" size="70" value=""> Thank you in advance. Hello, I'm planning on making a website where people are able to upload files and directly link to them. Ideally, I want to keep the same file names that the people use when they upload the file. I was planning on keeping the directory that stored all of the files outside of the www directory and disable execute permissions. However, how would I avoid file overwriting with the same file name? Hello Everyone, I have been working on this add product script but cannot seem to get it to work when two files are uploaded. All the data is uploaded to a database, including the two images filenames and then the two files are added to the server to different locations. Here is the form: <form action="addnewproduct.php" method="post" name="addproduct" id="addproduct" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="10000000"> <table width="98%" border="0" cellspacing="0" cellpadding="5"> <tr> <td width="28%" valign="middle" class="style1 style2"><div align="right" class="style5">Product Title </div></td> <td width="72%" class="style5"><input class="form" type="text" name="title" accesskey="1" tabindex="1" /></td> </tr> <tr> <td valign="middle" class="style1 style2"><div align="right" class="style5">Category</div></td> <td class="style5"> <select class="form" name="cat" accesskey="2" tabindex="2"> <option value="Boards">Boards</option> <option value="Accessories">Accessories</option> <option value="Clothing">Clothing</option> </select> </td> </tr> <tr> <td valign="top" class="style5"><div align="right">Description</div></td> <td class="style5"><textarea class="form" name="description" cols="50" rows="5" accesskey="3" tabindex="3"></textarea></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Price<br /> <span class="d">Including </span></div></td> <td class="style5"><input class="form" type="text" name="price" accesskey="4" tabindex="4" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Paypal Link<br /> <span class="d">Including</span></div></td> <td class="style5"><input class="form" type="text" name="paypal" accesskey="5" tabindex="5" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right">Thumbnail<br /> <span class="d">Image should be 100 x 100 </span></div></td> <td class="style5"> <input style="padding:2px; border:1px #999 solid; color:blue;" name="userfile[]" type="file" id="userfile[]"> </td> </tr> <tr> <td valign="top" class="style5"><div align="right">Image<br /> <span class="d">Image should be 300 x 450 </span></div></td> <td class="style5"><input style="padding:2px; border:1px #999 solid; color:blue;" name="userfile[]" type="file" id="userfile[]" /></td> </tr> <tr> <td valign="top" class="style5"><div align="right"></div></td> <td class="style5"><input class="form" type="submit" name="upload" value="upload" accesskey="6" tabindex="6" /></td> </tr> </table> </form> And here is the script: <?php $uploadDir = 'upload/'; $uploadDir2= "upload/big".$HTTP_POST_FILES['userfile']['name'][1]; copy($HTTP_POST_FILES['userfile']['tmp_name'][1], $uploadDir2); if(isset($_POST['upload'])) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $largeimage = $_FILES['userfile']['name'][1]; $filePath = $uploadDir . $fileName; $result = move_uploaded_file($tmpName, $filePath); if (!$result) { echo "Error uploading file"; exit; } include 'config.php'; include 'opendb.php'; if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); $largeimage = addslashes($largeimage); } $query = "INSERT INTO Products (title, description, price, paypal, cat, image, large) ". "VALUES ('$_POST[title]','$_POST[description]','$_POST[price]','$_POST[paypal]','$_POST[cat]','$fileName','$largeimage')"; mysql_query($query) or die('Error, query failed : ' . mysql_error()); include 'closedb.php'; echo 'Product Uploaded'; ?> I have been searching for an answer for several days but have not yet resolved my problem. Essentiallty I started out looking for an image upload script then slowly went towards just a basic upload script. Each time I try a new script I am getting the same error. My folder permissions are set, file uploads is enabled, safe mode is disabled. As of right now my page is giving me an error that says 'Failed to open stream' My existing code: Code: [Select] <?php $target = "images/"; $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; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP 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."; } } ?> <form enctype="multipart/form-data" action="uploader.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> You for testing purposes I have made my temporary upload page available for you to view and help disgnose the issue: http://www.sophienoelle.me/uploader.php also you can find the phpinfo at http://www.sophienoelle.me/phpinfo.php If you need further information than what I have supplied please let me know and I will be available to provide what you are requesting. If you have a suggestion I will gladly take it. Any steps I can get to uploading images the better. where is the problem? http://pastebin.com/Smw92nd5 I'm looking for the folder where the uploaded file should be but it doesn't exist, it seems that the condition "if($ext == $need)" is ignored Hi, I'm a PHP beginner using Julie Meloni Sams Teach yourself to help me. My confusion is with this script <?php $file_dir ="/path/to/upload/directory" ; foreach($_FILES as $file_name => $file_array) { echo "path: ".$file_array["tmp_name"]."<br/>\n" ; echo "name: ".$file_array["name"]."<br/>\n" ; echo "type: ".$file_array["type"]."<br/>\n" ; echo "File name is" . " ". $file_name ; } ?> What I don't understand is the foreach statement foreach($_FILES as $file_name => $file_array) $_FILES is an associative array, right? So $filename should represent the key id and $file_array the value. but she is using the $file_array as if it is an array and accessing the values with associative index which confuses. I mean, let's say I declared a normal array. $array = array("Sarah" => "Jane", "John Smith") ; if i wanted to use a foreach loop i would do it like so foreach($array as $fname => $surname) { echo $fname ; echo $surname ; } $fname will print the first name and surname surname. I didn't use an indices to access the values. foreach($_FILES as $file_name => $file_array) can someone explain this to me? Thanks Good Evening, If anyone could help with this little problem be much appreciated. what i'm trying to do is using a drop down menu select a folder name which is stored in a database table.. then taking that folder name and upload various files to that specified folder. There's probably an easier way to do this but i've searched google argggh.. The first part of code is the php to grab the folder names and the file selection form Code: [Select] <?php include("connection.php"); $sql="SELECT id, name FROM gallery"; $result=mysql_query($sql); $options=""; while ($row=mysql_fetch_array($result)) { $id=$row["id"]; $thing=$row["name"]; $options.="<OPTION VALUE=\"$id\">".$thing ; } ?> <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form action="postFiles.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td><strong>multiple Files Upload </strong></td> </tr> <td><SELECT NAME=thing> <OPTION VALUE=0>Choose <?=$options?> </SELECT> </td> <tr> <td>Select file <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <td>Select file <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <td>Select file <input name="ufile[]" type="file" id="ufile[]" size="50" /></td> </tr> <tr> <td align="center"><input type="submit" name="Submit" value="Upload" /></td> </tr> </table> </td> </form> </tr> </table> The second part of the code below is the php code to upload those files, the problem being how do i specify the upload destination using the drop down in the previous form (instead of UPLOAD) which it is default set to Code: [Select] <?php //set where you want to store files //in this example we keep file in folder upload //$HTTP_POST_FILES['ufile']['name']; = upload file name //for example upload file name cartoon.gif . $path will be upload/cartoon.gif $path1= "upload".$HTTP_POST_FILES['ufile']['name'][0]; $path2= "upload".$HTTP_POST_FILES['ufile']['name'][1]; $path3= "upload".$HTTP_POST_FILES['ufile']['name'][2]; //copy file to where you want to store file copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1); copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2); copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3); //$HTTP_POST_FILES['ufile']['name'] = file name //$HTTP_POST_FILES['ufile']['size'] = file size //$HTTP_POST_FILES['ufile']['type'] = type of file echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>"; echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]."<BR/>"; echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>"; echo "<img src=\"$path1\" width=\"150\" height=\"150\">"; echo "<P>"; echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>"; echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>"; echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>"; echo "<img src=\"$path2\" width=\"150\" height=\"150\">"; echo "<P>"; echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>"; echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>"; echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>"; echo "<img src=\"$path3\" width=\"150\" height=\"150\">"; /////////////////////////////////////////////////////// // Use this code to display the error or success. $filesize1=$HTTP_POST_FILES['ufile']['size'][0]; $filesize2=$HTTP_POST_FILES['ufile']['size'][1]; $filesize3=$HTTP_POST_FILES['ufile']['size'][2]; if($filesize1 && $filesize2 && $filesize3 != 0) { echo "We have recieved your files"; } else { echo "ERROR....."; } ////////////////////////////////////////////// // What files that have a problem? (if found) if($filesize1==0) { echo "There're something error in your first file"; echo "<BR />"; } if($filesize2==0) { echo "There're something error in your second file"; echo "<BR />"; } if($filesize3==0) { echo "There're something error in your third file"; echo "<BR />"; } ?> Thanks in advance for any help if you need to see a live version of these files i can provide a link Hi: Is it possible to use the ereg() function in a file upload script so that the ereg() can recognize whether or not the file type is a .jpg, .gif, .png? I already figured out how to do it without using the ereg() function - but I'm just interested to know if it is possible using ereg()..if so, could you provide me with an example? I'm also a bit confused as to how to use ereg() to recognize file types. Here;s what I've done: Code: [Select] function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } Thanks! Hello everyone. I'm posting because I'm having difficulty using a file upload script I wrote in PHP. (Based on a tutorial naturally.) May someone more skilled than I could take a look at it? Form: (simple, no ajax or jquery involved. I'll add that later.) Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> <table><tr><td>File</td><td><input name="uploaded" type="file" /></td></tr> <tr><td colspan="2"><input type="submit" value="Upload" style="float:right;" /></td></tr></table> </form> Upload Script: Code: [Select] <? session_start(); include('include/session.php'); /*IMAGE*/ $target = "upload/"; $target = $target . basename($_FILES['uploaded']['name']); $name = basename( $_FILES['uploaded']['name']); $ok=1; global $database; //This is our size condition if ($uploaded_size > 350000000) { echo "Your file is too large.<br>"; $ok=0; } //This is our limit file type condition if ($uploaded_type =="text/php") { echo "No PHP 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)) { $channel_number = $_SESSION['channel_number']; $n = "INSERT INTO `documents` (`name`,`channel_number`) VALUES ('$name','$channel_number')"; mysql_query($n); header("Location:index.php"); } else { echo "Sorry, there was a problem uploading your file."; } } ?> The mysql query works fine, and it's just so that I can keep track of the uploads. I'm well aware this is not a secure script, btw. I'm just doing it to learn. Hi, I have exactly the same script and same php.ini file like this website : https://translatesubtitles.com and as you can see the proccess of that php website is: upload srt file redirection to translate.php file where the uploaded text is shown in the table my website script is : https://translatesubtitles.co and when I try to upload srt file it redirected me to the translate.php page but there is no text shown in the table, so what can be the problem? ...and the file is to be copied into a folder created by me. I was wondering what the file path would be for Windows, since it does not seem to recognise the file path that I have chosen: Upload Form code: Code: [Select] <html> <head><title>Car Accident Report Uploader</title></head> <body> <form action="fileuploadform.php" method="post" enctype="multipart/form-data"> <input type="file" size="45" name ="file"><br> <input type="submit" value = "Upload Car Accident Report"> </form> </body> </html> Copying Script Code: Code: [Select] <?php if ($_FILES['file']['name'] !="") { copy ($_FILES['file']['tmp_name'], 'C:\xampp\htdocs\rcm' . $_FILES['file']['name']) or die ("Could not copy Car Accident Report Form"); } else {die ("No Car Accident Report Form has been chosen");} ?> <html> <head><title>Car Accident Report Form Upload Complete</title></head> <body><h3>Car Accident Report Form has been uploaded</h3> <ul> <li>Sent: <?php echo $_FILES['file']['name']; ?> <li>Size: <?php echo $_FILES['file']['size']; ?> bytes <li>Type: <?php echo $_FILES['file']['type']; ?> <a href = "<?php echo $_FILES['file']['name']; ?>"> Click here to view the Car Accident Report Form</a> </body> </html> If anyone can help me find the relevant file path, it would be appreciated! I am in the process of creating a script where only certains video types can be uploaded but at the moment am stuck.
Here is my code -
<?php $title = isset($_POST['title']) ? $_POST['title'] : null; $desc = nl2br(isset($_POST['description'])) ? $_POST['description'] : null; $name = isset($_POST['fullname']) ? $_POST['fullname'] : null; $email = isset($_POST['email']) ? $_POST['email'] : null; $country = isset($_POST['country']) ? $_POST['country'] : null; $video = isset($_FILES['video']); $videoname = isset($_FILES['video']['name']); $videotmp = isset($_FILES['video']['tmp_name']); $videosize = isset($_FILES['video']['size']); $videotype = isset($_FILES['video']['type']); $videoacceptable = array( "video/mp4", "video/ogg", "video/quicktime", ); $videopath = "/videos/"; $videofile = $videopath . $video; if(isset($_POST['submit'])) { //ERROR MESSAGES / VALIDATION if(empty($title)) { $errors[] = "A title is required"; echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($title) > 80) { $errors[] = "Your title can only be 80 characters long"; echo "<style type=\"text/css\"> #title { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($desc)) { $errors[] = "A description is required"; echo "<style type=\"text/css\"> #description { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($name)) { $errors[] = "Please enter your full name"; echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($name) > 32) { $errors[] = "Your name can only be 32 characters long"; echo "<style type=\"text/css\"> #fullname { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if(empty($email)) { $errors[] = "Please enter your email address"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif(strlen($email) > 50) { $errors[] = "Your email addess can only be 50 characters long"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Please enter a valid email address"; echo "<style type=\"text/css\"> #email { background-color:#F5A9A9;border:1px solid #DF0101; } </style>"; } if($videosize = 0) { $errors[] = "You forgot to upload a video"; } elseif($videosize >= 20000000) { $errors[] = "Your video size is too large, 20mb max"; } elseif(!in_array($videotype, $videoacceptable)) { $errors[] = "The file type is not allowed, only allowed .mp4, .ogg and .mov"; } if(count($errors) === 0) { $connect = mysqli_connect("localhost","username","password"); if(!$connect) { header("Location:"); // ADD ERROR LINK } $dbselect = mysqli_select_db("database"); if(!$dbselect) { header("Location:"); // ADD ERROR LINK } $query = mysqli_query("INSERT INTO cover_videos(title, desc, name, email, country, videotmp, videotype, videosize, videopath) VALUES('$title','$desc','$name','$email','$country','$videotmp','$videotype','$videosize','$videopath')"); move_uploaded_file($videotmp, $videofile); //SEND AN EMAIL TO THE USER $to = $email; $subject = "Thank's for your upload"; $message = ' <html> <head><title>We have received your video</title></head> <body> <h3>Good News!</h3> <p>We have recieved your video and is awaiting approval.</p> </body> </html> '; $headers = 'FROM: no-replyk' . "\r\n"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers = 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); header("Location:"); //SUCCESSFUL UPLOAD PAGE } } ?>So whats happening is when i go to upload a file, im uploading a .mov file but the error message that pops up is "The file type is not allowed, only allowed .mp4, .ogg and .mov" but the .mov mime is in the videoacceptable array so im a bit stuck at the moment, any know whats the problem? Hi all, This is my very first post here, so I will try and make it count Very recently I have been working with php and I found this simple little script that allows users to upload files. I tweaked some things to only make it upload .doc files but now I have a slight problem. Every time someone uploads a word file with the same name, it gets replaced. I tried looking for other examples here on the forum, but was unable to apply it to my own script. It would be a big help if someone could provide a simple add-on to this existing script. Thanks in advance. Script: <? $locatie="upload/"; $toegestaan = "doc"; $max_size = 1000000; set_time_limit(0); if(isset($_POST['upload'])) { if(is_uploaded_file($_FILES['bestand']['tmp_name'])) { $extensie_bestand = pathinfo($_FILES['bestand']['name']); $extensie_bestand = $extensie_bestand[extension]; $extensies_toegestaan = explode(", ", $toegestaan); for($i = 0; $i < count($extensies_toegestaan); $i++) { if($extensies_toegestaan[$i] == "$extensie_bestand") { $ok = 1; } } if($ok == 1) { if($_FILES['bestand']['size']>$max_size) { echo "Het bestand is te groot, de maximale grootte is: <b>$max_size</b>"; exit; } if(!move_uploaded_file($_FILES['bestand']['tmp_name'], $locatie.$_FILES['bestand']['name'])) { echo "het bestand kan niet worden verplaatst"; exit; } echo "Het bestand ".$_FILES['bestand']['name']." is geupload<br> <a href='".$locatie."".$_FILES['bestand']['name']."' </a>"; } else { echo "Verkeerde extentie, de toegestane extensies zijn: <b>$toegestaan</b>"; } } else { echo "Het uploaden is mislukt, probeer het opnieuw"; } } ?> <title>test tittle</title> <style type="text/css"> <!-- body { margin-top: 0px; } --> </style></head> <body> <table width="1216" height="1191" border="0" cellpadding="0" cellspacing="0" background="back"> <tr> <td height="317" colspan="2"> </td> </tr> <tr> <td height="381"> </td> <td><p> </p> <form method="post" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data"> <table width="398" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="180"> </td> <td width="218"><input type="file" name="bestand" /> <input type="submit" name="upload" value="uploaden" /></td> </tr> <tr> <td> </td> <td> </td> </tr> </table> </form></td> </tr> <tr> <td width="420"> </td> <td width="796"> </td> </tr> </table> |