I want to add image and text based mark on every image.
I am using this JavaScript for uploading multiple images.
<script>
$(document).ready(function() {
$(".add").click(function() {
$('<div><input class="files" name="user_files[]" type="file" ><span class="rem" ><a href="javascript:void(0);" >Remove</span></div><br />').appendTo(".contents");
});
$('.contents').on('click', '.rem', function() {
$(this).parent("div").remove();
});
});
</script>
For Uploading multiple images
<div class="form-group">
<div class="col-lg-10">
<input class="files" name="user_files[]" type="file" >
<br />
<span><a href="javascript:void(0);" class="add" >Add More</a></span>
<div class="contents"></div>
<div class="height10"></div><br />
<div><input type="submit" name="sub2" value="Upload Images" /> </div>
Here is the php which using for uploading & inserting into database
<!-- Image code starts here -->
<?php
$strmodelid=$_POST['txtmodelid'];
$strphotocat=$_POST['rbtnalbum'];
error_reporting(E_ALL & ~E_NOTICE);
#ini_set('post_max_size', '64M');
#ini_set('upload_max_filesize', '64M');
/* * *********************************************** */
// database constants
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'admin');
define('DB_SERVER_PASSWORD', 'admin');
define('DB_DATABASE', 'databasename');
$dboptions = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
//include"config/conn.php";
if (isset($_POST["sub1"]) || isset($_POST["sub2"])) {
// include resized library
require_once('imagecode/php-image-magician/php_image_magician.php');
$msg = "";
$valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
if (count($_FILES["user_files"]) > 0) {
$folderName = "modelimgs/";
$sql = "INSERT INTO photogallery (catid,modelid,imgurl) VALUES ('$strphotocat','$strmodelid',:img)";
$stmt = $DB->prepare($sql);
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
$filepath = $folderName . $filename;
$filetitle = $_POST[txtname];
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
$emsg .= "Failed to upload <strong>" . $_FILES["user_files"]["name"][$i] . "</strong>. <br>";
$counter++;
} else {
$smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";
$magicianObj = new imageLib($filepath);
$magicianObj->resizeImage(295, 295);
$magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);
/* * ****** insert into database starts ******** */
try {
$stmt->bindValue(":img", $filename);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// file uplaoded successfully.
} else {
// failed to insert into database.
}
} catch (Exception $ex) {
$emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
}
/* * ****** insert into database ends ******** */
}
} else {
$emsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> not a valid image. <br>";
}
}
}
// $msg .= (strlen($smsg) > 0) ? successMessage($smsg) : "";
//$msg .= (strlen($emsg) > 0) ? errorMessage($emsg) : "";
header("location:photo_add.php");
} else {
$msg = errorMessage("You must upload atleast one file");
}
}
?>
<!-- image code ends here -->
You would do something like this:
// *** Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// *** Add watermark to bottom right, 50px from the edges
$magicianObj -> addWatermark('monkey.png', 'br', 50);
// *** Save watermarked image as a PNG
$magicianObj -> saveImage('racecar_small.png');
See: this page
Related
As of right now, I am able to display my images in a single column, with an image, a title, and a small description. All of this is derived from the same database. I am not very good at coding and need some guidance, how would you add onto this existing code to 1) allow the pictures to be displayed in more than one column...and 2)allow the thumbnails to be clicked on, which will load a separate page that I can then style and list the full recipe on.
I have been messing with the code in general, and I am confused by what I created. I am not sure how to proceed.
<h2>index.php:</h2>
<section class="gallery-links">
<div class="wrapper">
<div class="gallery-container">
<?php
include_once 'includes/dbh.inc.php';
$sql = "SELECT * FROM gallery ORDER BY orderGallery DESC"
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statment failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
}
?>
</div>
<?php
echo '<div class="gallery-upload">
<form action="includes/gallery-upload.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="filename" placeholder="File name...">
<input type="text" name="filetitle" placeholder="Image title...">
<input type="text" name="filedesc" placeholder="Image description...">
<input type="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>'
?>
</div>
</section>
<h2>gallery-upload.inc.php:</h2>
<?php
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
if (empty($newFileName)) {
$newFileName = "gallery";
} else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES["file"];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 2000000) {
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../images/gallery/" . $imageFullName;
include_once "dbh.inc.php";
if (empty($imageTitle) || empty($imageDesc)) {
header("Location: ../index.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO gallery (titleGallery, descGallery, imgFullNameGallery, orderGallery) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageTitle, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("Location: ../index.php?upload=success");
}
}
}
} else {
echo "File size is too big!";
exit();
}
} else {
echo "You had an error!";
exit();
}
} else {
echo "You need to upload a proper file type!";
exit();
}
<h2>dbh.inc.php:</h2>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gallery";
$conn = mysqli_connect($servername, $username, $password, $dbname);
Basically, you need to make a link on anchor tag which will have url of image detailed page with image id as below:
while ($row = mysqli_fetch_assoc($result)) {
// assuming that imgId is your primary key
echo '<a href="detail.php?imageId="'.$row["imgId"].' target="_blank">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
After, you need to create a new file detail.php where you can get image id by $_GET['imgId'] and then can query on that and will be able to get complete image details. You will also need to create a HTML for view and can show details.
Hope it helps you!!
I currently am able to save multiple individual files to folder using an array. Now I would like to add the individual file paths from the folder into a database.
How would I be able to get the individual paths of each file uploaded to folder?
From there how would I insert those individual paths into my database into separate fields?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="submit" value="Upload all files">
</form>
</body>
</html>
PHP:
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
$imageFileType = pathinfo($path,PATHINFO_EXTENSION);
$path = 'uploads/' . $_FILES['my-file']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
$conn_info = "host=d port= dbname= user= password=";
$dbconn = pg_connect($conn_info)
or die('could not connect:' . pg_last_error());
echo"<br/>sucessful connection";
$query = "INSERT INTO photo2 (path) VALUES ('".$path."') ;";
$result = pg_query($dbconn, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "<br/> error with query: " . $errormessage;
exit();
}
echo "<br/> file uploaded to PostgreSQL";
pg_close();
?>
Get the path in for loop. And also write insert query in loop.
Database connection code has to be before for loop.
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
// get path
$path = "uploads/".$name_array[$i];
echo $name_array[$i]." upload is complete<br>";
// Insert query comes here
$query = "INSERT INTO photo2 (path) VALUES ('".$path."') ;";
pg_query($dbconn, $query);
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
There is the full code you need. I think it's may help you sir.
<?php
$conn_info = "host=d port= dbname= user= password=";
$dbconn = pg_connect($conn_info) or die('could not connect:' . pg_last_error());
echo "<br/>sucessful connection";
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
// you don't need this lines of code
// $imageFileType = pathinfo($path, PATHINFO_EXTENSION);
// $path = 'uploads/' . $_FILES['my-file']['name'] . '.' . $imageFileType;
for($i=0;$i<count($tmp_name_array);$i++) {
$path = "uploads/" . $name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $path)){
$query = "INSERT INTO photo2 (path) VALUES ('".$path."');";
$result = pg_query($dbconn, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "<br/> error with query: " . $errormessage;
exit();
} else {
echo $name_array[$i]." upload is complete<br>";
}
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
echo "<br/> file uploaded to PostgreSQL";
pg_close();
?>
So I am using ajax and php to 'create a post' which allows you to upload images along with text. Currently I have the php working to check if the post has any content and if it has an image, and validating everything. However the problem is when I get a response I am prepending it to the post feed, but this makes it so that when there is an error it also prepends it to the feed. What I would like to do is append the errors to a separate div called errors.
Here is my php (I'm just starting with php and if something is wrong or could have been done easier with less work, please let me know.)
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if (!getimagesize($_FILES[$image]['tmp_name'])) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
?>
<article class="post">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username']; ?>
</a>
</div>
<img src="users/user_<?php echo $rowuser['user_id'] ?>/posts/<?php echo $row['image']; ?>" alt="">
<div class="post-body">
<div class="post-options">
<a class="likes" href="">156 likes</a>
</div>
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }else{ ?>
<article class="post no-img">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username'] ?>
</a>
</div>
<div class="post-body">
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<div class="post-options">
<a class="likes" href="">1 like</a>
</div>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }
}else{
echo 'There was a database error';
}
die();
Here is my ajax call
$.ajax({
type: "post",
url: "includes/create-post.php",
data: new FormData(this),
processData: false,
contentType: false,
error: function (response) {
console.log(response);
},
success: function (response) {
$('section.feed').prepend(response);
$('article.post p').each(function () {
$(this).html(linkHashtags($(this).html()));
});
$('article.post p').each(function () {
$(this).html(linkatsymbols($(this).html()));
});
revealPosts();
}
});
For the die() you can simply put the statement die out of foreach like this:
if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
.
.
.
.
.
.
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}
else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
But since you want to display the errors in some other element, you need a way to check whether the output you are receiving is an error. So try replacing your code with this:
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}
else {
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
And in your AJAX success call do something like this:
success: function (response) {
var obj = JSON.parse(response);
var errorCode = obj.responseCode;
var errorSet = obj.items;
if(errorCode == 0) {
$.each(errorSet, function(i, v) {
console.log('<li>'+v+'</li>');
}
}
//Your rest of the code
BTW, its better if you separate your code from your design.
How to create a php image uploader with file system in which i could preview the thumb of image before uploading it to server and also validate the file before uploading.
I am using following code for image manipulation and saving.
HTML code:
<form id="imageform" enctype="multipart/form-data" method="post" action='upload.php'>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" />
</div>
PHP Code:
<?php
// include ImageManipulator class
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = 'Thumb' . '_';
$newNamePrefix1 = 'Highdef' . '_';
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
$manipulator1 = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
// resizing to 200x200
$newImage = $manipulator->resample(200, 200);
$newImage1 = $manipulator1->resample(1024, 768);
// saving file to uploads folder
$manipulator->save('uploads/thumbs/' . $newNamePrefix . $_FILES['fileToUpload'] ['name']);
$manipulator1->save('uploads/highDef/' . $newNamePrefix1 . $_FILES['fileToUpload']['name']);
echo 'Done ...';
$folder = 'uploads/thumbs/';
$filetype = '*.*';
$files = glob($folder . $filetype);
$count = count($files);
echo '<table>';
for ($i = 0; $i < $count; $i++) {
echo '<tr><td>';
echo '<a name="' . $i . '" href="#' . $i . '"><img src="' . $files[$i] . '" /></a>';
echo substr($files[$i], strlen($folder), strpos($files[$i], '.') - strlen($folder));
echo '</td></tr>';
}
echo '</table>';
} else {
echo 'You must upload an image...';
}
}
?>
The following code I'm using to upload images is failing for some reason...
Here is the HTML
<form id="image_upload" enctype="multipart/form-data" action="uploadImage.php" method="post" name="prof_picture">
<input id="image1" style="display:none;" name="image" accept="image/jpeg" type="file">
<input id="image2" value="Submit" type="submit" style="display:none;">
</form>
PHP (uploadImage.php)
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name'][0]);
echo $filename;
$size=filesize($_FILES['image']['tmp_name'][0]);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'][0], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}
JS
$('#image1').on('change', function() {
$("#image").attr('src',"profile/loading.gif");
$("#image_upload").ajaxForm({
target: '#image'
}).submit();
});
What I know for sure:
1º The php script is being achieved correctly because I failed part of the code on purpose and attained an error message regarding an internal php error.
2º The query is being done correctly (or at least by its syntax).
3º The javascript function related to #image is also working.
I only want to upload one image that the user selects (even if he selects 100 other items). But as I said, I don't even get an error message on the log... Any ideas on this one? Thank you very much!
EDIT
I've changed the code a bit
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)){
if ($size < (MAX_SIZE*1024)){
$image_name=time().$user_id."--pfi-".$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)){
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}else echo '<span class="imgList">This message appears </span>';
}else echo '<span class="imgList">You have exceeded the size limit!</span>';
}else echo '<span class="imgList">Unknown extension!</span>';
For some reason it now stops at if(move_uploaded_file($_FILES['image']['tmp_name'], $newname)). I've var_dump'ed this and it is indeed "false" but I can't get to understand why. Here is var_dump($_FILES):
array(1) { ["image"]=> array(5) { ["name"]=> string(21) "060424_hubble_big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpZYaDkm" ["error"]=> int(0) ["size"]=> int(35641) } }
EDIT 2
Warning:
move_uploaded_file(profile/uploads/1388794617.png):
failed to open stream: No such file or directory in
profile/uploadProfilePicture.php on line 37
Warning: move_uploaded_file(): Unable to move '/tmp/phppFfoL4' to
'profile/uploads/1388794617.png' in
profile/uploadProfilePicture.php on line 37
how should I specify $uploaddir or even $newname?
Edit
This is what I used. Notice the commented out conditional statements.
<?php
// include('../sqlconnection.php');
define ("MAX_SIZE","1000000000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
// {
$uploaddir = "profile/uploads/"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
// mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
// }
Original answer
Ok, I found the problem. Remove all [0] in your PHP and it will now work. Those are used for arrays and since you're only using it for single file uploads, is why it failed.
Sidenote: You may want to add a / at the end of $uploaddir = "profile/uploads"; as in $uploaddir = "profile/uploads/";
The following doesn't have the [0]'s and have tested it as pure PHP with no JS.
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}