MYSQL, PHP, image upload/update fail - php

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.

Related

I cannot upload variables to database

I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.

fail upload to database

I am trying to save a image file name at database, but i cannot make it, please help me
my database have no wrong, duno why it cannot update to databse, but i can get the $newname correctly
?php session_start();
include_once("connectDB.php");
$ID = $_SESSION['ID'];
if(isset($_POST['upload'])){
$ID = $_SESSION['ID'];
$loc = "profilepicture/";
if($_FILES["Adminpic"]["type"] == "image/png" || $_FILES["Adminpic"]["type"] ==
"image/jpeg" || $_FILES["Adminpic"]["type"] == "image/jpg" || $_FILES["Adminpic"]
["type"] == "image/gif")
{
$ID = $_SESSION['ID'];
$file = explode(".", $_FILES["Adminpic"]["name"]);
$newname = "$ID.$file[0].$file[1]";
mysql_query("UPDATE admin SET Adminpic == '$newname' WHERE ID='$ID'");
$path = "$loc$newname";
move_uploaded_file($_FILES["Adminpic"]["tmp_name"], $path) ;
echo "Your image has been uploaded success, $newname";
}
else{
echo"invalid file.";
}
}
Because your query is incorrect
mysql_query("UPDATE admin SET Adminpic ='$newname' WHERE ID=$ID");
try with this because you use double equal after Adminpic .

not updating in database

This is my code
$id = $_POST['id'];
$category = $_POST['category'];
$title = $_POST['title'];
$short_content = $_POST['short_content'];
$long_content = $_POST['long_content'];
$date = $_POST['date'];
$lang = $_POST['language'];
//echo $id." ".$category." ".$title." ".$short_content." ".$lang." ".$date;
if(empty($id)){
echo "<h3 align=\"center\">Please fill ID</h3>";
}
if(empty($category)){
echo "<h3 align=\"center\">Please fill Category</h3>";
}
if(empty($title)){
echo "<h3 align=\"center\">Please fill Title</h3>";
}
if(empty($date)){
echo "<h3 align=\"center\">Please fill Date</h3>";
}
if(empty($lang)){
echo "<h3 align=\"center\">Please fill Lang</h3>";
}
if(!empty($_FILES['img']['name'])){
$extension = end(explode(".",$_FILES['img']['name']));
//echo "file format: ".$extension."<br>";
$name = $_FILES['img']['name'];
$size = $_FILES['img']['size'];
if(file_exists("views/admin/uploads/".$name)){
echo "<h3 align=\"center\">".$_FILES['img']['name']." exists</h3>
<h3 align=\"center\">Go back</h3>";
return false;
}
if($extension != "jpg" && $extension != "png" && $extension != "gif" && $extension != "JPG"){
echo "<h3 align=\"center\">File with format: ".$extension." is not aviable to upload</h3>
<h3 align=\"center\">Go back</h3>";
return false;
}
}
if(!empty($id) && !empty($category) && !empty($title) && !empty($date) && !empty($lang)){
$query = mysql_query("UPDATE `news` SET `id`='$id', category`='$category',`title`='$title',`img`='$name',`short_content`='$short_content',`content`='$long_content',`date`='$date',`lang`='$lang' WHERE `id`='$id'");
move_uploaded_file($_FILES['img']['tmp_name'],"views/admin/uploads/".$name);
echo "<h2 align=\"center\">Successfully updated!</h2>";
}
It's should update table row, but it dont. The input value are sending ok. Please give me a solution..
Which part of code is wrong?????
I don't know will this fix your problem (yes, I don't have time to test this), but be happy about that I made your code much more readable.
In the future, it would be much easier answer if you 1. make your code readable and 2. give your mysql database dump.
Create classes.php file and add this code inside it. Change your host, dbname, username and password if needed.
// Connecting to database
class mysql{
public $db;
public function connect(){
$this->db = new PDO(
"mysql:host=localhost;dbname=xxxxx;",
"root",
""
);
}
}
// Update thing
class stuff extends mysql{
public function updateThing($id,$cat,$title,$img,$shortContent,$content,$date,$lang){
$this->statement = $this->db->prepare("UPDATE `news` SET `category`= $2,`title` = $3,`img` = $4,`short_content` = $5,`content` = $6,`date` = $7,`lang` = $8 WHERE `id` = $1");
$this->statement->execute(array($id,$cat,$title,$img,$shortContent,$content,date("Y-m-d H:i:s",strtotime($date)),$lang));
print_r($this->statement->fetchAll());
}
}
And then throw these into file what updates things:
include_once("classes.php");
$id = $_POST['id'];
$cat = $_POST['category'];
$title = $_POST['title'];
$shortContent = $_POST['short_content'];
$longContent = $_POST['long_content'];
$date = $_POST['date'];
$lang = $_POST['language'];
$stuff = new stuff;
$stuff->connect();
$errors = array();
if(empty($id)){
$errors[] = "Please fill ID";
}
if(empty($cat)){
$errors[] = "Please fill Category";
}
if(empty($title)){
$errors[] = "Please fill Title";
}
if(empty($date)){
$errors[] = "Please fill Date";
}
if(empty($lang)){
$errors[] = "Please fill Lang";
}
if(!empty($_FILES['img']['name'])){
$extension = end(explode(".",$_FILES['img']['name']));
$name = $_FILES['img']['name'];
$size = $_FILES['img']['size'];
if(file_exists("views/admin/uploads/".$name)){
$errors[] = "File with this name already exists!";
}
if($extension != "jpg" && $extension != "png" && $extension != "gif" && $extension != "JPG"){
$errors[] = "Unknown file format!";
}
}
if(count($errors)==0){
$stuff = new stuff;
$stuff->connect();
$stuff->updateThing($id,$cat,$title,$img,$shortContent,$longContent,$date,$lang);
move_uploaded_file($_FILES['img']['tmp_name'],"views/admin/uploads/".$name);
echo "<h2>Successfully updated!</h2>";
}else{
print "<h3>Errors!</h3><ul><li>".join("</li><li>",$errors)."</li></ul>";
}

How to submit form data with optional upload file

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.

rename image during upload not working with Mysql set

I have the bellow code which I was hoping to change/rename image name on upload to user id so I can avoid file overwrite and insert the name into database sadly after I added rename code the code is not able to upload image or update the database we out showing any error but if I remove the rename code everything was working.
Can one help me how to solve it or is there any better way I can do it?
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(#$_POST ['submit']) {
$file = $_FILES ['file'];
$name1 = $file ['name'];
$type = $file ['type'];
$size = $file ['size'];
$tmppath = $file ['tmp_name'];
if($type == 'jpeg' || $type == 'png' || $type == 'jpg') {
$name1 = $user_id.$type; // rename image
if($name1!="") {
if(move_uploaded_file ($tmppath, 'users/'.$name1)) {
$sql=("INSERT INTO USERS set photo='$name1' WHERE username='$username'");
mysql_query ($sql) or die ('could not updated:'.mysql_error());
echo ("Profile picture updated");
}
}
}
}
?>
You can try this, may be help you ...
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(#$_POST ['submit']) {
$file = $_FILES ['file'];
$name1 = time().$file ['name']; // rename image
$type = $file ['type'];
$size = $file ['size'];
$tmppath = $file ['tmp_name'];
if($type == 'image/jpeg' || $type == 'image/png' || $type == 'image/jpg') {
if($name1!="") {
if(move_uploaded_file ($tmppath, 'users/'.$name1)) {
$sql=("INSERT INTO USERS set photo='$name1' WHERE username='$username'");
mysql_query ($sql) or die ('could not updated:'.mysql_error());
echo ("Profile picture updated");
}
}
}
}}
?>
First of all change
$name1 = $user_id.$type;
to
$name1 = $user_id.".".$type;
And second of all clean up you sql.
Also. file_type is image/jpeg so that's why it doesn't work. It never goes past your if.
Create a switch to check the filetype or just take the last 3 characters of the file.
Try this to reorganise your $_FILES into an array you can understand and easily work with.
Shameless plug
https://gist.github.com/lukeoliff/5531772#file-quickrearrangefiles-php
<?php
function rearrangeFiles($arr) {
foreach($arr as $key => $all){
foreach($all as $i => $val){
$new[$i][$key] = $val;
}
}
return $new;
}
Used as such:
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(!empty($_POST) && !empty($_FILES)) {
$files = rearrangeFiles($_FILES)
foreach ($files as $key => $file) {
$name = $file['name'];
$type = $file['type'];
$size = $file['size'];
$tmppath = $file['tmp_name'];
if($type == 'jpeg' || $type == 'png' || $type == 'jpg') {
$name = time() . '_' . $user_id.'_'.$name.'.'.$type; // TIMESTAMP, USERID and FILENAME RENAME
if(!empty($name)) {
if(move_uploaded_file($tmppath, 'users/'.$name)) {
$sql = "INSERT INTO users (photo,username) values ('$name','$username')";
mysql_query($sql) or die('could not updated:'.mysql_error());
$successes[] = $file['name'] . " picture saved as " . $name;
}
}
}
}
if (!empty($successes)) {
echo implode('. ',$successes);
}
}
Further improved by inserting into database in a single query :) Also you really need to move from mysql_ functions to mysqli_ or PDO:: functions as per php.net http://www.php.net/manual/en/function.mysql-connect.php depreciating mysql_ functions soon.
you can use that one concept, but edit this as your requirement.
<?php
if ($_FILES['imagepath']['name'] != "")
{
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILES['imagepath']['name']);
if (move_uploaded_file($_FILES['imagepath']['tmp_name'], $uploadfile))
{
$rename = $_FILES['imagepath']['name'];
$rename = rand(0,1500000000).$rename;
$filename = strtolower(($rename));
if (file_exists(($uploaddir.$_FILES['imagepath']['name'])))
rename(($uploaddir.$_FILES['imagepath']['name']), ($uploaddir.$filename));
echo $_FILES['imagepath']['name']." with name ".$filename." file uploaded successfully";
}
}
?>

Categories