Jump to content

Search the Community

Showing results for tags 'file upload'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

Found 16 results

  1. Hi all ! I have been experimenting with a bit of code that uploads file to the server. The image is previewed once selected and can then be uploaded. The uploaded image is then selected and displayed. Here is the code usp5.php <?php error_reporting(E_ALL); require_once 'DB.php'; $uploaddir = 'D:/xampp/php/internals/uploads/'; # Outside of web root // echo $uploadfile."<br>"; // exit(); if(isset($_POST['upload'])) { $blob = "BLOB"; $filename = $_FILES['userfile']['name']; $filetype = $_FILES['userfile']['type']; $tmp_filename = $_FILES['userfile']['tmp_name']; $uploadfile = tempnam($uploaddir, "upm"); if (move_uploaded_file($tmp_filename, $uploadfile)) { try { $query = "INSERT INTO images (name, original_name, mime_type, images) VALUES (?,?,?,?)"; $stmt = $link->prepare($query); $stmt->bind_param('ssss',$uploadfile,$filename,$filetype,$blob); if($stmt->execute()){ $id=$stmt->insert_id; // get the just inserted id } else{ echo "Error : ".$link->error; } } catch(mysqli_sql_exception $imageException) { if ($imageException->getCode() === MYSQL_ER_DUP_ENTRY) { echo'The filename is already taken, please choose a different name.'; return false; } else { // rethrow exception throw $imageException; } } } if(!is_numeric($id)) { die("File id must be numeric"); } $query = 'SELECT name, mime_type FROM images WHERE id=?'; $stmt = $link->prepare($query); $stmt->bind_param('i',$id); $stmt->execute(); $stmt->bind_result($filename,$type); $stmt->store_result(); $stmt->fetch(); $stmt->free_result(); if(is_null($filename) || count($filename)===0) { die("File not found"); } header("Content-Type: " . $type); // echo "<div class='div2'>"; // works good without the div. Divs cause the binary dump to show instead echo '<img src="'.readfile($filename).'"alt="">'; // echo "</div>"; } ?> <html> <head> <title>File Upload To Database</title> <link class="jsbin" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" > <link rel="stylesheet" type="text/css" media="screen" href="divs.css" /> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script> <meta charset=utf-8 /> </head> <body> <form name="upload" action="#" method="POST" enctype="multipart/form-data"> Select the file to upload: <br> <input type="file" name="userfile" onchange="readURL(this)"; /><br> <br><input type="submit" name="upload" value="Upload"> <div class = "div1"> <img id="image" src="#" alt="load image" /> <!-- This displays the image. --> </div> </form> <!-- <img class="div2" src="'<?php // readfile($filename); ?>'" alt="load image" /> --> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#image') .attr('src', e.target.result) .width(200) .height(200); }; reader.readAsDataURL(input.files[0]); }else{ alert( "File not selected or browser incompatible." ); } } </script> </body> </html> divs.css .div1 { height:220px; width: 220px; display:block; margin:5px; border:1px solid navy; background-color:#ffffbb; } .div2 { height:350px; width: 350px; display:block; margin-left:1px; border:1px solid navy; background-color:#ffaaff; } img{ max-width: 100%; max-height: 100%; } In the first preview, before upload, a bigger image is automatically reduced to fit into a 200px by 200px due to the width and height set in the jquery. After the image is loaded on the server and is selected using the id of the image, I am unable to fit the same in a div to restrict the size of the image to any arbitrary given dimensions. Kindly help me with that. Is it possible to display both the images simultaneously in two separate divs ? How ? Any security issues in this ? Thanks all !
  2. Guest

    PHP file upload problem

    I am trying to send a file through Rest Webservices using php and i was able to send the file through email but i'm having problems with the webservices, it only receives an empty file. <?php ini_set('display_errors', 1); error_reporting(E_ALL); if($_POST) { //check if its an ajax request, exit if not if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { $output = json_encode(array( //create JSON data 'type'=>'error', 'text' => 'Sorry Request must be Ajax POST' )); die($output); //exit script outputting json data } //Sanitize input data using PHP filter_var(). $user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING); $user_company = filter_var($_POST["user_company"], FILTER_SANITIZE_STRING); $user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL); $country_code = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT); $phone_number = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT); $message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING); $to_email = $user_email; //Recipient email, Replace with own email here $from_email = 'jveleztorres@wovenware.com'; //From email address (eg: no-reply@YOUR-DOMAIN.com) //additional php validation if(strlen($user_name)<4){ // If length is less than 4 it will output JSON error. $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'.realpath(sys_get_temp_dir()."\\".basename($_FILES['file_attach']['tmp_name'])))); die($output); } if(strlen($user_company)<2){ // If length is less than 4 it will output JSON error. $output = json_encode(array('type'=>'error', 'text' => 'Company Name is too short or empty!')); die($output); } if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!')); die($output); } if(!filter_var($country_code, FILTER_VALIDATE_INT)){ //check for valid numbers in country code field $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in country code')); die($output); } if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number')); die($output); } if(strlen($phone_number) != 7){ // Phone number can contain 4 characters $output = json_encode(array('type'=>'error', 'text' => 'Must only contain 7 numbers without including country code')); die($output); } if(strlen($message)<3){ //check emtpy message $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.')); die($output); } if(isset($_FILES['file_attach'])) //check uploaded file { //get file details we need $file_tmp_name = $_FILES['file_attach']['tmp_name']; $file_name = $_FILES['file_attach']['name']; $file_size = $_FILES['file_attach']['size']; $file_type = $_FILES['file_attach']['type']; $file_error = $_FILES['file_attach']['error']; //exit script and output error if we encounter any if($file_error>0) { $mymsg = array( 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 3=>"The uploaded file was only partially uploaded", 4=>"No file was uploaded", 6=>"Missing a temporary folder" ); $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error])); die($output); } } //read from the uploaded file & base64_encode content for the mail $convertIt = $_FILES['file_attach']['type']; $whatIWant1 = substr($convertIt, strpos($convertIt, "/") + 1); if($whatIWant1 === "octet-stream"){ $whatIWant = "zip"; } else{ $whatIWant = $whatIWant1; } //email body with attachment $message_body = "Message: ".$message."<br/>"."Contractor".$user_name."<br/>"."Company:".$user_company."<br/>"."Email : ".$user_email."<br/>"."Phone Number : (".$country_code.") ". $phone_number."<br/>"."Access Bonita to initiate Invoice Approval process" ; $handle = $_FILES["file_attach"]["name"]; $uploadfile1 = "C:/Users/hrivera/Documents/".basename($_FILES['file_attach']['name']); $handle =fopen($uploadfile1,"r"); $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['file_attach']['name'])); if (move_uploaded_file($_FILES['file_attach']['tmp_name'], $uploadfile)) { require 'PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = ''; // SMTP username $mail->Password = ''; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->From = ''; $mail->addAddress(''); $mail->addAttachment($uploadfile, $user_company.' Invoice.'.$whatIWant); // Add attachments $mail->isHTML(true); // Set email format to HTML $mail->Subject = $user_company.' Invoice Approval Requested'; $mail->Body = $message_body; $mail->AltBody = ', Thank you and have a nice day'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } } //Login to bonitasoft by using REST API function httpRequest($host, $port, $method, $path, $params) { $paramStr = ""; if ($method == "GET" || $method == "POST" ) { foreach ($params as $name => $val) { $paramStr .= $name . "="; $paramStr .= $val; $paramStr .= "&"; } } // Assign defaults to $method and $port, if needed if (empty($method)) { $method = "GET"; } $method = strtoupper($method); if (empty($port)) { $port = 8081; // Default HTTP port } // Create the connection $sock = fsockopen($host, $port); if (!$sock) { echo "Error! Couldn't open the file."; } else { if ($method == "GET") { $path .= "?" . $data; } //Necessary header fputs($sock, "$method $path HTTP/1.1\r\n"); fputs($sock, "Host: $host\r\n"); fputs($sock, "Content-type: application/x-www-form-urlencoded\r\n"); if ($method == "PUT") { fputs($sock, "Content-length: " . strlen($params) . "\r\n"); }elseif ($method == "POST") { fputs($sock, "Content-length: " . strlen($paramStr) . "\r\n"); } fputs($sock, "Connection: close\r\n\r\n"); if ($method == "PUT") { fputs($sock, $params); } elseif ($method == "POST") { fputs($sock, $paramStr); } // Buffer the result $result = ""; do { $temp = fgets($sock,1024); $result .= $temp; }while($temp !=""); fclose($sock); return $result; } } //Call to Function that logs into bonitasoft $resp = httpRequest("localhost", 8081, "POST", "/bonita/loginservice", array("username" => "walter.bates", "password" => "bpm")); $string = $resp; echo $resp; //Gets JSESSIONID preg_match("/Set-Cookie: (.*?) Path/",$string, $display); //Process to Start Case with variables $data = array("processDefinitionId"=>"5623733440372144264", "variables" => array(array("name" => "contractorComment", "value" => "$message"),array("name" => "contractorName", "value" => "$user_name"),array("name" => "contractorCompanyName", "value" => "$user_company"),array("name" => "contractorEmail", "value" => "$user_email"),array("name" => "contractorPhone", "value" => "("."$country_code".") "."$phone_number"))); $options = array( "http" => array( "method" => "POST", "header"=> "POST /bonita/API/bpm/case/ HTTP/1.1\r\n". "Host: localhost\r\n". "Cookie: ". $display[1]."\r\n". "Content-Type: application/json\r\n" . "Accept: application/json\r\n". "Cache-Control: no-cache\r\n". "Pragma: no-cache\r\n". "Connection: close\r\n\r\n", "content" => json_encode($data) ) ); $url = "http://localhost:8081/bonita/API/bpm/case/"; $context = stream_context_create( $options ); $result = file_get_contents( $url, false, $context ); $response = json_decode($result); echo print_r($response); preg_match('/"rootCaseId":"(.*?)",/',$result, $case_id); //Process to Attach Document to case //problem lies here $data1 = array("caseId"=> "$case_id[1]","file"=>realpath(sys_get_temp_dir()."\\".basename(sha1($_FILES['file_attach']['name']))),"name"=> "doc_Invoice", "fileName"=>"Invoice.pdf","description" => "Invoice"); echo json_encode($data1); switch (json_last_error()) { case JSON_ERROR_NONE: echo ' - No errors'; break; case JSON_ERROR_DEPTH: echo ' - Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: echo ' - Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: echo ' - Unexpected control character found'; break; case JSON_ERROR_SYNTAX: echo ' - Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: echo ' - Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: echo ' - Unknown error'; break; } $options1 = array( "http" => array( "method" => "POST", "header"=> "POST /bonita/API/bpm/case/ HTTP/1.1\r\n". "Host: localhost\r\n". "Cookie: ". $display[1]."\r\n". "Content-Type: application/json\r\n" . "Accept: application/json\r\n". "Cache-Control: no-cache\r\n". "Pragma: no-cache\r\n". "Connection: close\r\n\r\n", "content" => json_encode($data1) ) ); $url1 = "http://localhost:8081/bonita/API/bpm/caseDocument"; $context1 = stream_context_create($options1); $result1 = file_get_contents($url1, false, $context1); $response1 = json_decode($result1) ; echo print_r($response1); } ?>
  3. I'm looking to order my upload files in a specific order. I believe the default is a random upload order, but I would like to change this based on the file name, which I'm having difficulty with. The file names would be for example; '01 smiley' '02 dog' '03 cat' Currently I used a 'Drag & Drop' multiple file upload although this just uploads in any random order to my database table, I'd like to upload it by numeric order as above. Code so far (upload code works, just the order needs work)... $count = count($_FILES['upload']['name']); $in=0; while($in<$count) { //upload here $in++; } I think I need to sort()? before my while loop, but having difficulty getting this correct. How would I be able to sort each file into a correct order. Many thanks.
  4. Trying to find a way to combine two scripts. 1. picture upload script that uploads the picture, gives it a new unique name, saves it to a specified directory and saves the unique name path to a user database (basically a user profile picture upload). and 2. A larger user login script I already have worked into my website that allows users to register on the site, view and edit their profile, log in, log out, etc. The issue is in part that I don't understand PHP well enough to figure out how to work these in together and the other part is that they are written a bit differently from each other so it's making it hard to combine them. One of the user profile fields I am using with script 2 is valued "bpic" and is where path to the uploaded picture would go. I have been successful in getting the unique path to save in that field in the database but absolutely can NOT seem to get the picture to actually upload and save in the "avatars" directory no matter what I try. I have determined that because my user script already calls the database, has an "INSERT INTO" database command and has error and success messages, I could take out those aspects of the picture uploading code below so I'm just trying to figure out where to place the "$new_image_name =" and "$bpic = " lines and how and where to code in the "move_uploaded_file" portion so the file actually uploads lol. (These are the two portions of the script below that I have decided I need to use and find a place to paste): $new_image_name = md5( rand (0, 1000) . rand (0, 1000) . rand (0, 1000) . rand (0, 1000) ) .'.jpg'; $bpic = 'avatars/' . $new_image_name; if(move_uploaded_file($_FILES['bpic']['tmp_name'], $bpic)) { } Any help and direction is appreciated! I have been at this for weeks with no success. It took me a while to actually get the picture upload script to work on it's own and upload the file, give it a unique name and save that unique name in both the directory and database so it can be found and displayed correctly. But anyway, the upload picture script works perfect now on it's own, but I gotta figure out how to place it in the script I already have. Upload Picture Script: (note: "bpic" is the field name of the file upload on the form and "$bpic" both references the field in the database and the file path to be created for the pic.) <?php //This is the directory where images will be saved $new_image_name = md5( rand (0, 1000) . rand (0, 1000) . rand (0, 1000) . rand (0, 1000) ) .'.jpg'; $bpic = 'avatars/' . $new_image_name; // Connects to your Database mysql_connect("businessdb1.db.9878324.hostedresource.com", "businessdb1", "Spidey148!") or die(mysql_error()) ; mysql_select_db("businessdb1") or die(mysql_error()) ; //Writes the photo to the server if(move_uploaded_file($_FILES['bpic']['tmp_name'], $bpic)) { //Writes the information to the database mysql_query("INSERT INTO `employees` VALUES ('$bpic')") ; //Tells you if its all ok echo "The file has been uploaded, and your information has been added to the directory"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> As far as the user upload script goes, I'm not sure which page to work this code into so I don't want to make this post insanely long by posting every potential page (database.php - which I think is it, process.php, session.php, constants.php). The exact same code I am using is downloadable for free here: http://blog.geotitles.com/2011/07/php-login-script/ so you can see exactly how my code is formatted. I understand that's a lot of information and actually quite a bit of work for someone to look at and offer help, but if anyone is up to it, I would really appreciate any advice and help with this as I have been pulling out my hair trying to figure this out and it's going to completing a website that a lot of bands are waiting to sign up for! Thanks so much for your time! -David.
  5. Hi everyone, first post on the forum, so sorry if I've missed anything... I've been doing small bits of php/msql recently and I'm trying to write some code that will display a pdf or jpg that has certain keywords associated with it. I've created a table and added 4 fields/columns. ID, filename, thumbnail, keywords How can I get php to display a PDF/JPG that has a certain keyword associated with it? so... say I had 10 different animal pictures, and I wanted to see the dog picture and the dog picture had 'brown' and 'dog' as keywords in the database how and what would the code look like to display this on a webpage search? Hope I'm making sense Stu
  6. Hi. I have a file upload script and I want to allow css files to be uploaded as well. Here is my code allowing the certain filetipes allowed to be uploaded. || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) When I tried doing this code to allow css files through || ($_FILES["file"]["type"] == "text/css")) it didn't work. Should it? If not, what did I do wrong?
  7. Hey guys does anyone know why this doesnt upload large files? 6/7mb... the PHP ini files seem fine... i even overdone it by upload_max_filesize = 20M; post_max_size = 20M; max_execution_time = 400; max_input_time = 400; memory_limit = 900M; was over the top but was just trying to find answer... i have the code here and attaching a full code thing. $src1 = '../../image_uploads/layout_uploads/temp/temp/'.$image_name.'.jpg'; $src2 = '../../image_uploads/layout_uploads/temp/'.$image_name.'.jpg'; // Get Rid Of Old Files unlink($src1); if(!empty($src2)){ unlink($src2); } move_uploaded_file($_FILES["img_upload"]["tmp_name"], $src1); // INIT list($old_width, $old_height) = getimagesize($src1); if($old_width > $old_height){ $total_w = $old_width; $total_h = $old_width; $image_top1 = $total_h - $old_height; $image_top2 = $image_top1 * 0.5; $image_top = $image_top2; $image_left = 0; } else { $total_w = $old_height; $total_h = $old_height; $image_left1 = $total_w - $old_width; $image_left2 = $image_left1 * 0.5; $image_top = 0; $image_left = $image_left2; } $create_bg = imagecreatetruecolor($total_w,$total_h); // Full Blue // CREATE WHITE BG $white = imagecolorallocate($create_bg, 255, 255, 255); imagefilledrectangle($create_bg, 0, 0, $total_h, $total_w, $white); // GET IMAGE $create_image = imagecreatefromjpeg($src1); // CREATE IMAGE imagecopyresampled($create_bg, $create_image, $image_left, $image_top, 0, 0, $old_width, $old_height, $old_width, $old_height); // OUTPUT if(filesize($src1) > 2000000){ imagejpeg($create_bg, $src2, 60); } else if(filesize($src1) < 2000000 && filesize($src1) > 1000000){ imagejpeg($create_bg, $src2, 70); } else if(filesize($src1) < 1000000 && filesize($src1) > 100000){ imagejpeg($create_bg, $src2, 80); } else if(filesize($src1) < 100000 && filesize($src1) > 50000){ imagejpeg($create_bg, $src2, 90); } else { imagejpeg($create_bg, $src2, 95); } unlink($src1);
  8. I have a working example below of a single file input upload via php and now I'd like to upload multiple files either by iterating through each input type="file". I've read that the multiple attribute on the input tag is not supported below IE10 so I think the best way would be to have several input type=files in order to loop through them any help is appreciated <input type="file" name="FilesUpload1" class="filesUpload" /> <input type="file" name="FilesUpload2" class="filesUpload" /> <input type="file" name="FilesUpload3" class="filesUpload" /> <?php //Сheck that we have a file if((!empty($_FILES["FilesUpload1"])) && ($_FILES['FilesUpload1']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['FilesUpload1']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); //check file extension if ((($ext == "gif") || ($ext == "jpeg") || ($ext == "jpg") || ($ext == "png") || ($ext == "doc") || ($ext == "docx") || ($ext == "rtf") || ($ext == "txt") || ($ext == "pdf")) //check file mime && (($_FILES["FilesUpload1"]["type"] == "image/gif") || ($_FILES["FilesUpload1"]["type"] == "image/jpeg") || ($_FILES["FilesUpload1"]["type"] == "image/jpg") || ($_FILES["FilesUpload1"]["type"] == "image/pjpeg") || ($_FILES["FilesUpload1"]["type"] == "image/x-png") || ($_FILES["FilesUpload1"]["type"] == "image/png") || ($_FILES["FilesUpload1"]["type"] == "application/msword") || ($_FILES["FilesUpload1"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") || ($_FILES["FilesUpload1"]["type"] == "application/rtf") || ($_FILES["FilesUpload1"]["type"] == "text/plain") || ($_FILES["FilesUpload1"]["type"] == "application/pdf")) //check file size is less than 1048576 bytes [1 MB] && (($_FILES["FilesUpload1"]["size"] < 1048576))) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/../entries/'.$_POST["CompanyName"].'-'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['FilesUpload1']['tmp_name'],$newname))) { echo "It's done! Your file has been saved."; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["FilesUpload1"]["name"]." already exists"; } } else { echo "Error: Only .gif, .jpeg, .jpg, .png, .doc, .docx, .rtf, .txt, .pdf files under 1 MB are accepted for upload."; } } else { echo "Error: No file uploaded"; } ?>
  9. i am trying to make a filter for file uploads that users upload on my site and I was just wondering to know if there's any book on how I can make a advance file upload form with advance security system installed on it.
  10. I added a file upload option to the contact form and it works perfectly when I comment out <?php wp_footer(); ?> from the footer.php I'm assumed the admin bar search form caused a conflict, so I included the enctype="multipart/form-data" code to the form like this; admin-bar.php $form = '<form action="' . esc_url( home_url( '/' ) ) . '" method="get" id="adminbarsearch" enctype="multipart/form-data" >'; $form .= '<input class="adminbar-input" name="s" id="adminbar-search" type="text" value="" maxlength="150" />'; $form .= '<input type="submit" class="adminbar-button" value="' . __('Search') . '"/>'; $form .= '</form>'; When I include the admin bar, the $_FILES array returns back empty and I can't figure out why. This is a custom template so I viewed source from the browser to see if I was missing a form, but no luck. There are other forms, but all from my contact form, which works without the admin bar. This is Wordpress 3.5.1 running on a GoDaddy environment. Ideas?
  11. Hey Wondered if anyone could help me with this. I had this right a couple of days ago but for some reason it wasn't in my code yesterday and since rebuilding, has ceased to work. I have a multi file upload that creates a directory as the name of the username variable ($username_entry). When using this variable in the file path along with the variable for the name of the file ($name) the file path simply puts the variable text "$name" as some random blank file within the newly created directory. Im sure it something pretty small that needs editing to use 2 variables in 1 path. Anyway here's the code i need tweaking. Thanks to anyone that can help me <?php if (isset($_FILES['upload']) === true) { $files = $_FILES['upload']; for($x = 0; $x < count($files['name']); $x++) { $name = $files['name'][$x]; $tmp_name = $files['tmp_name'][$x]; move_uploaded_file($tmp_name, 'user_images/'.$username_entry.'/ . $name'); } ?> Its the move_uploaded_file($tmp_name, 'user_images/'.$username_entry.'/ . $name'); where i think the problem lies.......any takers? Thanks.
  12. Hi everyone - thanks for taking the time to read this. I have a form with 35 file input boxes as part of a CMS for my customer to upload 35 pictures of each his products. The breakdown of that is 7 pictures of the black version, 7 pictures of the blue, 7 pictures of the grey, 7 pictures of the red, and 7 pictures of the white version of each product. So that's 35 total pictures he needs to upload. Additionally, for each of those files that he uploads, a smaller "thumbnail" sized picture needs to be made. I have a file upload script that I always use that works beautifully - when there's one file to upload. I'm not sure how to apply it in this case for 35 files. Each input box has a unique name (black1, black2...black7, blue1, blue2...blue7, etc) so, technically I could repeat the upload code 35 times with the unique name of each file input box to do this, but that is obvoiusly extremely inefficient. I'm hoping someone here can help me out with a better solution. An additional requirement is that the names of the files be stored in a database. All of the filenames of the black pictures should be put into a string, separated by commas, and stored in the `blackpics` column of the database. All of the filenames of the blue pictures should be put into a string, separated by commas, and stored in the `bluepics` columns of the database. And so on for the grey, red, and white pictures. Here is the code that I have now to upload one file. It gets the file from input box "file", checks that it's of the right extension (an image file), checks the filesize, creates a random file name with a random number and timestamp, creates a thumbnail (448px x 298px - big thumbnail, I know), checks that the original image uploaded was of the right dimensions (873px x 581px), and if everything is okay, I end up with the big file saved in ../images/store/big/ and the thumb saved in ../images/store/small/. They both have the same filename, they're just stored in different directories. Temporary files are deleted and all that, and if there are any errors, the files are deleted. As I said, this works great for one file. So what I need to do is modify the code so that it does all of this for input box "black1", "black2"..."black7", then saves all the filenames into a string (black1.jpg,black2.jpg,black3.jpg,black4.jpg,black5.jpg,black6.jpg,black7.jpg) which I can then store in the 'blackpics' column of the database. Same for the blue, grey, red, and white. I don't need any help with the database part. I'm thinking that I need to create a function containing the file upload script that returns the filename. Then call that function 35 times, one for each of the input boxes. But I could be wrong. If anyone could offer me any assistance, I would greatly appreciate it. Here is the code for the upload script: <?php $filename = $_FILES["file"]["name"]; $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention $file_ext = substr($filename, strripos($filename, '.')); // get file name $filesize = $_FILES["file"]["size"]; $allowed_file_types = array('.jpg','.gif','.png', '.JPG'); if (in_array($file_ext,$allowed_file_types) && ($filesize < 1024000)) { // rename file $rand = rand(1,100000000); $time = time(); $newfilename = $rand . $time . $file_ext; if (file_exists("../images/store/big/" . $newfilename)) { // file already exists error $err[] = "You have already uploaded this file."; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "../images/store/big/" . $newfilename); $pathToImage = '../images/store/big/' . $newfilename; $pathToThumb = '../images/store/small/' . $newfilename; $last4 = substr($pathToImage, -4); switch(strtolower($last4)) { case '.jpeg': $img = imagecreatefromjpeg($pathToImage); break; case '.jpg': $img = imagecreatefromjpeg($pathToImage); break; case '.png': $img = imagecreatefrompng($pathToImage); break; case '.gif': $img = imagecreatefromgif($pathToImage); break; default: exit('Unsupported type: '. $pathToImage); } $max_width = 448; $max_height = 298; // Get current dimensions $old_width = imagesx($img); $old_height = imagesy($img); // Calculate the scaling we need to do to fit the image inside our frame $scale = min($max_width/$old_width, $max_height/$old_height); // Get the new dimensions $new_width = ceil($scale*$old_width); $new_height = ceil($scale*$old_height); $tmp_img = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); switch(strtolower($last4)) { case '.jpeg': imagejpeg($tmp_img, $pathToThumb); break; case '.jpg': imagejpeg($tmp_img, $pathToThumb); break; case '.png': imagepng($tmp_img, $pathToThumb); break; case '.gif': imagegif($tmp_img, $pathToThumb); break; default: exit('Unsupported type: '. $pathToImage); } imagedestroy($tmp_img); imagedestroy($img); } } elseif (empty($file_basename)) { $err[] = "Select a file to upload"; } elseif ($filesize > 1024000) { $err[] = "File size limit exceeded"; } else { $err[] = "File type not allowed"; unlink($_FILES["file"]["tmp_name"]); } list($width, $height) = getimagesize("../images/store/big/$newfilename"); if ($width != "873" || $height != "581") { $err[] = "File dimensions error"; unlink("../images/store/big/$newfilename"); unlink("../images/store/small/$newfilename"); } ?> And in the body I have the file upload fields as so... <input type="file" name="black1" disabled="1"> <input type="file" name="black2" disabled="1"> ... <input type="file" name="black7" disabled="1"> <input type="file" name="blue1" disabled="1"> <input type="file" name="blue2" disabled="1"> ... <input type="file" name="blue7" disabled="1"> and so on for grey, red, and white. Like I said, if anyone can help me out, I would greatly appreciate it. And if you made it all the way down here, thanks again for taking the time to read all of this.
  13. Any one please help me... I have three input type file in the form and the values are passed to a function if(isset($_POST['submit'])=='submit') { $result=$obj->insertdata($_POST); } ..form <form method="post" enctype="multipart/form-data"> <input type="file" name="f_image" style="width:220px;"/> <input type="file" name="ev_image" style="width:220px;"/> <input type="file" name="ga_thumb_image" style="width:220px;"/> My question is how do I send the value of each file one by one to this function public function file_upload($a, $b, $c) { print_r($a); } from the below function public function insertdata($a) { $ev_banner=self::file_upload($_FILES['ev_image'],'ev_image','gallery/banner'); } the answer i am getting is Array ( [f_image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 => 0 ) [ev_image] => Array ( [name] => 027.JPG [type] => [tmp_name] => [error] => 1 => 0 ) [ga_thumb_image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 => 0 ) I only want Array ( [name] => 027.JPG [type] => [tmp_name] => [error] => 1 => 0 ) this out put Please help
  14. Hey all, hoping to get this code solved. I am building an image gallery for a client's website and wanted a way for the client to upload their own images from the back end and shows up on the website page for the pictures. I am using color box as the lightbox feature for the photos and on the webpage thumbnails are displayed in rows. In the backend, I have the upload page and here is my form: <form name="form" action="../uploader.php" method="POST" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="uploaded_file" id="uploaded_file"> <input type="hidden" name="MAX_FILE_SIZE" value="10485760" /><br /> <input type="hidden" name="image_type" value="" /><br /> <input type="submit" name="submit" value="Submit"> <input type="hidden" name="MM_insert" value="form" /> </form> From the admin upload page, the client can upload their image and it will save it into the "image/uploads/" folder. Here is the uploader.php script: <?php //Сheck that we have a file if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 1.4MB $filename = basename($_FILES['uploaded_file']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && ($_FILES["uploaded_file"]["size"] < 10485760)) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/images/uploads/'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) { echo "Upload Complete! "; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists"; } } else { echo "Error: File too big to upload"; } } else { echo "Error: No file uploaded"; } ?> Now the website page will display all the images in the "images/uploads" folder and will update itself when new photos are uploaded. Here is the gallery code from the website: <div class="gallery"> <?php /* function: returns files from dir */ function get_files($images_dir,$exts = array('jpg')) { $files = array(); if($handle = opendir($images_dir)) { while(false !== ($file = readdir($handle))) { $extension = strtolower(get_file_extension($file)); if($extension && in_array($extension,$exts)) { $files[] = $file; } } closedir($handle); } return $files; } /* function: returns a file's extension */ function get_file_extension($file_name) { return substr(strrchr($file_name,'.'),1); } /** settings **/ $images_dir = 'images/uploads/'; $images_per_row = 5; /** generate photo gallery **/ $image_files = get_files($images_dir); if(count($image_files)) { $index = 0; foreach($image_files as $index=>$file) { $index++; echo '<a href="',$images_dir.$file,'" class="photo-link group1" rel="uploads"><img src="timthumb.php?src=',$images_dir.$file,'&h=150&w=150" /></a>'; if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; } } echo '<div class="clear"></div>'; } else { echo '<p>There are no images in this gallery.</p>'; } ?> </div> With the help from timthumb.php and timthumb-config.php I am able to produce the thumbnails for the website. Once clicked, brings up the colorbox feature for the image slideshow. For some reason, this code only can use image sizes under 1500px. How can I upload a bigger image and resize it to save itself into the "images/uploads/" folder to be under 1500px? Please look at my codes and let me know where and what code I need to produce the resized image. Thanks!
  15. Hi Guys, I been googling every where to find some code sample that will enable me to upload multiple photos from an iphone running IOS 6 to a website. According to what I had read, Safari for IOS supports this by using a mutiple boolean value in an input tag. And that works fine. When the button is pressed to select pictures I am able to select multiple pictures, what I can't seem to figure out is how on the server side I can grab those multiple images selected. Here is code sample( I found online not mine) that I was able to use . And it works fine with 1 image; I can upload the image. But with 2 or more I can't seem to figure out how to make it happen. Thank you. <?php $result=0; if (trim($_POST["action"]) == "Upload File") { //**** User Clicked the Upload File Button //*********** Execute the Following Code to Upload File ************* $imagename = basename($_FILES['image_file']['name']); // grab name of file $result = @move_uploaded_file($_FILES['image_file']['tmp_name'], $imagename); // upload it if ($result==1) echo("Successfully uploaded: <b>".$imagename."</b>"); // did it work? } // end if ?> <html> <head> <title>Upload file script</title> </head> <body> <form method='POST' enctype='multipart/form-data' name='frmmain' action='up2.php'> Browse for Image (jpg): <input type="file" name="image_file" size="35"> <br> <input type="submit" value=" Upload File " name="action" multiple> </form> <br> <?php if ($result==1) echo("<img src='".$imagename."'>"); // display the uploaded file ?> </body> </html> Can any one help me figure out how I can make this happen?
  16. The code works but it puts the files into /uploadir/. The users directories go by their email addresses ($email). Using the error reporting it tells me: ! ) Notice: Undefined variable: email in /var/www/html/Lab5/uploadfile.php on line 10 Call Stack # Time Memory Function Location 1 0.0010 129288 {main}( ) ../uploadfile.php:0 Any help is much appreciated!! <?php error_reporting(E_ALL | E_NOTICE); ini_set('display_errors','1'); session_start(); if ($_COOKIE["auth"] == "1") { $file_dir = "/var/www/html/uploaddir/$email"; foreach($_FILES as $file_name => $file_array) { echo "path: ".$file_array["tmp_name"]."<br/>\n"; echo "name: ".$file_array["name"]."<br/>\n"; echo "type: ".$file_array["type"]."<br/>\n"; echo "size: ".$file_array["size"]."<br/>\n"; if (is_uploaded_file($file_array["tmp_name"])) { move_uploaded_file($file_array["tmp_name"], "$file_dir/".$file_array["name"]) or die ("Couldn't copy"); echo "File was moved!<br/>"; } } } else { //redirect back to login form if not authorized header("Location: userlogin.html"); exit; } ?>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.