Jump to content

Search the Community

Showing results for tags 'image 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 8 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. I am using a simple image upload. http://www.w3schools.com/php/php_file_upload.asp It gives me 2 errors like this. Warning: move_uploaded_file(C:/xampp/htdocs/home/upload/images/grandpix 2.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\home\upload\post.php on line 174 Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpF915.tmp' to 'C:/xampp/htdocs/home/upload/images/grandpix 2.jpg' in C:\xampp\htdocs\home\upload\post.php on line 174 This is my code. Post.php . I see that it's the "$target_dir" issue. How can I fix it? if(isset($_FILES['fileToUpload'])){ if(!empty($_FILES['fileToUpload']['name'])) { $target_dir = $_SERVER['DOCUMENT_ROOT'].'/home/upload/images/'; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { $errors[] = 'File is not an image.'; $uploadOk = 0; } // Check if file already exists if (file_exists($target_file)) { $errors[] = 'Sorry, file already exists.'; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { $errors[] = 'Sorry, your file is too large.'; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.'; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $errors[] = 'Sorry, your file was not uploaded.'; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { $errors[] = 'Sorry, there was an error uploading your file.'; } } $insert_image = $db->prepare("INSERT INTO images(user_id, item_id, image_path, date_added) VALUES(:user_id, :item_id, :image_path, :date_added)"); $insert_image->bindParam(':user_id', $userid); $insert_image->bindParam(':item_id', $item_id); $insert_image->bindParam(':image_path', $target_file); $insert_image->bindParam(':date_added', $date_added); if(!$insert_image->execute()) { $errors[] = 'There was a problem uploading the image!'; } else { if(empty($errors)) { $db->commit(); $success = 'Your post has been saved.'; } else { $db->rollBack(); } } } else { $errors[] = 'An image is required!'; } }
  3. Hi Guys, I'm looking for an excellent image manager for my website, it will be for uploading large image files for products to be sold online, the image program would need to be easy to install and integrate with my system. Preferable written mainly in PHP, It would need to reduce the size of the image but keep the quality of the image still. Kind of the same as how image manage their image uploads, or Photobucket. It doesn't have to be FREE, I don't mind forking out for a quality programme. But will also use a FREE open source program if it does the job. Has anyone got any ideas or links to where I could find the best options. I have researched this myself and found basic scripts, this isn't what I'm looking for. Cheers for reading guys.
  4. I have a form that has some predefined images that are already uploaded, if however the user wants to add a new picture they select other from the form and then the image should be uploaded and added to database. The upload and add code is below. It appears that if I select one of the predefined images then the value is added to the db without any problems, the problem arises when a new image is to be uplaoded. The code to add and uplaoad <?php if(isset($_POST['submit'])){ //set variables from form $identifier=$_POST['identifier']; $headline=$_POST['headline']; $content=addslashes($_POST['content']); //echo $content; $photo=$_POST['image']; echo $photo; if($photo!='other'){ $image=$photo; } else{ //upload image $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','.png','.gif','.bmp'); //echo $file_basename; //echo $file_ext; if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000)) { // rename file $newfilename = mktime() . $file_ext; echo $newfilename; if (file_exists("http://www.jasondoyleracing.com/news-images/" . $newfilename)) { // file already exists error $message= "You have already uploaded this file."; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "http://www.jasondoyleracing.com/news-images/" . $newfilename); $image=$newfilename; } } } $today=date("Y-m-d"); echo $today; preg_match("/<p[^>]*>(.*)<\/p>/",$content,$matches); //print_r($matches); $intro = strip_tags($matches[1]); //removes anchors and other tags from the intro //update page content echo $image; echo $intro; $add_news="INSERT INTO `tbl_news`(`identifier`,`headline`,`news_date`,`story`,`image`,`intro`) VALUES ('$identifier','$headline','$today','$content','$image','$intro')"; //echo $add_news; $add_news_sql=mysql_query($add_news)or die(mysql_error()); $message="Your news story has been added"; } ?> Any idea why the upload isn't working
  5. Im currently creating a site for a University project but struggling with the file directories and image uploading. I've managed to get a profile image visible and working but the aim is to allow users to upload many images, which will be visible on their profile page. The image files appear in the main directory instead of in "images/". Also Although they are recognised in the database they don't appear on the profile page of the user... Also within 'functions.php' this function is used to call the images onto a profile page. What does '$user.jpg' need to be replaced with in order to show all the images uploaded by one specific user? Below are the two PHP files concerned with the image upload process. Firstly 'function.php'. <?php $dbhost = '...'; $dbname = '...'; $dbuser = '...'; $dbpass = '...'; $appname = "..."; $link = mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbname, $link) or die(mysql_error()); function createTable($name, $query) { if (tableExists($name)) { echo "Table '$name' already exists<br />"; } else { queryMysql("CREATE TABLE $name($query)"); echo "Table '$name' created<br />"; } } function tableExists($name) { $result = queryMysql("SHOW TABLES LIKE '$name'"); return mysql_num_rows($result); } function queryMysql($query) { $result = mysql_query($query) or die(mysql_error()); return $result; } function destroySession() { $_SESSION=array(); if (session_id() != "" || isset($_COOKIE[session_name()])) setcookie(session_name(), '', time()-2592000, '/'); session_destroy(); } function sanitizeString($var) { $var = strip_tags($var); $var = htmlentities($var); $var = stripslashes($var); return mysql_real_escape_string($var); } function log_image_upload($Filename, $Location, $Time) { //add in sanitization code in here for all variables being parsed. mysql_query("INSERT INTO `images` (`filename`, `location`, `time`) VALUES ('$Filename', '$Location', '$Time')"); } function showProfile($user) { if (file_exists("$user.jpg")) echo "<img src='$user.jpg' border='1' align='left' />"; $result = queryMysql("SELECT * FROM rnprofiles WHERE user='$user'"); if (mysql_num_rows($result)) { $row = mysql_fetch_row($result); echo stripslashes($row[1]) . "<br clear=left /><br />"; } } ?> And secondly 'profile.php' is below ?php // rnprofile.php include_once 'rnheader.php'; if (!isset($_SESSION['user'])) die("<br /><br />You need to login to view this page"); $user = $_SESSION['user']; echo "<h3>Edit your Profile</h3>"; ?> </br> <?php if (isset($_POST['text'])) { $text = sanitizeString($_POST['text']); $text = preg_replace('/\s\s+/', ' ', $text); $query = "SELECT * FROM rnprofiles WHERE user='$user'"; if (mysql_num_rows(queryMysql($query))) { queryMysql("UPDATE rnprofiles SET text='$text' where user='$user'"); } else { $query = "INSERT INTO rnprofiles VALUES('$user', '$text')"; queryMysql($query); } } else { $query = "SELECT * FROM rnprofiles WHERE user='$user'"; $result = queryMysql($query); if (mysql_num_rows($result)) { $row = mysql_fetch_row($result); $text = stripslashes($row[1]); } else $text = ""; } $text = stripslashes(preg_replace('/\s\s+/', ' ', $text)); if (isset($_FILES["image"]["name"])) { $FolderName = 'simple/'; // Setting the upload directory $CurrentTime = time(); // Time of upload (UNIX) $Filename = $user."_".$CurrentTime.".jpg"; // Filename of the file $saveto = $Foldername.$Filename; // Will look something like"images/alex_1365249148.jpg" move_uploaded_file($_FILES["image"]["tmp_name"], $saveto); $typeok = TRUE; switch($_FILES["image"]["type"]) { case "image/gif": $src = imagecreatefromgif($saveto); break; case "image/jpeg": // Both regular and progressive jpegs case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break; case "image/png": $src = imagecreatefrompng($saveto); break; default: $typeok = FALSE; break; } if ($typeok) { list($w, $h) = getimagesize($saveto); $max = 150; $tw = $w; $th = $h; if ($w > $h && $max < $w) { $th = $max / $w * $h; $tw = $max; } elseif ($h > $w && $max < $h) { $tw = $max / $h * $w; $th = $max; } elseif ($max < $w) { $tw = $th = $max; } $tmp = imagecreatetruecolor($tw, $th); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h); imageconvolution($tmp, array( // Sharpen image array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1) ), 8, 0); imagejpeg($tmp, $saveto); log_image_upload($Filename, $saveto, $CurrentTime); // Logging the image upload into MySQL imagedestroy($tmp); imagedestroy($src); } } showProfile($user); echo <<<_END <form method='post' action='rnprofile.php' enctype='multipart/form-data'> Enter or edit your status and/or upload an image:<br /> <textarea name='text' cols='50' rows='4'>$text</textarea><br /> Image: <input type='file' name='image' size='14' maxlength='32' /> <input type='submit' value='Save Profile' /> </pre></form> _END; ?> Any help would be much appreciated! thanks.
  6. I have a web page that lets user upload their profile photo. The PHP script works, but sometimes it just wont upload the photo. It will even give you a success message that the image was uploaded but it wont add the filename to the database nor will it save the file on the server. If you keep trying to upload the same image for couple more times then it will work and upload the photo. So i need some help in debugging it. Where am i going wrong? I am also using this thumb_function.php file which i got from internet, it basically saves thumbnails in a seperate folder, it works fine. Here is the PHP script that i am using. // Check if the button was clicked or not and process the profile updation if(isset($_POST['btnphoto'])){ include('php/thumb_function.php'); $filename = $_FILES["txtphoto"]["name"]; $newfilename = sha1($userid.$email); $extension = substr(strrchr($filename,'.'),1); $newfilename = $newfilename.".".$extension; $allowedExts = array("jpg", "jpeg", "gif", "png"); if ((($_FILES["txtphoto"]["type"] == "image/gif") || ($_FILES["txtphoto"]["type"] == "image/jpeg") || ($_FILES["txtphoto"]["type"] == "image/png")) && ($_FILES["txtphoto"]["size"] < 1048576) && in_array($extension, $allowedExts)){ if ($_FILES["txtphoto"]["error"] > 0){ $msg = "Error: " . $_FILES["file"]["error"] . "<br>"; } else { $path="../photos/".$newfilename; // the path with the file name where the file will be stored, upload is the directory name. if(move_uploaded_file ($_FILES["txtphoto"]["tmp_name"],$path)){ if ($stmt = $mysqli->prepare("UPDATE student_profile SET photo = ? WHERE user_id = ?")) { // Bind the variables to the parameter as strings. $stmt->bind_param("si", $newfilename, $userid); // Execute the statement. $stmt->execute(); // Close the prepared statement. $stmt->close(); } $msg = 'Your Photo has been updated... '; } else { $msg = 'Failed to upload file Contact Site admin to fix the problem'; exit; } $file = $newfilename; $save = $file; $t_w = 100; $t_h = 100; $o_path = "../photos/"; $s_path = "../photos/thumbnails/"; Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path); } } else { $msg = 'File is of a wrong type or too heavy.'; } } Here is the HTML form code.. <form name="frmphoto" method="post" action="" enctype="multipart/form-data"> <table border="0" cellpadding="5" cellspacing="5"> <tr><td>Upload Profile Photo : </td></tr> <tr><td><input type="file" name="txtphoto" size="45"></td></tr> <tr><td><input type="submit" name="btnphoto" value="Update Photo"></td></tr> </table> </form>
  7. Hi guys, I am building a back end for personal project, I need to upload image via back end and need to know how to rename file before upload to its name but with md5 encryption $file=$_FILES['image']['tmp_name']; $image= addslashes(file_get_contents($_FILES['image']['tmp_name'])); $image_name= addslashes($_FILES['image']['name']); move_uploaded_file($_FILES["image"]["tmp_name"],"../img/ga/" . $_FILES["image"]["name"]); Thanks in advance to you all.
  8. so I'm in the process of making a .gif uploading website, and this is my code for "upload_file.php". <?php $allowedExts = array("jpg", "jpeg", "gif", "png"); $extension = end(explode(".", $_FILES["file"]["name"])); if ((($_FILES["file"]["type"] == "image/gif")) && ($_FILES["file"]["size"] < 5242880) && in_array($extension, $allowedExts)) { 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("i/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "i/" . $_FILES["file"]["name"]); echo "Stored in: " . "i/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> How can I add a random image name? Preferably 6-8 digits of only #0-9. That way the image name is simple instead of being specific to capital letters etc. Please be as specific with directions as possible, because I'm still learning PHP, and that's one of the main reasons I'm making this website. P.S. Bonus points if you can tell me how to redirect straight to the image without the page that shows the file info.
×
×
  • 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.