PHP - How To Restrict File Sizes And File Type And Prevent Overwriting In Upload.php
Hiya,
Firstly, I'm a complete novice, apologies! But I have got my upload.php working which is nice. I will post the code below. However, I would now like to restrict the file size and file type to only word documents. I currently have a restriction of 200KB but it's not working - no idea why as I've looked at other similar codes and they look the same. Also, just to complicate things - can I stop files overwriting each other when uploaded? At the moment, if 2 people upload files with the same name one will overwrite the other. Is this too many questions in 1? Any help is very much appreciated! Code below: Code: [Select] <form enctype="multipart/form-data" action="careers.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> <?php $target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition if ($uploaded_size > 200) { 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 "Your file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded."; } else { echo "Sorry, there was a problem uploading your file."; } } ?> Similar Tutorialsfiles that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
Folks,
I am building a membership script for 21 months now!!! That long!!!
Not pasting the whole script as really long. Would do your head in. if($_SERVER["REQUEST_METHOD"] == "POST") { if(!isset($_FILES["id_verification_video_file"])) //REtype { echo "no isset"; } else { $id_verification_video_file = $_FILES['id_verification_video_file']; //REtype //Feed Id Video Verification File Upload Directory Path. $directory_path = "uploads/videos/id_verifications/"; //Make Directory under $user in 'uploads/videos/id_verifications' Folder. if(!is_dir("$directory_path" . "$user")) { $mode = "0777"; mkdir("$directory_path" . "$user", "$mode", TRUE); //Thanks Requinix for my "$mode" typo hint. } //Grab Uploading File details. $Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ? $file_name = $_FILES["id_verification_video_file"]["name"]; $file_tmp = $_FILES["id_verification_video_file"]["tmp_name"]; $file_type = $_FILES["id_verification_video_file"]["type"]; $file_size = $_FILES["id_verification_video_file"]["size"]; $file_error = $_FILES['id_verification_video_file']['error']; //Grab File Extension details. $file_extension = pathinfo($file_name, PATHINFO_EXTENSION); if(file_exists('$directory_path' . '$user/' . '$file_name')) { $Errors[] = "Error: You have already uploaded a video file to verify your ID!"; exit(); } else { //Feed allowed File Extension(s). $allowed_file_extensions = array("mp4" => "video/mp4","wmv" => "video/wmv"); //Feed allowed file size. $max_file_size_allowed_in_bytes = 1024*1024*100; //Allowed limit: 100MB. $max_file_size_allowed_in_kilobytes = 1024*100; $max_file_size_allowed_in_megabytes = 100; $max_file_size_allowed = "$max_file_size_allowed_in_bytes"; //RETYPE //Verify File Extension. if(!array_key_exists($file_extension,$allowed_file_extensions)) die("Error: Select a valid video file format. Select an MP4 or WAV file."); //Verify MIME Type of the file. elseif(!in_array($file_type,$allowed_file_extensions)) { echo "Error:<font size ='5' font color ='red'><b>There was a problem uploading your video file $file_name! Make sure your file is an MP4 or a WAV file. You may try again now.</b></color></size>"; //THANKS TO REQUINIX FOR BRINNGING IT TO MY ATTENTION I AM STILL PROCESSING THE SCRIPT AFTER THIS LINE WHEN I SHOULD NOT. exit(); } //Verify File Size. Allowed Max Limit: 100MB. elseif($file_size>$max_file_size_allowed) die("Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes."); //Fixed variable name typo. Thanks to Requinix & Simon JM. //Move uploaded File to newly created directory on the server. move_uploaded_file("file_tmp","$directory_path" . "$user/" . "$file_name"); //Notify user their File was uploaded successfully. echo "<font size ='5' font color ='red'><b>Your Video File \"$file_name\" has been uploaded successfully! You will get notified once your Id has been verified successfully.</b></color></size>";
Can you spot my coding error ? Hi. I'm making a file-sharing website but how do I stop users from uploading certain extensions? Here is my script so far: <?php session_start(); $file_name = $HTTP_POST_FILES['ufile']['name'];$random_digit=rand(0000,9999);$new_file_name=$random_digit.$file_name;$path= "upload/".$new_file_name;if($ufile !=none){if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path)){echo "Successful<BR/>";}else{echo "Error";}}?>() In this multi file upload form, choose three images, click submit and preview the images on the preview page. If the user wishes to delete or replace an image, click edit and the form will go back to the previous page. Select the replace radio button for example on one of the three images and select a new image from the file input prompt and click submit. The form will go to the preview page again to display the images. During this process the image names are being input into a table and the images are being moved to a directory. The table is `id` AUTO_INCREMENT, `image0` `image1` `image2` `status` So input name='image[image0]' can be directed to table `image0` and so on. The code for keep and delete work fine, but how do I replace an image? I have two foreach blocks. The first one deletes the image file from the directory and deletes the image name from the table, but the second foreach dose not move the new image file into the directory. Thanks. <input type='radio' name='image[image0]' value='keep' checked='checked'/> <input type='radio' name='image[image0]' value='delete' /> <input type='radio' name='image[image0]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image1]' value='keep' checked='checked'/> <input type='radio' name='image[image1]' value='delete' /> <input type='radio' name='image[image1]' value='replace' /> <input type="file" name="image[]" /> <input type='radio' name='image[image2]' value='keep' checked='checked'/> <input type='radio' name='image[image2]' value='delete' /> <input type='radio' name='image[image2]' value='replace' /> <input type="file" name="image[]" /> <?php if (isset($_POST['status'])) { $status = $_POST['status']; $confirm_code = $status; #--------------------------- replace -------------------------------------------- if (isset($_POST['submitted']) && ($image = $_POST['image'])) { foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $query = "SELECT $imageKey FROM table WHERE status = '$status' "; if($result = $db->query( $query )){ $row = $result->fetch_array(); } unlink( UPLOAD_DIR.$row[0] ); $query = "UPDATE table SET $imageKey = '' WHERE status = '$status' "; } } foreach($image as $imageKey => $imageValue) { if ($imageValue == 'replace') { $filenm = $_FILES['image']['name']; $file = $_FILES['image']['tmp_name']; move_uploaded_file($file, UPLOAD_DIR . $filenm); $filename[] = $filenm; $query = "INSERT INTO table VALUES ('','$filename[0]','$filename[1]','$filename[2]','$confirm_code')"; } } } } ?> I havent included the whole title as it wouldnt let me but I was wondering if someone could help me on this? I know this is possible as torrentflux caters for this but unsure of where to start. I dont want to allow file or directory uploads or creation in my /etc/php.ini file (this is turned off). Yet then torrentflux allows me to link a torrent from an external source (using legal downloads of course ) but then it uploads it on my server and creates folders on a per user basis. How is this possible can someone give me some pointers please? I look forward to any replies, Jeremy. So, I'm learning how to upload pictures into a system from my awesome PHP book. I've looked and looked through the script but I can't figure out whats wrong with it. Goal: The script is meant to save a full version of the image in the images folder and a thumbnail in the thumbnail folder. Bug: The full image does not appear in any folder, and the thumbnail is created but its put in the images folder. I've checked the GD library, and everything is supported. image_effect.php <?php //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // make sure the requested image is valid if (isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir . '/' . $_GET['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_GET['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_GET['e'])) ? $_GET['e'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_GET['capt'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']); } //add the logo watermark if requested if (isset($_GET['logo'])) { // determine x and y position to center watermark list($width, $height) = getimagesize($dir . '/' . $_GET['id'] . '.jpg'); list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // show the image header('Content-Type: image/jpeg'); imagejpeg($image, '', 100); ?> check_image.php <?php include 'db.inc.php'; //connect to MySQL $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your thumbnail directory $thumbdir = $dir . '/thumbs'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // handle the uploaded image if ($_POST['submit'] == 'Upload') { //make sure the uploaded file transfer was successful if ($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK) { switch ($_FILES['uploadfile']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive ' . 'in php.ini.'); break; case UPLOAD_ERR_FORM_SIZE: die('The uploaded file exceeds the MAX_FILE_SIZE directive that ' . 'was specified in the HTML form.'); break; case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded.'); break; case UPLOAD_ERR_NO_FILE: die('No file was uploaded.'); break; case UPLOAD_ERR_NO_TMP_DIR: die('The server is missing a temporary folder.'); break; case UPLOAD_ERR_CANT_WRITE: die('The server failed to write the uploaded file to disk.'); break; case UPLOAD_ERR_EXTENSION: die('File upload stopped by extension.'); break; } } //get info about the image being uploaded $image_caption = $_POST['caption']; $image_username = $_POST['username']; $image_date = @date('Y-m-d'); list($width, $height, $type, $attr) = getimagesize($_FILES['uploadfile']['tmp_name']); // make sure the uploaded file is really a supported image $error = 'The file you uploaded was not a supported filetype.'; switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error); break; default: die($error); } //insert information into image table $query = 'INSERT INTO images (image_caption, image_username, image_date) VALUES ("' . $image_caption . '", "' . $image_username . '", "' . $image_date . '")'; $result = mysql_query($query, $db) or die (mysql_error($db)); //retrieve the image_id that MySQL generated automatically when we inserted //the new record $last_id = mysql_insert_id(); // save the image to its final destination $image_id = $last_id; imagejpeg($image, $dir . '/' . $image_id . '.jpg'); imagedestroy($image); } else { // retrieve image information $query = 'SELECT image_id, image_caption, image_username, image_date FROM images WHERE image_id = ' . $_POST['id']; $result = mysql_query($query, $db) or die (mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width, $height, $type, $attr) = getimagesize($dir . '/' . $image_id . '.jpg'); } if ($_POST['submit'] == 'Save') { // make sure the requested image is valid if (isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir . '/' . $_POST['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_POST['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_POST['emb_caption'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $image_caption); } //add the logo watermark if requested if (isset($_POST['emb_logo'])) { // determine x and y position to center watermark list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // save the image with the filter applied imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100); //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . '/' . $_POST['id'] . '.jpg', 100); imagedestroy($thumb); ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>Your image has been saved!</h1> <img src="images/<?php echo $_POST['id']; ?>.jpg" /> </body> </html> <?php } else { ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>So how does it feel to be famous?</h1> <p>Here is the picture you just uploaded to our servers:</p> <?php if ($_POST['submit'] == 'Upload') { $imagename = 'images/' . $image_id . '.jpg'; } else { $imagename = 'image_effect.php?id=' . $image_id . '&e=' . $_POST['effect']; if (isset($_POST['emb_caption'])) { $imagename .= '&capt=' . urlencode($image_caption); } if (isset($_POST['emb_logo'])) { $imagename .= '&logo=1'; } } ?> <img src="<?php echo $imagename; ?>" style="float:left;"> <table> <tr><td>Image Saved as: </td><td><?php echo $image_id . '.jpg'; ?></td></tr> <tr><td>Height: </td><td><?php echo $height; ?></td></tr> <tr><td>Width: </td><td><?php echo $width; ?></td></tr> <tr><td>Upload Date: </td><td><?php echo $image_date; ?></td></tr> </table> <p>You may apply special options to your image below. Note: saving an image with any of the options applied <em>cannot be undone</em>.</p> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div> <input type="hidden" name="id" value="<?php echo $image_id;?>"/> Filter: <select name="effect"> <option value="-1">None</option> <?php echo '<option value="' . IMG_FILTER_GRAYSCALE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE) { echo ' selected="selected"'; } echo '>Black and White</option>'; echo '<option value="' . IMG_FILTER_GAUSSIAN_BLUR . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR) { echo ' selected="selected"'; } echo '>Blur</option>'; echo '<option value="' . IMG_FILTER_EMBOSS . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS) { echo ' selected="selected"'; } echo '>Emboss</option>'; echo '<option value="' . IMG_FILTER_NEGATE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE) { echo ' selected="selected"'; } echo '>Negative</option>'; ?> </select> <br/><br/> <?php echo '<input type="checkbox" name="emb_caption"'; if (isset($_POST['emb_caption'])) { echo ' checked="checked"'; } echo '>Embed caption in image?'; echo '<br/><br/><input type="checkbox" name="emb_logo"'; if (isset($_POST['emb_logo'])) { echo ' checked="checked"'; } echo '>Embed watermarked logo in image?'; ?> <br/><br/> <input type="submit" value="Preview" name="submit" /> <input type="submit" value="Save" name="submit" /> </div> </form> </body> </html> <?php } ?> Any help appreciated. <td><label for='images'> <b>File to upload:</b> </label></td> <td><input type='file' name = 'drama_image' '<?php echo $row['drama_image']; ?>'/></ </tr> <?php $target_path = "images/"; $target_path = $target_path . basename( $_FILES['images']['name']); if(move_uploaded_file($_FILES['images']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['images']['name']). " has been uploaded"; } else{ echo $row['drama_image']; } ?> ['drama_image'] is the name of the file I wanna echo it out in the box of file upload so when I save , the default picture will still be there instead of being overwritten as the box does not have any value in it. Hello, 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 ?> I have solved this now. HI All, I have a form submission that uploads a photo as well as submitting other data. I would like to change the name of the photo to the id of the person record (created automatically on by the database) then a hyphen, then their first name and lastname. (i am flexible on this). This file name will also need to be submitted into the person record so the photo and the person can be linked. I am struggling with this one - but here is the code i have so far.
<?php include 'includes/dbconn.php'; $target_dir = "img/people/"; $target_file = $target_dir . basename($_FILES["personHeadshot"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); if ($_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']; $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) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "); $stmt -> bind_param(ssiiissssssi, $fn, $ln, $crole, $playerType, $team, $ad1, $ad2, $city, $post, $tel, $email, $OFA); $stmt -> execute(); // Check if image file is a actual image or fake image //photo upload $check = getimagesize($_FILES["personHeadshot"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } //photo upload header("location: ../admin-people-list.php"); } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["personHeadshot"]["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["personHeadshot"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["personHeadshot"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }
Hello! I have this validation script that seems to work great until I add the size validation. I'm ready to pull my hair out! Can someone tell me what I'm doing wrong? Code: [Select] if (isset($_POST['Submit'])) { $user_id = $userdata[user_id]; $number_of_file_fields = 0; $number_of_uploaded_files = 0; $number_of_moved_files = 0; $uploaded_files = array(); $max_filesize = 5242880; // Maximum filesize in BYTES (currently 5MB). $upload_directory = dirname(__file__) . '/'.$user_id.'/'; //set upload directory if (!is_dir($upload_directory)) { mkdir($upload_directory, 0777, true); } for ($i = 0; $i < count($_FILES['images']['name']); $i++) { $number_of_file_fields++; if ($_FILES['images']['name'][$i] != '') { //check if file field empty or not $number_of_uploaded_files++; if($_FILES['images']['size'] > $max_filesize){ echo "<b class='red'>Max file size is 5MB.</b><br/>"; $sz = true; } $ext = validate_extension($_FILES['images']['name'][$i]); if (($ext == true) && ($sz == true)){ $uploaded_files[] = $_FILES['images']['name'][$i]; if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i])) { $number_of_moved_files++; } }else { echo "<b class='red'>File extention error. Only .doc, .pdf, .jpg and .gif files are allowed. </b><br/>"; } } } if ($number_of_uploaded_files >= 1){ echo "Number of files submitted:<b class='red>".$number_of_uploaded_files."</b><br/>"; echo "Number of successfully uploaded files:<b class='red>".$number_of_moved_files."</b><br/><br/>"; echo "Uploaded File Name(s):<br/>" . implode('<br/>', $uploaded_files); } } As of now it results in every uploaded file returning the error "Max file size is 5MB." I have a script that I am trying to transfer one file from a remote server to my local server and save it. The files can be quite large. I have successfully backed up around 200 MB... But, anything over that seems to fail with a strange error... I was hoping for a little guidance... here is my code and error/warning that I get: PHP Code: function remote_capture($tmp_url, $filename) { $r_handle = fopen($tmp_url, "rb"); $d_handle = fopen($filename, 'w'); if($r_handle&&$d_handle) { while(($buffer = fgets($r_handle)) !== false) { fputs($d_handle, $buffer); } fclose($r_handle); fclose($d_handle); return true; } else { return false; } } Warning Message: Warning: file_get_contents(URL_OF_MY_SCRIPT_HAS_BEEN_REMOTED) [function.file-get-contents]: failed to open stream: HTTP request failed! in /path/on/my/local/server/to/script on line 298 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); } ?>
How do I Upload Multiple Files using a PHP form and script? 10 files at one time would be great. Ultimately I need a photo upload and management script. Here is my current single file upload form: <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Upload a Photo:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> Here is the Php Script: <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 200000)) { 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"], "uploads/" . $_FILES["file"]["name"]); echo "Stored in: " . "uploads/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> Been looking on the web on and off for the past few days but can't seem to find a list of all file types that PHP (or is it Apache) appreciates. Like when you go and upload file using a form and then it outputs: Quote Array ( [upload_file] => Array ( [name] => discount_xcart_orders.csv [type] => text/comma-separated-values [tmp_name] => /tmp/phprAk2R6 [error] => 0 [size] => 674 ) ) Is there an entire list of file types that this '[type] => text/comma-separated-values' falls under? Just out of interest of course, Jeremy. I have two scripts: script1.php and script2.php.
Script1 creates if it doesn't already exist and adds to a session named "SESSION1" and displays it:
Script2 similarly adds to a session named "SESSION2", but then needs to display the session used by the first script (i.e. SESSION1), and then goes back to its original session (SESSION2).
Script1 works perfect. But when Script2 is executed, it changes the session ID in the SESSION1 cookie to the same value as used in its SESSION2 cookie. If Script1 is later executed, it obviously lost its previous session values as it is now using a new session ID.
If I comment out the two session_name() lines, it will not overwrite the other session, however, this doesn't provide the functionality I need.
What is causing this and how do I prevent it????
script1.php
<?php // script 1. Will be accessed as http://one.example.com $t=time(); //Access the primary session for script 1 session_name('SESSION1'); session_start(); $_SESSION['s1_'.$t]=$t; echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>"); ?>script2.php <?php // script 2. Will be accessed as http://two.one.example.com $t=time(); //Access the primary session for script 2 $default_name=session_name('SESSION2'); session_start(); $_SESSION['s2_'.(2*$t)]=2*$t; echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>"); //Use session created by script 1 $old_id_script2 = session_id(); session_write_close(); $old_name_script2 = session_name('SESSION1'); session_start(); echo("SESSION1<pre>".print_r($_SESSION,1)."</pre>"); //Go back to primary session session_write_close(); $old_id_script1 = session_id($old_id_script2); $old_name_script1 = session_name($old_name_script2); session_start(); echo("SESSION2<pre>".print_r($_SESSION,1)."</pre>"); echo("default_name: $default_name<br>"); echo("old_id_script2: $old_id_script2<br>"); echo("old_name_script2: $old_name_script2<br>"); echo("old_id_script1: $old_id_script1<br>"); echo("old_name_script1: $old_name_script1<br>"); ?> Edited by NotionCommotion, 30 November 2014 - 11:45 AM. How would i do a random file name for my upload script Code: [Select] $type = $_FILES['uploadedfile']['type']; // Where the file is going to be placed $target_path ="/***/***/public_html/****/lofslidernews/images/"; /* Add the original filename to our target path. Result is "/images/uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $uploadedfile2 = $_FILES['uploadedfile']['name']; if (empty($quicktitle) || empty($maintitle ) || empty($description ) || empty($uploadedfile)) { $_SESSION["promoerror"] = "Please Select an image and enter a Quick Title, Main Title and Description!" ; header("Location: promo.php"); //This sets the redirection information //echo "Going to login.php, username or password is empty"; exit(); //Ends the script and redirects to above } $query = "INSERT INTO promotion (title, maintitle, description, image) VALUES ('$quicktitle','$maintitle','$description', '$uploadedfile2')"; $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); if ( ( $type != "image/jpeg") && ($type != "image/gif") ) { die ("That format is not allowed"); } else { move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path); header("Location: promo.php"); $_SESSION["promoerror"] = "Added Successfully!"; } A shipping vendor (like Stamps.Com) provides me a Printable Shipping Label to display on my website for Visitors to print.
When Visitors come to my page, my PHP code:
$Shipping_Label_Data = $LabelVendor->data[0]->contents; // vendor's API echo '<img src="/Label-Directory/'.$Order_Number.'.png" />'; Later I realized the security flaw: any snooper can fish for other Visitor's labels in my Label directory. What is the best way to prevent the display of other people's labels? Thank you!! I use jQuery when adding messages. However, the file can be called directly. For example: includes/add_comment.php?id=2 So, I can make a form and call this file directly to add a message. ID is user id and form can be submited with HTML form wherever are located. How to prevent direct access to the file when called through a Ajax? Hi. I want to create a list of files in a directory. But I don't want all the files to be listed, only .gif, .jpg and .bmp. Does anyone know the PHP code how to do that? (My directory name is 'images' if you need that). Thanks! |