How can I submit form data with an optional upload file. I mean, can I submit form data together with an uploaded file? But I want to make the upload file optional. Here is the my code :
<?php
define ("MAX_SIZE","5000");
$errors=0;
if(($_SERVER["REQUEST_METHOD"] == "POST") && isset($_FILES["file"]["size"]) && ($_FILES["file"]["size"] > 0))
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=500;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=300;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagealphablending($tmp1, false);
imagesavealpha($tmp1, true);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
$image_name=time().'_'.$_FILES['file']['name'];
$filename = "images/". $image_name;
$filename1 = "images/small_". $image_name;
$uid=$_SESSION['uid'];
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
if(isset($_POST['Submit']) && !$errors )
{
$category_group= $_POST['category_group'];
$title=$_POST['title'];
$details=$_POST['details'];
$ad_keywords=$_POST['ad_keywords'];
$category_state=$_POST['category_state'];
$category_city=$_POST['category_city'];
$address=$_POST['address'];
$telephone=$_POST['telephone'];
$email=$_POST['email'];
$website=$_POST['website_link'];
$price=$_POST['price'];
$filename= ($_FILES["file"]["size"] > 0) ? $filename : '';
$filename1= ($_FILES["file"]["size"] > 0) ? $filename1 : '';
$url=time().'-'. createUrl($title);
if(!$category_group || !category_city || !$title || !$details || !$category_state ){
echo "enter state and city name";
}else{
try{
$sth = $dbh->prepare("
INSERT INTO
advertisement(user_id,ad_image_big,ad_image_small,ad_cat_group,ad_title,ad_details,ad_state,ad_city,ad_address,ad_telephone,ad_email,ad_website,ad_price,ad_slug,ad_keywords)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6,:field7,:field8,:field9,:field10,:field11,:field12,:field13,:field14,:field15)
");
$sth->execute(array(':field1' => $uid, ':field2' => $filename, ':field3' => $filename1, ':field4' => $category_group, ':field5' => $title, ':field6' => $details, ':field7' => $category_state,':field8'=> $category_city, ':field9' => $address, ':field10' => $telephone,':field11'=> $email,':field12'=> $website, ':field13' => $price, ':field14' => $url , ':field15'=> $ad_keywords));
}catch (PDOException $ex){
echo "An Error occured while inserting data to database";
some_logging_function($ex->getMessage());
}
header('location:success.php');
}
}
?>
Whenever I try to submit the form without the upload file I get this error:
"An Error occurred while inserting data to database"
which is in the catch section. If I upload a file, I get a success message without any error. Help me please.
Here is the code I made not long ago... Had the same problem :)
The form itself:
<form action="index.php" method="post" enctype='multipart/form-data'>
<input class="header_input" type="text" name="header" />
<br/><span class="input_headers"><p>Content</p></span>
<textarea class="textarea_input" rows="10" cols="30" name="content">
</textarea><br />
Select File: <input type='file' name='filename' size='10' /><br />
<input type="submit" class="submit" />
</form>
Altho it doesn't check, wether something is inputed into the "Header" and "Content" section, so try to fix that:
if (isset($_POST['header']) && isset($_POST['content'])) {
$header = mysql_real_escape_string(htmlentities($_POST['header']));
$content = mysql_real_escape_string(nl2br(htmlentities($_POST['content'])));
$sql = mysqli_query($con,"INSERT INTO posts (Header, Content) VALUES
('{$header}','{$content}')");
}
And this uploads the image, if there is one:
if (isset($_FILES['filename']['name'])) {
$name = htmlentities($_FILES['filename']['name']);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES['filename']['name']));
if ((($_FILES['filename']['type'] == "image/gif")
|| ($_FILES['filename']['type'] == "image/jpeg")
|| ($_FILES['filename']['type'] == "image/jpg")
|| ($_FILES['filename']['type'] == "image/pjpeg")
|| ($_FILES['filename']['type'] == "image/x-png")
|| ($_FILES['filename']['type'] == "image/png"))
&& ($_FILES['filename']['type'] < 20000)
&& in_array($extension, $allowedExts)) {
$result = mysqli_query($con,"SELECT * FROM posts WHERE PID=(SELECT max(PID) FROM posts)");
$row = mysqli_fetch_array($result);
$id = $row['PID'];
$new_name = $id . "_" . "000" . ".jpg";
if (file_exists("images/" . $new_name)) {
$new_name_ex = $id . "_" . "001" . ".jpg";
move_uploaded_file($_FILES['filename']['tmp_name'],"images/" . $new_name_ex);
$sql = mysqli_query($con,"UPDATE posts SET Images='{$new_name_ex}' WHERE PID='{$id}'");
} else {
move_uploaded_file($_FILES['filename']['tmp_name'],"images/" . $new_name);
$sql = mysqli_query($con,"UPDATE posts SET Images='{$new_name}' WHERE PID='{$id}'");
}
}
}
Hope that helps :) I am new to PHP, so maybe there is a way to make all of this code more simple, altho I hope it answers your question
From PHP Documentation (http://php.net/manual/en/features.file-upload.post-method.php), Example #3 Uploading array of files does pretty much what you need by walking through each file (in case you have an array of files) then the if statement checks whether the file is there. The code below is from the PHP documentation:
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "data/$name");
}
}
If there's no file, the code simply skips the upload and move on to the next.
Related
I have been trying over weeks now to figure out how to use ffmpeg to get thumbnail from a video while upload that video in php.
This is my code and I don't where I went wrong please help.
<?php
if (logged_in() === true) {
if (isset($_POST['up'], $_FILES['file'])) {
$file_name = $_FILES['file']['name'];
$file_type = explode('.', $file_name);
$file_type = strtolower(end($file_type));
$random = rand();
$file_tmp = $_FILES['file']['tmp_name'];
$file_dir = "jobalertme/includes/video_uploads/$random.$file_type";
if ($file_type == 'mp4' || $file_type == 'avi' || $file_type == 'wmv' || $file_type == 'mov' || $file_type == 'flv') {
if (move_uploaded_file($file_tmp, "$file_dir")) {
$ffmpeg = "C:\\ffmpeg\\bin\\ffmpeg";
$img_name = "1.jpg";
$img_size = "120x90";
$getimgsec = 5;
$cmd = "$ffmpeg -i $file_tmp -an -ss $getimgsec -s $img_size www/jobalertme/includes/img_thumnail/$img_name <br>";
if (shell_exec($cmd)) {
echo "ok";
} else {
echo "not";
}
$updat = "UPDATE registration SET video='$file_dir' WHERE uname='$username'";
$qry = mysqli_query($con, $updat);
if ($qry) {
echo "<script> alert('your file has been successfully uploaded ')</script>";
echo "<script>window.open('upload_vid.php','_self')</script>";
exit();
} else {
echo "<script> alert('we ran into some problems')</script>";
echo "<script>window.open('upload_vid.php','_self')</script>";
exit();
}
} else {
echo "<script> alert('we ran into some problems')</script>";
echo "<script>window.open('upload_vid.php','_self')</script>";
exit();
}
} else {
echo "<script>alert('please this file extension is not allowed, it must be an mp4 file format')</script>";
echo "<script>window.open('upload_vid.php','_self')</script>";
exit();
}
}
} else {
echo "<script>alert('please you need login before you can upload resume.')</scrpt>";
echo "<script>window.open('upload_vid.php','_self')</script>";
exit();
}
?>
I have search on google youtube and others but still have not gotten the solution.
I have written some codes to collect images, re-size, upload to two different folders and store the new name in a mysql database. Every other aspect of the code is working. The only issue i am having is that, the new name given to the image is not being stored in the datatbase. What i am getting is just a single digit. E.g rather than have the name of file uploaded as 1234_12345.jpg stored in the database, the file name stored is just say 1 or 3 etc.
Below is my form:
<form method="POST" id="adimageadd" action="<?php echo $editFormAction; ?>" name="adimageadd" enctype="multipart/form-data">
<div class="h1">Select Album:</div>
<select class="input-field-login2" id="albumselect" name="albumselect" required type="text" tabindex="1">
<option value="">Please Select</option>
<?php foreach ($result_album as $rs) { ?>
<option value="<?php echo $rs["alID"]; ?>"><?php echo $rs["alTitle"]; ?></option>
<?php } ?>
</select>
<input type="hidden" name="MAX_FILE_SIZE" value="" />
<input name="photo[]" type="file" required id="photo" size="26" multiple='multiple'/>
<button name="login" type="submit" id="login_submit" tabindex="3">Add Images</button>
<input type="hidden" name="form_insert" value="adimageadd">
</form>
And the php code is:
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
define ("MAX_SIZE","2048");
$errors=0;
$query_album = "SELECT alID, alTitle, alImage, alDesc FROM galbum ORDER BY alID DESC";
$result_album = mysqli_query($connKcla, $query_album);
$row_album = mysqli_fetch_assoc($result_album);
$totalRows_album = mysqli_num_rows($result_album);
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["form_insert"])) && ($_POST["form_insert"] == "adimageadd")) {
//get form details and check for sql injections and disable them
$albumRef = mysqli_real_escape_string($connKcla, $_POST['albumselect']);
$image = $_FILES["photo"]["name"];
$uploadedfile = $_FILES['photo']['tmp_name'];
$img = count($image);
for ($i = 0; $i < $img; $i++) {
if ($image){
$filename = mysqli_real_escape_string($connKcla, $image[$i]);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size=filesize($_FILES['photo']['tmp_name'][$i]);
if ($size > MAX_SIZE*1024)
{
echo "Your image has exceeded the size limit of 2Mb. Click the back button on your browser to re-enter the right size of image";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['photo']['tmp_name'][$i];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['photo']['tmp_name'][$i];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=760;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$thumbnewwidth=250;
$thumbnewheight=($height/$width)*$thumbnewwidth;
$thumbtmp=imagecreatetruecolor($thumbnewwidth,$thumbnewheight);
imagecopyresampled($thumbtmp,$src,0,0,0,0,$thumbnewwidth,$thumbnewheight,$width,$height);
$set['photo'] = $image[$i];
$kaboom = explode(".", $image[$i]);
$pixExt = end($kaboom);
$photo = rand()."_".time().".".$pixExt;
$target = "../gallery/images/". $photo;
$thumbtarget = "../gallery/images/thumbs/". $photo;
imagejpeg($tmp,$target,100);
imagejpeg($thumbtmp,$thumbtarget,75);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($thumbtmp);
}
}
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo[$i], $albumRef)");
$results = $stmt->execute();
$stmt->close();
if($results){
$updateGoTo = "confirm.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
}
header("Location: ". $updateGoTo);
}else{
header("Location: error.php");
}
}
}
Please any help would be much appreciated.
This creates a string:
$photo = rand()."_".time().".".$pixExt;
This gets one character from that string:
$photo[$i]
Which you're storing in your database:
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo[$i], $albumRef)");
If you want to store the whole string, just use the string itself and not the index of a specific character:
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo, $albumRef)");
//^-- here
Additionally, you should probably start looking into using query parameters and prepared statements. While this code may coincidentally not currently be open to SQL injection if none of the input is from users, it's still difficult to guarantee that. And not being open to SQL injection is a good habit to get into in general.
Problem solved. I just changed the value part of the query from:
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ($photo[$i], $albumRef)");
to
$stmt = $connKcla->prepare("INSERT INTO gimage (imImage, albumRef) VALUES ('$photo', '$albumRef')");
i want to check user credentials after user login in a form, then if username and password correct, user will redirected to upload.php page, and after upload an image and a status, image and status will post on user twit
here's my code for verifikasi.php
<h2>Verifikasi ID Twitter...</h2>
/*verification of user credentials
after validation of username and password success, redirect to upload image and status page
but if validation of username and password fail, back to login page
*/
<?php
require_once('codebird.php');
$cb = new \Codebird\Codebird;
$id = $_POST['id'];
$pass = $_POST['pass'];
//if($_POST['loginTwitter'] == "Submit"){
//if(isset($_POST['loginTwitter'])){
if(isset($id) && isset($pass)){
//cek bener apa engga nya
//if($_POST['id'] == '' || $_POST['pass'] == ''){ header('login.php'); }
$cb::setConsumerKey('somekey', 'somekeysecret');
$cb::getInstance();
$cb->setToken('tokenaccess', 'tokenaccesssecret');
$code = $cb->account_verifyCredentials();
if($code == 200){
//$reply = $cb->oauth2_token();
//$bearer_token = $reply->access_token;
header('upload.php');
}
else{ header('login.php'); }
//echo "Redirect to Upload Image...."; for($i = 0; $i <= 20000000; $i++); header('upload.php');
}
else{
echo "<br />";
echo "<h3>Something went wrong... Please Check Again Your Credentials</h3>";
}
?>
and here's the post.php page (for posting image and status to user twit using update_with_media API
<div id="photo_tweet">
<h2>Photo Tweet</h2>
<br />
<?php require_once('codebird.php'); ?>
<?php
function redirectToUpload(){
echo "Redirect...";
for($i = 0; $i <= 20000000; $i++);
header('upload.php');
}
?>
<?php
$imgExt = array("jpeg", "jpg", "png");
$currImgExt = end( explode(".", $_FILES["file"]["name"]) );
if($_POST['uploadTwit'] == "Submit"){
if ((($_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") || $_POST['status'] == '')
&& ($_FILES["file"]["size"] < 20000)
&& in_array($currImgExt, $imgExt))
{
if ($_FILES["file"]["error"] > 0){
echo "Error: " . $_FILES["file"]["error"] . "<br>";
redirectToUpload();
}
else{
$params = array(
'status' => $_POST['status'],
'media[]' => $_FILES["file"]["name"]
);
/*
$data_user = array(
'user_id' => ,
'screen_name' =>
);
*/
$reply = $cb->statuses_updateWithMedia($params);
}
}
}
else { echo "Invalid Image File or Invalid File Size or Twit cannot empty! Please check agian your image file before proceed!"; redirectToUpload(); }
?>
<p>You Just Succeed Post image and status!</p>
</div>
The problem for verifikasi.php is
Notice: Object of class stdClass could not be converted to int in C:\wamp\www\twcodebird\verifikasi.php on line 36
i want to return status code in verifikasi.php, if code = 200 then user redirected to upload.php page,
but looking from error return, it seems my code wrong return... what should i do?
for post.php i'm not run it yet, because i want to make sure verification of user credentials work first
I have a problem in retrieving an image from a database. Here is the code that uploads the image to the database:
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
}
if (($imageextension1= "jpg") && ($imageextension1= "jpeg") && ($imageextension1= "gif") && ($imageextension1 = "png") && ($imageextension1 = "bmp")) {
$query1=mysql_query("INSERT INTO store set image='$imgname1'");
$action = move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1);
die('not Uploded');
}
}
?>
Now I want to retrieve all the images in the database; for this I am using the following code:
<?php
$query1="select * from store";
$fetch=mysql_query($query1);
while ($rows=mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['image']."' />";
}
?>
You should not be using the old mysql_* functions and use PDO or mysqli instead. Here is a much cleaner and securer way of doing what you want.
<?php
/**
* A Simple class to handle your database requests
* related to your image storage ect
*/
class image_model{
private $db;
function __construct($db){
$this->db = $db;
}
function add($img_name){
$sql = "INSERT INTO store (image) VALUES (:value)";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':value', $img_name, PDO::PARAM_STR);
$stmt->execute();
}
function get_all(){
$sql = "SELECT image FROM store";
return $this->db->query($sql)->fetchAll();
}
//Perhaps use in future
function get_image($id){
$sql = "SELECT image FROM store WHERE id=:id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $result->fetchAll();
}
}
//Connect safely to your database...
try{
$db = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}
//Create an instance of the image model above
$img_model = new image_model($db);
//Boom...Handle the upload
if($_SERVER['REQUEST_METHOD']=='POST'){
if ($_FILES["img"]["error"] > 0){
echo "Error: ".$_FILES["img"]["error"]."<br />";
}else{
$img = getimagesize($_FILES["img"]["tmp_name"]);
$allowed = array('image/jpeg','image/gif','image/png','image/bmp');
//Width and height must be more then 0 pixles and mime must be in allowed array
if($img[0] > 0 && $img[1] > 0 && in_array($img['mime'],$allowed)){
if(is_uploaded_file($_FILES["img"]["tmp_name"])){
//Clean image name
$img_name = preg_replace('/[^a-zA-Z0-9.-]/s', '_', basename($_FILES["img"]["name"]));
//move image to folder
move_uploaded_file($_FILES["img"]["tmp_name"],"images/".$img_name);
//Add image to db using a method from the image model
$img_model->add($img_name);
}
}else{
echo "Error: Unknown extension. Only jpg, bmp and gif files are allowed. Please hit the back button on your browser and try again.<br />";
}
}
}
//Your form
?>
<h1>Upload image</h1>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="img"/>
<input type="submit" name="submit" value="Save"/>
</form>
<?php
//Access your image model in a simple way and get all images
foreach($img_model->get_all() as $row){
echo '<img src="images/'.$row['image'].'" /><br />';
}
?>
Refer this link,
Hope this will help.
Change retrieval of image code to following,
$content = $row['image'];
header('Content-type: image/jpg');
echo $content;
try this I've tested this code and made some modifications.
<form method="post" action="index2.php" enctype="multipart/form-data">
<input type="file" name="drimg2"/>
<input type="submit" name="submit2" value="Save"/>
</form>
<?php
if(isset($_POST['submit2'])) {
$con=mysql_connect("localhost","root","root");
mysql_select_db("test",$con);
$imgname1=$_FILES['drimg2']['name'];
//echo $imgname1;
$imageextension1 = substr(strrchr($imgname1,'.'), 1);
//echo '<pre>';print_r($imageextension1);echo '</pre>';die('Call');
if (($imageextension1!= "jpg") && ($imageextension1 != "jpeg") && ($imageextension1 != "gif")&& ($imageextension1 != "png")&& ($imageextension1 != "bmp")) {
die('Unknown extension. Only jpg, jpeg, and gif files are allowed. Please hit the back button on your browser and try again.');
} else {
//if (($imageextension1 == "jpg") && ($imageextension1 == "jpeg") && ($imageextension1 == "gif") && ($imageextension1 == "png") && ($imageextension1 = "bmp")) {
if(move_uploaded_file($_FILES['drimg2']['tmp_name'],"images/".$imgname1)) {
$query1=mysql_query("INSERT INTO fileurl(filename) VALUES('".$imgname1."')"); //fileurl is table name and filename is field name
if($query1) {
echo "Data inserted";
} else {
echo "Data not inserted";
}
} else {
echo "Error occured while trying to upload image";
}
//$action = ;
//die('not Uploded');
}
}
?>
and for fetching images try this
$query = "SELECT * FROM fileurl";
$fetch = mysql_query($query);
while($rows = mysql_fetch_array($fetch)) {
echo "<img src='images/".$rows['filename']."' />";
}
if your image format not matched it will close the program automatically otherwise it'll jump to the else condition and upload the image and then insert the name of file into the database.
i am trying to allow users to update their profile picture using this code.
require("../connection.php");
$imgName = $_FILES['pic']['name'];
$imgTmp = $_FILES['pic']['tmp_name'];
$imgtype = $_FILES['pic']['type'];
$imgSize = $_FILES['pic']['size'];
$maxFileSize = 200000;
$pic = "../uploads/" . $user_id . "_" . time() . $imgName;
if ($imgSize > $maxFileSize) {
$error = "size";
}
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$error .= "";
} else {
$error = "type";
}
if (file_exists($pic)) {
$error = "exists";
}
if ($error == "" && $imgName != "") {
move_uploaded_file($imgTmp, $pic);
mysql_query("UPDATE users SET pic = '$pic', WHERE username = '$username'");
if (!mysql_query($query, $connect)) {
die(mysql_error());
} else {
mysql_close($connect);
header('location:http://www.WEBSITE.co.uk/users/upload-pic-thanks.php');
}
} else {
header("Location:edit-pic-error.php?e=".$error);
}
and it gives me this in the address bar: edit-pic-error.php?e=type, however the file i am trying to upload is .jpg, and its smaller than the 20000kb allowance.
The table in my mysql database is called 'users', and the table row is called 'pic', its Varchar, 60, allow null ticked.
The table is not being updated with the new time stamped profile picture.
Please help.
Thanks very much
$imgtype = $_FILES['pic']['type'];
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$imgType vs. $imgtype, notice the case.