PHP - Inserting Images Using $_files
Ok, I have this working on another page from a long time ago, but it's not working right he It gets past the if($num == 0) part, but when it's seeing if the files has been uploaded, it's not getting past that and it won't give me my error message too. So I have a feeling it's getting past it, but it's not uploading it into the software/ directory and not inserting it into the database.
I get no errors in my error_log or my default errors I have set up under the variable, $message. Code: [Select] $target_path = "software/"; $basename = strtolower(basename($_FILES['softwarePath']['name'])); $target_path = $target_path . $basename; $sql = "SELECT softwarePath FROM software WHERE softwarePath='$target_path'"; $result = mysqli_query($cxn, $sql) or die(mysqli_error()); $num = mysqli_num_rows($result); if($num == 0) { if(move_uploaded_file($_FILES['softwarePath']['tmp_name'], $target_path)) { $sql = "INSERT INTO software(softwareName,softwareType,softwareDesc,softwarePath,ITOnly) VALUES('$softwareName','$softwareType','$softwareDesc','$target_path','$ITOnly')"; mysqli_query($cxn,$sql) or die(mysqli_error()); header("Location: search_software.php"); } } else { $message = "There is already a file with that name."; } Similar TutorialsI am trying to create insert function when there is no picture. Here is the code: Code: [Select] if(isset($_POST['submit'])) { $pages = new Pages(); $pages->body = htmlspecialchars($_POST['body']); $pages->meni_id = $_POST['meni_id']; $pages->lang_id = $_POST['lang_id']; if(!empty($_FILES['image'])){$pages->attach_file($_FILES['image']); } else { $body = htmlspecialchars($_POST['body']); $meni_id = $_POST['meni_id']; $lang_id = $_POST['lang_id']; $roller = 0; $query = "INSERT INTO pages VALUES (NULL, '$body', '$roller', '$meni_id', '$lang_id')"; $result = mysql_query($query); $session->message("Strana je uspesno uneta."); } if($pages->save()) { // Success $session->message("Strana je uspesno uneta."); redirect_to('index.php?page=pages'); } else { // Failure $message = join("<br />", $pages->errors); } } It works fine when picture is selected, but it does not work when one is selected. How to make it work? How do I determine if $_FILES['thumbNail']['name'] is blank? I am uploading images into a folder on my server called thumbNail and I would like to specify a default image (noimage.gif) if no prior image has been uploaded, but I'm having trouble getting an if statement to register true if the image upload was skipped. Thank you. Hi, My $_FILES is not working. Its working when Im doing my project on the local host. After I uploaded my project to the server, the $_FILES is not working. Im trying to upload images. the $_FILES['name'] couldn't read anything. its like no file there. whats causes it? any other way to read from <input type='file'/> ? or way to solve this? Thank You. I need to check whether the user has uploaded a file when submitting a form using isset. If they have, the file path is recorded to the database. If they haven't nothing needs to occur, the file path field will just be NULL. Here is my issue: When I test it with uploading no file I'm still getting "images/" from my $ filelocation variable recorded to the database. How can I fix this? <?php if(isset($_FILES['userfile'])) { $fileupload = $_FILES['userfile']['name']; $filetype = $_FILES['userfile']['type']; $filesize = $_FILES['userfile']['size']; $tempname = $_FILES['userfile']['tmp_name']; $filelocation = "images/$fileupload"; } else { $filelocation = NULL; } if (!move_uploaded_file($tempname,$filelocation)) { switch ($_FILES['userfile']['error']) { case UPLOAD_ERR_INI_SIZE: echo "<p>Error: File exceeds the maximum size limit set by the server</p>" ; break; case UPLOAD_ERR_FORM_SIZE: echo "<p>Error: File exceeds the maximum size limit set by the browser</p>" ; break; default: echo "<p>File could not be uploaded </p>" ; } } if ($_POST["productName"] == "") { header("Location:getProductDetails.php"); exit(); } elseif ($_POST["productDescription"] == "") { header("Location:getProductDetails.php"); exit(); } else { $conn = @mysqli_connect("localhost", "root", ""); if (!$conn) { echo "The connection has failed: " . mysqli_error($conn); } else { //echo "Successfully connected to mySQL!"; $query = "CREATE DATABASE IF NOT EXISTS bazaar"; $dbName =""; if (!mysqli_query($conn,$query)) { echo "<p>Could not open the database: " . mysqli_error($conn)."</p>"; } else { //echo "<p>Database successfully created</p>"; if (!mysqli_select_db($conn,"bazaar")) { echo "<p>Could not open the database: " . mysqli_error($conn)."</p>"; } else { //echo "<p>Database selection successful</p>"; $query = "CREATE TABLE IF NOT EXISTS products(productid int primary key not null auto_increment,productname varchar(50), productdesc text, colour varchar(25), price decimal(5,2) not null,imagepath varchar(250));"; if (!mysqli_query($conn,$query)) { echo "table query failed1: " . mysqli_error($conn); } else { //echo "<p>table query successful</p>"; $insert = "INSERT INTO products (productname, productdesc, colour, price, imagepath) VALUES ('$_POST[productName]','$_POST[productDescription]','$_POST[colour]','$_POST[price]','$filelocation');"; if (mysqli_query($conn,$insert)) { $customerId = mysqli_insert_id($conn); } else { echo "table query failed: " . mysqli_error($conn); } } } } } mysqli_close($conn); } ?> What is $_FILES['userfile']['tmp_name']?? Is it a two-dimensional array? Why can't I have a $_FILES['tmp_name']?? Debbie Hi, I have simple php code with HTML.. but its not working with all browser, some time its works in Chrome sometimes its not working in IE I have saved this filr as index.php its code is: <html> <head> <title> Upload </title> </head> <body> <form action="index2.php" method="POST" enctype="multipart/form-data"> Image: <input type="file" name="myImage" /> <input type="submit" value="Upload" /> </form> <?php echo $_FILES["myImage"]["tmp_name"]; ?> </body> </html> I have a multipart forum that can load a photo if needed. My problem is that if no photo is selected for upload it deletes any data in the database for the current row if there is a photo. What I'm trying todo is not load upload_thumb.inc.php if no photo is selected and not run the UPDATE query // If everything's Okay Process the whole form if (empty($errors)) { //Run some of the script here if (isset($_FILES['image'])) { // Upload thumb if one is selected include_once ('../includes/upload_thumb.inc.php'); // run UPDATE query script to insert photo location and stuff in db } // run more script here } What's happening if I have a photo and don't upload another photo the guery over writes the db info for the current photo. The idea with isset($_FILES['image']) was to not load upload_thumb.inc.php and not to run the UPDATE script Thanks S When you try and upload files using a size limiting feature, when you consider $_FILES['form_element']['size'] what actually is this measured in again? I seem to have forgotten what it's actually measured in, if I was to say a limit on $_FILES['myform_file_upload']['size'] < 20000, what does the 20000 actually mean? Any help is appreciated, Jeremy. I'm using a upload class that works with $_FILES, but have a couple of reasons to need the content of php://input: 1) When submitting PDF forms as a complete form, the form is available in php://input. 2) An ajax uploader I'd like to use submits the file making it only available in php://input. I know I could use an if statement to check $_FILES else php://input, but I'm concerned about security, and being able to identify the filetype, get the size, etc. I'm skipping over some other details, because I need to leave in 5 minutes. I've not seen any classes that merge the two ( $_FILES and php://input ), and really haven't seen any that are specifically for php://input. Can anyone offer advice or point me in the right direction? For uploading files, I use a class which accepts an uploaded file array, validates that it has a name, tmp_name, type, error, and size key, validates that it doesn't have errors and meets various requirements, and moves it to the applicable folder. For another applicable, I will be generating the file directly on the server, however, wish to use this same class. Will I need to manually create this "file" array, or is there a native PHP function to accept a path and automatically do it? Thanks Just a question concerning the $_FILES['tmp_name'] field. I'm uploading a file which is being moved into two different locations. I run an 'If' check to see if either process fails but as I am running them both at the same time, when a $_FILES['tmp_name'] is moved, can it be used again? Both my functions run fine independetly but when I try run them both it doesn't work So my question is which may be seem fairly obvious: Once you move the $_FILES['tmp_name'] is it removed from the temp folder it's in? or is it copied? Thanks! I have an index.php file which includes my form and code to move the user's uploaded file to s3. My HTML form calls a js function sendEmails() which makes an AJAX request to another php script dbSystem() to validate the emails input and add it to a database. Everything is working except that the php code in my index.php file (at the very bottom) does not execute. It's supposed to execute when the user uploads a file and presses submit but it doesn't go into the if statement. I tried putting the $fileName = basename($_FILES["fileName"]["name"]) statement before the if statement but I get an undefined index error. I put my a comment in my code to show which if statement I am talking about. This is my HTML code in index.php: <form action="javascript:void(0)" method="POST" id="files" enctype="multipart/form-data"> <label class="col-md-4 col-form-label text-md-right">Select File: <span class="text-danger">*</span></label> <input type="file" id="userFile" name="fileName" style="cursor: pointer; max-width: 170px;" onchange="enableBtn()"> <label class="col-md-4 col-form-label text-md-right">Authorized Users: <span class="text-danger">*</span></label> <input placeholder="Enter e-mail(s) here..." id="req" autocomplete="off"/> <button id="submitBtn" name="submitBtn" class="<?php echo SUBMIT_BUTTON_STYLE; ?>" onclick="return sendEmails()" disabled>Submit</button> </form> This is my php code in index.php: <?php $conn = new mysqli($servername, $username, $password, $db); $sql = "SELECT sender_id, sender_email, receiver_emails, receiver_ids, file_name from filedrop_logs"; $result = mysqli_query($conn, $sql); if ($result) { echo "<div class='outputDiv'>"; echo "<table id='sharedOthers'>"; echo "<thead><tr class='headings'>"; echo "<th class='files'>Files</th>"; echo "<th class='users'>Users</th>"; echo "</tr></thead>"; while ($row = mysqli_fetch_assoc($result)) { $receiverEmails = $row['receiver_emails']; $fileName = $row['file_name']; echo "<tbody id='bodyOthers'>"; echo "<tr id='rowOthers'>"; echo "<td>$fileName<br>"; $objects = getListofObjects('FileDrop'); foreach ($objects as $object) { $file = $object['Key']; $splits = explode('/', $file); if (end($splits) !== '') { $presignedUrl = getPresignedUrlForPrivateFile($object['Key'], '+20 minutes'); $link = '<a href="'.$presignedUrl.'">Download</a>'; echo $link; } } echo " <a href=''>Delete</a></td>"; echo "<td>$receiverEmails</td>"; echo "</tr></tbody>"; } echo "</table></div>"; } ?> <?php //the if statement below doesn't execute if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES["fileName"])) { $fileName = basename($_FILES["fileName"]["name"]); $error = $_FILES["fileName"]["error"]; $tmpName = $_FILES["fileName"]["tmp_name"]; if (isset(fileName) && $fileName != '' && $tmpName != '' && sys_get_temp_dir()) { $separator = DIRECTORY_SEPARATOR; $newDir = sys_get_temp_dir() . $separator . "FileDrop" . microtime(true); if (!file_exists($newDir)) { mkdir($newDir, 0777, true); // creates temp FileDrop directory $tempFilePath = $newDir . $separator . $fileName; // creates temp file inside FileDrop directory if (move_uploaded_file($tmpName, $tempFilePath)) { // moves file to tmp folder $s3FileName = "FileDrop" . substr($newDir, 4) . $separator . $fileName; $result = putFileToS3($s3FileName, $tempFilePath, 'public-read'); deleteDir($newDir); } } } } ?> This is my js code in case you want to see it: function sendEmails() { var fileData = $('#userFile').prop('files')[0]; var formData = new FormData(); formData.append('tags', JSON.stringify(tags)); formData.append('fileName', fileData); $.ajax({ type: "POST", url: "../FileDrop/dbSystem.php", processData: false, contentType: false, data: formData, success: function(result) { result = JSON.parse(result); if (result.validity === "valid emails") { location.reload(); resetInputs(); //IMPORTANT $(".outputDiv").show(); } else { var tagsBrackets = result.emails.toString().replace(/[\[\]']+/g,''); var tagsQuotes = tagsBrackets.replace(/['"]+/g, ''); var tagsInvalid = tagsQuotes.replace(/,/g, ", "); $('#alertModal').modal({show:true}); document.getElementById('invalid').textContent = tagsInvalid; } } }); return false; } I've been stuck on this for so long, so I'd really appreciate the help!! Hi Everyone, I have a rather stupid question, but I haven't been able to find the correct method / syntax to do this. I want to allow users to upload a maximum of 5 photos - less then 5 is OK too. I've been testing the following script and haven't gotten it to ignore error # 4 (no file uploaded): Code: [Select] if ($_FILES['userfile']['error'] == 1 || 2 || 3 || 6 || 7) { echo 'Problem: '; switch ($_FILES['userfile']['error']) { case 1: echo 'File exceeded upload_max_filesize'; break; case 2: echo 'File exceeded max_file_size'; break; case 3: echo 'File only partially uploaded'; break; case 6: echo 'Cannot upload file: No temp directory specified.'; break; case 7: echo 'Upload failed: Cannot write to disk.'; break; } exit; } I will be using a while loop and incrementing through the script (this is simpler version). Does anyone know the proper syntax for the IF statement ' if ($_FILES['userfile']['error'] == 1 || 2 || 3 || 6 || 7)" ? Thanks much, Rick I have another thread, but it's on a different question.
// remake image if(create_image($fileExt, $_FILES["myfile"]["tmp_name"], $_FILES["myfile"]["tmp_name"], 80) !== FALSE){ // generate thumbnail if(generatethumbs2('.'.$fileExt, $_FILES["myfile"]["tmp_name"], 120, $_FILES["myfile"]["tmp_name"], 85) == TRUE){ $aws = new s3; $aws = $aws->putObject($newFileName, $_FILES["myfile"]["tmp_name"]); image_string($username,$newFileName,$mysqli); } }Is my code. How do I access both the remade image AND the thumbnail? Currently, I can only access the thumbnail. I need to be able to access them concurrently for upload to Amazon s3. How do i display the image uploaded after the form has been submitted? After the form is submitted it will be a preview page, so i'm not storing the image type BLOB in MySQL yet. How do i display $_FILES['image']? Code: [Select] <?php if(isset($_POST['submit'])) { //preview page $info = getimagesize($_FILES['image']['tmp_name']); $imagetype = $info['mime']; $tmpname = $_FILES['image']['tmp_name']; $fp = fopen($tmpname,'r'); $data = fread($fp,filesize($tmpname)); $data = addslashes($data); fclose($fp); } else { ?> <form enctype="multipart/form-data" action="http://www.example.com/submit" method="POST"> <input type="file" name="image" value="" size="50" /> <input type="submit" name="submit" value="submit" /> </form> <?php } ?> I have this script from http://lampload.com/...,view.download/ (I am not using a database) I can upload images fine, I can view files, but I want to delete them. When I press the delete button, nothing happens
http://www.jayg.co.u...oad_gallery.php
<form>
<?php $dir = dirname(__FILENAME__)."/images/gallery" ; $files1 = scandir($dir); foreach($files1 as $file){ if(strlen($file) >=3){ $foil = strstr($file, 'jpg'); // As of PHP 5.3.0 $foil = $file; $pos = strpos($file, 'css'); if ($foil==true){ echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />'; echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host //echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/ $file' /><br/>"; } } }?> <input type="submit" name="mysubmit2" value="Delete"> </form>
any ideas please?
thanks
Hello guys, im wonder if ca i syntax the insert so i can insert some fields with alphabeticly shorting by name field Thanks All the variables are set for sure, anyone have any clue why the following isnt inserting anything into the db? Code: [Select] //### Query to insert new item into the database table "items" $query = "INSERT INTO `items`(`name`,`image`,`description`,`description2`,`description3`,`ItemType`,`cash_price `,`credit_price `,`GrowAmount`,`SellAmount`,`MaxOff`,`MaxDef`,`MaxHoes`,`Attack`,`Defense`,`Prestige`,`SafeLimit`,`ProductionQuality`,`ProductionWeight`,`HoDrugUsage`,`HoIncome`,`PurchaseDiscount`,`Informants`,`Pimpness`,`SalesPrice`,`SalesWeight`,`TroopDiscount`,`NotoReq`,`SCReq`,`PRReq`,`Buyable`,`ClassSpecific`,`Sellable`,`Multiple`) VALUES('{$name}','{$image}','{$description}','{$description2}','{$description3}','{$ItemType}','{$price}','{$creditprice}','{$GrowAmount}','{$SellAmount}','{$MaxOff}','{$MaxDef}','{$MaxHoes}','{$Attack}','{$Defense}','{$Prestige}','{$SafeLimit}','{$ProductionQuality}','{$ProductionWeight}','{$HoDrugUsage}','{$HoIncome}','{$PurchaseDiscount}','{$Informants}','{$Pimpness}','{$SalesPrice}','{$TroopDiscount}','{$NotoReq}','{$SCReq}','{$PRReq}','{$Buyable}','{$ClassSpecific}','{$Sellable}','{$Multiple}'"; //### Execute the above query mysql_query($query); Hey, Basically the script runs fine except for the fact its just inserting one user instead of multiple users, anyone have a clue as to why? would be a huge hand, Cheers Code: [Select] <?php if (isset($_POST["submit"]) && $_POST["submit"] == "Recall Selected Informants") { //Force POST values to be INTs $addIDs_ary = array_map('intval', $_POST['chkInv']); //Remove any 'false' value $addIDs_ary = array_filter($addIDs_ary); //Check that there was at least one valid value if(count($addIDs_ary)) { //Create comma separated string of the IDs $addIDs_str = implode(',', $addIDs_ary); //Create and run one query to perform all the adds (of the user) $query = "INSERT INTO hitlist SET hit_id = '($addIDs_str)' AND player_id = '$playerID'"; $sql = "UPDATE players SET Informants = Informants - 1 WHERE id = '$playerID'"; mysql_query($sql) or die(mysql_error()); if(mysql_query($query)) { $selectedCount = count($addIDs_ary); $adddCount = mysql_affected_rows(); echo "{$adddCount} of {$selectedCount} Investigated player(s) were successfully added."; }else{ echo "There was a problem running the query.<br>" . mysql_error(); } }else{ echo "Invalid ID data passed."; } } Code: [Select] elseif($_GET['rma']=="issue"){ session_start(); $rma_id=$_GET['id']; $_SESSION['rma_id']=$rma_id; $rma_issued=$_POST['rma_issued']; if($rma_issued=="y"){ $length = 2; $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $string= microtime(true); for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } for ($p = 0; $p < $length; $p++) { $string2 .= $characters[mt_rand(0, strlen($characters))]; } $string="".$string2."".$string; $string=explode(".",$string); $string=$string[0].$string[1]; $rma_number=$string; date_default_timezone_set('US/Eastern'); $rma_date_issued = date("F j, Y, g:i A T"); $rma_month_issued = date("m"); $rma_year_issued = date("Y"); $sql2000000="UPDATE $tbl_name4 SET rma_number='$rma_number', rma_issued='$rma_issued', rma_date_issued='$rma_date_issued', rma_month_issued='$rma_month_issued', rma_year_issued='$rma_year_issued', returned='n' WHERE rma_id = $rma_id"; mysql_query($sql2000000); header("Location: ./acp_admincp.php?rma=issued"); } The above isn't inserting anything into the DB... not even the Date information. |