PHP - Upload Script Writing Files Regardless
Hi All,
I need some help blocking files that don't pass authentication from being uploaded to the server. Here is my script (below). It correctly throws errors, but regardless of error / no-error, the file is uploaded. For example, the only files allowed to be uploaded should be .png, .jpeg, .gif -- but I see .flv .docx etc in the destination folder. You'll see below a variable for each of the error messages. They basically say that the file name is too long, too big, not an allowed file type, or English characters only allowed in file title name. Again the errors work properly, but regardless files are uploaded to the "quiz_images" folder. What do I need to do to stop the upload if an error is triggered? Thank you for your help... here is the code snip: Code: [Select] $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']); $uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'quiz_images/'; $fieldname = 'file'; if ($_POST[submit]) { if ($_POST[title] <> "") { $a = TRUE; } else { $a = FALSE; $content .= "<p>$enter_title</p>\n"; } if ($_POST[video] <> "") { $b = TRUE; } else { $b = FALSE; $content .= "<p>$enter_embed</p>\n"; } if ($_POST[description_text] <> "") { $c = TRUE; } else { $c = FALSE; $content .= "<p>$enter_description</p>\n"; } if ($_POST[submit] <> "") { $f = TRUE; } else { $f = FALSE; $content .= "<p>$sorry_error</p>\n"; } if (is_uploaded_file($_FILES[$fieldname]['tmp_name'])) { $g = TRUE; } else { $g = FALSE; $content .= "<p>$sorry_error</p>\n"; } if (getimagesize($_FILES[$fieldname]['tmp_name'])){ $h = TRUE; } else { $h = FALSE; $content .= "<p>$error2</p>\n"; } if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 50000)) { $i = TRUE; } else { $i = FALSE; $content .= "<p>$error2</p>\n"; } if(preg_match('#^[a-z0-9_\s-\.]*$#i', $pic) ) { $k = TRUE; } else { $k = FALSE; $content .= "<p>$error3</p>\n"; } $desc_length = strlen($pic); $limit = 40; if ($desc_length <= $limit) { $l = TRUE; } else { $l = FALSE; $content .= "<p>$error4</p>\n"; } $now = time(); while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'])) { $now++; } if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)){ $j = TRUE; } else { $j = FALSE; $content .= "<p>$enter_thumb</p>\n"; } $pic=$now++.'-'.$_FILES[$fieldname]['name']; if ($a AND $b AND $c AND $f AND $g AND $h AND $i AND $j AND $k AND $l) {............ Similar Tutorialsso what i have going on is that i need help writing a basic script to upload original and copy with resize for thumbnail. then also need to rename both image files with content in the form. My server supports GD Library and that imagemagik or whatever it is lol. upload dirs orig: ../media/photos/ thumb: ../media/photos/thumb/ mySQL DB: name: m_photos fields: id(INT) m_cat(varchar) m_sub_cat(varchar) pic(varchar) description(varchar) p_group(varchar) I have the form written up for how it should look like: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> Upload an image for processing<br /> <input type="file" name="Image"><br /> <select name="sub_group"> <option value="Photo Shoot">Photo Shoot</option> <option value="Live Performances">Live Performances</option> <option value="Randoms">Randoms</option> <option value="Fan Photos">Fan Photos</option> </select><br /> Location: <input type="text" name="p_group" /><br /> Date of Pic: <input type="text" name="date" /><br /> Description: <input type="text" name="description" /><br /> <input type="submit" value="Upload"> </form> so what needs to happen is for the file upload name. it needs to grab a count from "p_group" database to give it a starting number in a "00" pattern and then the date of pic needs to go in there next then the p_group name. so when the files gets uploaded it would look something like this after upload. "03 - Oct 21, 2011 - The Mex.jpg" NOTE: all pics must be converted to ".jpg" extension. both the orig and thumb will use that same file name cuz they just go into different dirs re-sizing for the thumbnail should be done by aspect ratio and needs to either be 300px width or 400px height. so if anyone would like to help me out please do. im not the greatest at writing in php yet <!doctype html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <title>Untitled Document</title> </head> <body> <form action="upload_image.php" method="post" enctype="multipart/form-data"> <label>select page<input type="file" name="image"> <input type="submit" name="upload"> </label> </form> <?php if(isset($_POST['upload'])) { $image_name=$_FILES['image']['name']; //return the name ot image $image_type=$_FILES['image']['type']; //return the value of image $image_size=$_FILES['image']['size']; //return the size of image $image_tmp_name=$_FILES['image']['tmp_name'];//return the value if($image_name=='') { echo '<script type="text/javascript">alert("please select image")</script>'; exit(); } else { $ex=move_uploaded_file($image_tmp_name,"image/".$image_name); if($ex) { echo 'image upload done "<br>"'; echo $image_name.'<br>'; echo $image_size.'<br>'; echo $image_type.'<br>'; echo $image_tmp_name.'<br>'; } else { echo 'error'; } } } ?> </body> </html>I make this simple script for upload files like photo , It's work correctly ,but not upload the large files ex 8MB images 12MB images Edited by Ch0cu3r, 04 October 2014 - 09:50 AM. Modified topic title - changed download to upload Hi all, I am having a few problems. Basically I have a multiple file upload script, that I can get successfully to save the images to a folder. However what I am trying to do is enter a record in the database for every file that is uploaded, giving it a picture id, album id and user id (p_id, a_id, u_id). From here I then want to rename the image to the p_id in the database(auto_increment). I am starting just by counting the amount of images uploaded and then creating a record. However I seem to have something wrong, as when I tried it to upload 1 image as a test it created 388,000 blank records! (just p_id as auto) Can someone explain what I am doing wrong? I am quite new to php. <?php $result = array(); $result['time'] = date('r'); $result['addr'] = substr_replace(gethostbyaddr($_SERVER['REMOTE_ADDR']), '******', 0, 6); $result['agent'] = $_SERVER['HTTP_USER_AGENT']; if (count($_GET)) { $result['get'] = $_GET; } if (count($_POST)) { $result['post'] = $_POST; } if (count($_FILES)) { $result['files'] = $_FILES; } // we kill an old file to keep the size small if (file_exists('script.log') && filesize('script.log') > 102400) { unlink('script.log'); } $log = @fopen('script.log', 'a'); if ($log) { fputs($log, print_r($result, true) . "\n---\n"); fclose($log); } // Validation $error = false; if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) { $error = 'Invalid Upload'; } else { include('../includes/config.php'); session_start(); $a_id = $_SESSION["a_id"]; $u_id = $_SESSION["id"]; $togo = $result['files']; $i=0; while ($i < $togo) { $query = mysql_query("INSERT into images (a_id,u_id) VALUES ('$a_id','$u_id')"); $i++; } } ?> Many Thanks So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png file which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is? im trying to make a program that changes some files from 0 to 1,but im having some trouble... heres my code, Code: [Select] $id = $_GET["id"]; $file1 = "http://mysite.co.cc/users/".$id."/file1.txt"; $fh = fopen($file1, 'w'); fwrite($fh, "1"); fclose($fh); I followed this tut: http://www.tizag.com/phpT/filewrite.php I cant find anything wrong with the code,but it will not make the file have 1 in it. I'm trying this simple script on my windows server 2008 standard edition but keep getting errors. Code: [Select] <?php error_reporting(-1); ini_set( 'display_errors' , 1 ); $file=fopen("2.txt","a") ; fwrite($file,"Hai"); ?> Code: [Select] Warning: fopen(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Paris' for '1.0/no DST' instead in C:\inetpub\wwwroot\10.php on line 3 Warning: fopen(2.txt): failed to open stream: Permission denied in C:\inetpub\wwwroot\10.php on line 3 Warning: fwrite(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Paris' for '1.0/no DST' instead in C:\inetpub\wwwroot\10.php on line 4 Warning: fwrite() expects parameter 1 to be resource, boolean given in C:\inetpub\wwwroot\10.php on line 4 Any help is appreciated. Hi everyone, I have a page that i use to upload images to my website, i got a bit fed up of uploading one at a time so i decided to add multiple file fields to the form to upload multiple images at the same time. Im having a few problems, iv read up he http://www.php.net/manual/en/features.file-upload.multiple.php and it seems all i have to do is add [] to the form names to turn them into arrays. However when i come to upload the images, i keep getting the "$error[] = "Incorrect format!...." error from the code below. I cant seem to figure out what the problem is. Could anybody please point me in the right direction? <?php session_start(); $id = $_SESSION['id']; $connect = mysql_connect("localhost","leemp5_admin","p7031521"); mysql_select_db("leemp5_database"); $query = mysql_query("SELECT * FROM users WHERE id='$id'"); $row = mysql_fetch_assoc($query); $username = $row['username']; $submit = $_POST['submit']; $type = $_FILES['image']['type']; $size = $_FILES['image']['size']; $max_size = "1000"; $width = "100"; $height = "100"; $error = array(); function make_thumb($image_name,$filename,$new_width,$new_height) { $ext=getExtension($image_name); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $source_image=imagecreatefromjpeg($image_name); if(!strcmp("png",$ext)) $source_image=imagecreatefrompng($image_name); if(!strcmp("gif",$ext)) $source_image=imagecreatefromgif($image_name); $old_x=imageSX($source_image); $old_y=imageSY($source_image); $ratio1=$old_x/$new_width; $ratio2=$old_y/$new_height; if($ratio1>$ratio2) { $thumb_width=$new_width; $thumb_height=$old_y/$ratio1; } else { $thumb_height=$new_height; $thumb_width=$old_x/$ratio2; } $destination_image=ImageCreateTrueColor($thumb_width,$thumb_height); imagecopyresampled($destination_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$old_x,$old_y); if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) { imagejpeg($destination_image,$filename); } if(!strcmp("png",$ext)) { imagepng($destination_image,$filename); } if(!strcmp("gif",$ext)) { imagegif($destination_image,$filename); } imagedestroy($destination_image); imagedestroy($source_image); } function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } if($submit) { $image=$_FILES['image']['name']; if ($image) { $filename = stripslashes($_FILES['image']['name']); $extension = getExtension($filename); $extension = strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { $error[] = "Incorrect format! Please make sure your image is a .jpg, .jpeg, .png or .gif file."; } else { $size=getimagesize($_FILES['image']['tmp_name']); $sizekb=filesize($_FILES['image']['tmp_name']); if ($sizekb > $max_size*1024) { $error[] = "Your image is too big! The maximum upload size is 1MB."; } else { $image_name=time().'.'.$extension; $newname="uploads/" . $username . "/images/".$image_name; $copied = copy($_FILES['image']['tmp_name'], $newname); if (!$copied) { $error[] = "There was an error uploading your image. Please try again!"; } else { $thumb_name='uploads/' . $username . '/images/thumbs/thumb_'.$image_name; $thumb=make_thumb($newname,$thumb_name,$width,$height); } } } } else { $error[] = "Please select an image to upload!"; } if(empty($error)) { echo "Upload Successfully!<br />"; echo '<img src="'.$thumb_name.'">'; mysql_query("INSERT INTO images VALUES ('','$username','$image_name','','','','','uploads/$username/images/$image_name','uploads/$username/images/thumbs/thumb_$image_name','$type','$size')"); } else { echo implode($error); } } ?> <form method="post" enctype="multipart/form-data" action="upload_images.php"> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="file" name="image[]" /><br /> <input type="submit" name="submit" value="Upload"> </form> Thanks I am looking to allow people to also upload pdf and doc ad txt files can you show me how to convert this script . Thanks. Code: [Select] [php] // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp","image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } [/php] Good day: I have a simple uploader form to upload video files. FLV and mpg files will upload without problems. But mp4, m4v, ogg and webm files will not upload. I get this error: Warning: copy() [function.copy]: Unable to access in /mounted-storage/home7/sub007/sc30390-PTUD/**********.com/admin123/insertvideo.php on line 32 Error Video not loaded. I have read about adding the files in config/mimes.php but I do not see that folder or files in my hosting service (which is servage). Any help will be appreciated. Thanks. Good afternoon,
I wrote a script for uploading files to ftp server. When I lunch this on local server(wamp) it does upload files into ftp server.
When I run the same script on my host provider(iPage) it doesn't upload files. Any advices?
Have a look at the code please.
form
<code>
<form enctype="multipart/form-data" action="upload.php" method="post"> <table > <tr> <td> <input name="userfile" type="file"> </td> </tr> <tr> <td > <input type="Submit" value="Add file"> </td> </tr> </table> </form> </code> upload.php <code> <?php ###################################################################### /* For remote servers */ ini_set("max_execution_time", 100000000000); // execution time must be bigger for larger files $file = basename($_FILES['userfile']['name']); //$remote_file = "/home/users/web/b1729/ipg.marcinkopecnet/remote_upload/$file"; $remote_file = "/remote_upload/$file"; /* Define ftp server connection */ $ftp_server = "right_server"; $ftp_user_name = "right_username"; $ftp_user_pass = "right_password"; // set up basic connection $conn_id = ftp_connect($ftp_server, 21) or die ("Cannot connect to host"); // turn passive mode on ftp_pasv($conn_id, true); // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("Cannot login"); // upload a file if ($upload = ftp_put($conn_id, $remote_file, $_FILES['userfile']['tmp_name'], FTP_BINARY)) { // check upload status: print (!$upload) ? 'Cannot upload' : 'Upload complete'; print "\n"; //echo "successfully uploaded $file\n"; } else { echo "There was a problem while uploading $file\n"; } // close the connection ftp_close($conn_id); ###################################################################### ?> </code> Edited by MarcinUK, 04 September 2014 - 05:39 PM. I am using the following code to upload images for my products. How can I modify it to not only upload the product image, but upload it a 2nd time resized for thumbnail or is it even possible? Code: [Select] 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("images/" . $_FILES['file']['name'])) { echo $_FILES['file']['name'] . " already exists. "; } else { move_uploaded_file($_FILES['file']['tmp_name'], "images/$companyname/$materialdir/$prefix$modelnumber.jpg"); //"images/" . $companyname . "/" . $materialdir/$prefix$modelnumber . ".jpg"); //"images/" . $_FILES['file']['name']);//change to Timp folder // "C:/upload/" . $_FILES['file']['name']);//change to Timp folder //echo "Stored in: " . "C:/xampp/htdocs/Timp/UserLogin/upload/" . $_FILES["file"]["name"]; echo "Stored in: images/$companyname/$materialdir/$prefix$modelnumber.jpg"; } } $photo = "images/$companyname/$materialdir/$prefix$modelnumber.jpg"; Hey guys, im uploading up to 48 PNG images from one page, this works fine when theres only a few images, but doesnt work the more there are. Is there any reason for this? Is it to do with php.ini or is that per file, not for the whole upload? Thanks. Danny. Hey guys, I have an image upload script and it's working fine. But for some files it will not work. It says it can't get the filesize and it can't copy that file. I have tried to change the file format of that file, but with no result. So it's not the file format. Is there anything else that could confuse getfilesize and copy commands in PHP? Can you please tell me what is wrong? include ("include/session.php"); //Pohranjivanje podataka za 1. sliku $naziv1 = mysql_real_escape_string($_POST["naziv1"],$veza); $opis1 = mysql_real_escape_string($_POST["opis1"],$veza); $album_id = mysql_real_escape_string($_POST["album_id"],$veza); $datum1 = date("Y-m-d H:i:s"); //Upload slike i thumba //define a maxim size for the uploaded images define ("MAX_SIZE","10000000000"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","200"); define ("HEIGHT","150"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext)) $src_img=imagecreatefrompng($img_name); if(!strcmp("gif",$ext)) $src_img=imagecreatefromgif($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) //and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['spremi'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['slika1']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['slika1']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message //and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server $size=getimagesize($_FILES['slika1']['tmp_name']); $sizekb=filesize($_FILES['slika1']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*1024) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name1=mt_rand(0,9999999).'.'.$extension; //the new name will be containing the full path where will be stored (images folder) $newname="slike_natjecanja/".$image_name1; $copied = copy($_FILES['slika1']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='slike_natjecanja/thumbs/thumb_'.$image_name1; $thumb_name1 = 'thumb_'.$image_name1; // call the function that will create the thumbnail. The function will get as parameters //the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } if (empty($_FILES['slika1']['name'])) { echo "Prazno je!"; die; } else { //Ubacivanje u bazu $upit = "INSERT INTO natjecanja_slike_sve (album_id, naziv_slike, opis_slike, datum_dodavanja_slike, slika_nat_mala, slika_nat_velika) VALUES ('$album_id', '$naziv1', '$opis1', '$datum1', '$thumb_name1', '$image_name1')"; echo "$upit"; die; $rezultat = mysql_query($upit) or die (mysql_error()); } I have 2 sites here that does what i need them to do but i dont know how to put the 2 codes together i got it to upload all files and used rand() to give the files a # but it ends up giving them all the same # lol so they overwrite them selfs lol This site shows how to upload mltiple fiels with php. http://www.ehow.com/how_6345068_upload-multiple-files-php.html This site shows how to rename only 1 file uploaded with rand() http://php.about.com/od/advancedphp/ss/rename_upload.htm i pray this is not to hard to do and if any one gets bored after words can you show how to block a file type from being uploaded ? like php/exe types PS)i would call my self a php newbe lol and ty you for your time and help Code from http://php.about.com/od/advancedphp/ss/rename_upload.htm Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> //This function separates the extension from the rest of the file name and returns it function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //This applies the function to our file $ext = findexts ($_FILES['uploaded']['name']) ; //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. $ran = rand () ; //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended. $ran2 = $ran."."; //This assigns the subdirectory you want to save into... make sure it exists! $target = "images/"; //This combines the directory, the random file name, and the extension $target = $target . $ran2.$ext; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; } The code from http://www.ehow.com/how_6345068_upload-multiple-files-php.html Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> <input type="submit" name="submit" value="Upload"/> </form> $destpath = "upload/" ; while(list($key,$value) = each($_FILES["file"]["name"])) { if(!empty($value)){ f ($_FILES["file"]["error"][$key] > 0) { echo "Error: " . $_FILES["file"]["error"][$key] . "<br/>" ; } else { $source = $_FILES["file"]["tmp_name"][$key] ; $filename = $_FILES["file"]["name"][$key] ; move_uploaded_file($source, $destpath . $filename) ; echo "Uploaded: " . $destpath . $filename . "<br/>" ; } } } I'm using the following code to create a folder from a text field and works fine. I would like to upload 3 files in the created folder. <?php // set our absolute path to the directories will be created in: $path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/'; if (isset($_POST['create'])) { // Grab our form Data $dirName = isset($_POST['dirName'])?$_POST['dirName']:false; // first validate the value: if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) { // We have a valid directory: if (!is_dir($path . $dirName)) { // We are good to create this directory: if (mkdir($path . $dirName, 0775)) { $success = "Your directory has been created succesfully!<br /><br />"; }else { $error = "Unable to create dir {$dirName}."; } }else { $error = "Directory {$dirName} already exists."; } }else { // Invalid data, htmlenttie them incase < > were used. $dirName = htmlentities($dirName); $error = "You have invalid values in {$dirName}."; } } ?> <html> <head><title>Make Directory</title></head> <body> <?php echo (isset($success)?"<h3>$success</h3>":""); ?> <h2>Make Directory on Server</h2> <?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?> <form name="phpMkDIRForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> Enter a Directory Name (Alpha-Numeric only): <input type="text" value="" name="dirName" /><br /> <input type="submit" name="create" value="Create Directory" /> </form> </body> </html> Hi i have the script to upload files i set the type of file and extension allowed all the files type and extension i can upload except mp4 is ther anything extra i need to do isnt file type (video/mp4) extension (mp4) but still not working. Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("database_name") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"]["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif','avi','mp4'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif', 'video/mp4'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $title = $_POST["title"]; $subtitle = $_POST["subtitle"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { if (move_uploaded_file($temp1, $location .$name1)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO tablename (title, subtitle, image) VALUES ('$title', '$subtitle', '$appendic_name')") ; echo $type; echo "<br />"; echo $type1; } } else { foreach ($error as $error) { echo $error; } } } //echo $type; ?> hi! i want to upload videos and music files using php but it's not working correctly.through this code imges are uploaded successfully but there is problem with video files ..i hv use php.ini to resolve the size prblem but still its not working..can u give me any code that works perfectly. here is my code.. Collapse <?php ini_set('post_max_size', 5242880); // Set upload limit (5MB) ini_set('upload_max_filesize', 5242880); // Enforce upload limit ini_set('max_execution_time', 2400); // Increase 'timeout' time echo "<form enctype='multipart/form-data' name='form2' method='post' action='video.php?view_id=view'>"; if(isset($_REQUEST['Submit'])) { print_r($_FILES['file2']); $music=($_FILES['file2']['name']); if($_FILES['file2']['error']>0) { echo "error accured"; } else { move_uploaded_file($_FILES['file2']['tmp_name'],"uploadedMusic/".$_FILES['file2']['name']); } } echo "<input name='file2' type= 'file'>"; echo "<input name='Submit' type='submit' value='upload music'>"; echo "</form>"; ?> In the database, I have a table called 'users' inside that I have email, nick (aka username), and balance. The individual aspects are set up, and work. My site is also successfully connecting to and reading / writing info in the database. So my question is: How would I go about having a box on the register page called 'refer' where the person would enter their referrers email (or nickname, one or the other) then it finds that person, and puts a value of 10 in 'balance'. Anyone with more experience than me have any ideas? All help is greatly appreciated.
i have php at server side and c++ at client side.what i am trying to do is to constantly look for files on server in folder on server if there’s a file in folder then download it on client side and delete it from server folder Hi, ive recently created a gallery website and im happy with the way everything currently works. However the main drawback is the site uploads using a html webfom which is great for remote users or the odd image. However, as i want to mass upload my existing collection i will need the ability to read a selected folder and then to carry out all the same processes that existed from the existing html form upload. Im also using gdlibrary and checking file types to ensure they are within my allowed list, but im wondering if there are any other common security alerts i should be aware of to keep things a little bit safer if/when i publish outside of my LAN. So in a nut shell i need some assistance with changing my upload process to work for more than one file at a time, ideally by reading a folder, or at least reading X amount of files at a time - processing them then moving onto next batch of files in the list. Then the next part i need help with is checking/improving basic security of the system |