I'm having trouble with an image upload form, with most images it works just fine but with larger image files I get a Column 'userimage' cannot be null error.
I have changed the following values in my php.ini file;
post_max_size
upload_max_filesize
memory_limit
I'm using a prepared statement(I've just included a small section here);
$sql = "INSERT INTO gallery (user, area, userimage, socialurl) VALUES (?, ?, ?, ?)";
if($stmt = $conn->prepare($sql)){
$stmt->bind_param("ssss", $user, $area, $userimage, $socialurl);
I've tried searching but I can't find a similar problem.
My code, I've edited out some that isn't relevant to make the question shorter;
<?php
$error = "";
$dangererror = "";
$successmsg = "";
require("config/connect.php");
if (isset($_POST['submit'])){
if(empty($_POST['user'])) {
$error .= "User is required<br>";
}
if(empty($_POST['area'])) {
$error .= "Location is required<br>";
}
if(isset($_FILES["userimage"]) && $_FILES["userimage"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
echo $_FILES["userimage"]["name"];
$userimage = $_FILES["userimage"]["name"];
echo $userimage;
$filetype = $_FILES["userimage"]["type"];
$targetDir = "uploads/";
$targetFilePath = $targetDir . $userimage;
$targetThumbFilePath = "uploads/thumbs/";
if(!file_exists("uploads/" . $_FILES["userimage"]["name"])){
// Verify file extension
$ext = pathinfo(strtolower($userimage), PATHINFO_EXTENSION);
if(array_key_exists($ext, $allowed)) {
$maxsize = 5000000;
if($_FILES['userimage']['size'] < $maxsize) {
if (move_uploaded_file($_FILES["userimage"]["tmp_name"], $targetFilePath)){
$successmsg .= "<div class='alert alert-success'>Image - " . $userimage . " - Uploaded Successfully!</div>";
$upload = 'uploads/' . $_FILES["userimage"]["name"];
list ($width, $height, $type) = getimagesize ($upload);
//switches content-type and calls the imagecreatefrom... function
<!------------- cut ------->
//switches content-type and saves thumbnail
<!------------- cut ------->
}
} else {
echo "test";
$error .= "File Exceeds 5mb Limit<br>";
}
} else {
$error .= "Invalid File Format<br>";
}
} else {
$error .= "The Filename " . $_FILES["userimage"]["name"] . " already exists - please rename your picture before uploading<br>";
}
}
if($_POST['socialpage'] != ""){
//switches content-type and saves thumbnail
<!------------- cut ------->
}
if($error) {
$dangererror = "<div class='alert alert-danger'>";
$dangererror .= $error;
$dangererror .= "</div>";
}
else {
// Prepare an insert statement
$sql = "INSERT INTO gallery (user, area, userimage, socialurl) VALUES (?, ?, ?, ?)";
if($stmt = $conn->prepare($sql)){
// Set parameters
$user = $_REQUEST['user'];
$area = $_REQUEST['area'];
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssss", $user, $area, $userimage, $socialurl);
// Attempt to execute the prepared statement
if($stmt->execute()){
$successmsg .= "<div class='alert alert-success'>Image Added Successfully!</div>";
} else{
echo "ERROR: Could not execute query: $sql. " . $conn->error;
}
} else{
echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
// Close statement
$stmt->close();
// Close connection
$conn->close();
}
}
?>
Your problem is that you have no else clause on this if:
if(isset($_FILES["userimage"]) && $_FILES["userimage"]["error"] == 0){
As a result, if $_FILES['userimage'] is unset, or if there is an error (i.e. $_FILES["userimage"]["error"] != 0), your $error variable remains an empty string and so you attempt to make an INSERT even though you haven't set the value of $userimage. You need to add an else clause something like this:
elseif (isset($_FILES['userimage']) {
// must have been an error uploading i.e. $_FILES["userimage"]["error"] != 0
$error .= "Error uploading file, error code = " . $_FILES["userimage"]["error"];
}
else {
// no uploaded file!
$error .= "No file uploaded!";
}
The problem was that when I set the following options in the php.ini file;
post_max_size
upload_max_filesize
memory_limit
I set the values too high as;
If the upload_max_filesize is larger than post_max_size, you must increase post_max_size so that it is bigger than upload_max_size.
Related
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.
I have this php photo gallery, however my "mysqli_stmt_prepare" statement seems to be failing in someway. However, when I check my DB, the files that are in accordance to the upload rules, I created in my code, have been uploaded.
The message I get each time I upload a file to the DB is the one corresponding to a failed "mysqli_stmt_prepare", namely as in the code:
echo "SQL statement failed! 1"
<?php
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
//sets the file name to "gallery"
if (empty($_POST['filename'])) {
$newFileName = "gallery";
//adds hyphens to empty spaces
} 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", "pdf");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 200000) {
$imageFullName = $newFileName . "." . uniqid("uniqID", false) . "." . $fileActualExt;
$fileDestination = "../gallery/" . $imageFullName;
include_once "dbh.inc.php";
if (empty($imageTitle || $imageDesc)) {
header("Location: ../gallery.php?upload=empty");
echo "You didn't include the Image Title and Image description!";
exit();
} else {
$sql = "SELECT * FROM gallerytrexatek";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed! 1";
} 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! 2";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageTitle, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("Location: ../galleryInPHP.php?upload=success");
}
}
}
} else {
echo "File Size is way to big";
exit();
}
} else {
echo "You had an error with the file";
exit();
}
} else {
echo "The file type you tried to upload is not allowed!";
exit();
}
}
?>
I expect the file to upload without problems. It seems I am overlooking something rather simple.
Hint: There are 3 files connected to this one.
1. The gallery.php where the form exists for images to be uploaded
2. The one which is pasted here
3. the DB handler file
Do'h, there was a problem with one of the file handler files.
I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i am updating name , email in DB of registered user through php form. its working fine.
class.usr.php
public function update($uname,$email, $tax)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ? , tax = ? WHERE userID = ? ');
$stmt->execute(array($uname,$email, $tax , $_SESSION['userSession']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Image
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
form related code to save in db
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
after this, now i am uploading an image to folder through same php form successfully with below code.
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
now images are just saving in folders, what i need is i want that image path to save in database and assign that image path to uploaded user in database. so that one registered user can update the existing image, but not upload one more image.
i tried below code , but not working:
<?php
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
$tax= $full_path;
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
db columns : userName, userEmail, tax , photo
with help of google i done all above, i am new to php, so please kindly help me.
Here is another solution:
First of all execute this query manually to add the new column:
ALTER TABLE `tbl_users` ADD `photo` VARCHAR(255) NOT NULL ;
Then this is the php code:
<?php
$dbConn = new Database();
$dbConn->dbConnection();
$user_home = new USER();
function uploadUserPhoto($uid) {
global $dbConn;
if(isset($_FILES["photo"]["error"])) {
if($_FILES["photo"]["error"] > 0) {
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
$userDir = $uid;
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)) {
if(!is_dir('upload/'.$uid)) {
mkdir('upload/'.$uid);
}
$photoname = time().$uid.'_photo'.'.'.$ext;
// delete all the files in this directory
$files = glob('upload/'.$uid.'/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
// Upload the photo
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname);
$updateData = array(':userID' => $uid, ':photo' => $photoname);
$stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:photo WHERE userID=:uid");
$stmt->execute($updateData);
echo "Your file was uploaded successfully.";
} else {
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else {
echo "";
}
}
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
uploadUserPhoto($uid);
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
There is $dbConnection variable which is the connection to the DB but because I don't know the rest of your code you should replace it with your proper db connection variable.
The photo of the user is saved in photo column in tbl_users and for every user is created sub dir in uploads dir. The subdir is the userID. So for example for user with userID = 1 its upload path will be uploads/1/<filename>.
File name is generated dynamically - this avoids caching of uploaded photo with the same name for example ... and it is better approach.
You have to make a change in code for displaying the photo because now its filename is in the DB and there is subdir in uploads (which is the userID of the user)
Add new function for saving files and use global php var $_FILES
1
Add new column to your DB to store file path, let's name it photo
2
Add new functions for your user class:
<?php
class User {
...
const PATH_PHOTOS = '/path/to/photo/folder/';
const BASE_URL = 'http://YOUR_DOMAIN_NAME:YOUR_PORT/YOUR_PATH/';
public function add_photo($file)
{
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$file['new_name'] = uniqid(rand(), true) . ".$ext";
if (!$this->_upload_file($file))
return false;
return $this->_remove_previous_photo()->_add_file_to_db(self::PATH_PHOTOS . basename($file['new_name']));
}
protected function _remove_previous_photo()
{
$photo = $this->get_photo();
if ($photo)
unlink($photo);
return $this;
}
public function get_photo()
{
global $_SESSION;
$stmt = $this->conn->prepare('SELECT photo FROM tbl_users WHERE userID = ? ');
$stmt->execute(array($_SESSION['userSession']));
$result = $stmt->fetch();
return reset($result);
}
public function get_photo_url()
{
$pathInfo = pathinfo($this->get_photo());
$last_dir = end(explode(DIRECTORY_SEPARATOR, $pathInfo['dirname']));
return self::BASE_URL . "$last_dir/" . basename($this->get_photo());
}
protected function _upload_file($file)
{
$uploadfile = self::PATH_PHOTOS . $file['new_name'];
return move_uploaded_file($file['tmp_name'], $uploadfile);
}
protected function _add_file_to_db($file_path)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET photo = ? WHERE userID = ? ');
return $stmt->execute(array($file_path, $_SESSION['userSession']));
} catch (PDOException $e) {
echo '<p class="bg-danger">' . $e->getMessage() . '</p>';
}
}
...
}
?>
3
The main file should look like this:
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid) && $user_home->add_photo($_FILES['photo']))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Hope this helps
I am designing a CMS with PHP PDO for user to update there information, this part I am letting the user change there business image, which will upload to the server and also to database through PHPMyAdmin.
With this I can upload the image and it will replace its value on the database as well fine. What I am having trouble with is when the user just wants to update other information (Not the image) and nothing else, the system submits the image value and replaces the row within database with no value (Blank upload) in the related row? As I would like it to not effect this row, if no image was uploaded.
I have been looking at if ($_FILES['image']['error'] === UPLOAD_ERR_NO_FILE) but not luck, but I think i am in the right area.
HTML
<form action='edit_account.php' method='post' enctype='multipart/form-data'>
<h4>Business Image</h4>
<input type='file' name='image' id='fileToUpload' >
<input type='submit' value='Update Account' />
</form>
PHP
if(isset($_FILES['image'])) {
$username = $_POST['username'];
$target_dir = "images/users/$username/";
$target_file = $target_dir.basename($_FILES['image']['name']);
$upload0K = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
if(isset($_POST['submit'])) {
$check = getimagesize($_FILES['image']['tmp_name']);
if($check !== false) {
echo "<p>File is an image - ".$check["mime"]."</p>";
$upload0K = 1;
} else {
echo "<p>File is not an image</p>";
$upload0K = 0;
}
}
//if (file_exists($target_file)) {
//echo "<p>Sorry, file already exists.</p>";
//$upload0K = 0;
//}
if ($_FILES['image']['size'] > 5000000) {
echo "<p>Sorry, your file is too large.</p>";
$upload0K = 0;
}
///
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "<p>Sorry, only JPG, JPEG, PNG and GIF files are allowed.</p>";
$upload0K = 0;
}
//if(!isset($_FILES['image']) || $_FILES['image']['error'] == UPLOAD_ERR_NO_FILE) {
//echo "Error no file selected";
//}
///
if ($upload0K == 0) {
echo "Sorry, your file was not uploaded.";
}
else {
if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
echo "<p>The file ". basename( $_FILES["image"]["name"])."has been uploaded.</p>";
} else {
echo "<p>Sorry, there was an error uploading your file.</p>";
}
}
}
SQL Insert
$query_params = array(
':email' => $_POST['email'],
':username' => $_POST['username'],
':name' => $_POST['name'],
':image' => $_FILES['image']['name'],
':description' => $_POST['description'],
':moderatedcheck' => $moderatedcheck,
':user_id' => $_SESSION['user']['id']
);
$query = " UPDATE users SET email = :email, username = :username, name = :name, image = :image, description = :description, moderatedcheck = :moderatedcheck";
The best and correct way of doing this is by judging the image Error value, An error value of 4 indicates that no file was uploaded. Other tests of the name of the file or other attributes are somewhat imprecise.
$imageFile = $_FILES['image'];
if ($imageFile['error'] != 4) {
///this code only runs if a file has been given.
}
update
I have been looking at if ($_FILES['image']['error'] ===
UPLOAD_ERR_NO_FILE) but not luck, but I think i am in the right area.
The $_FILES['image']['error'] is the correct thing to check but this value is a numeric value NOT a text value. See if checking if $_FILES['image']['error'] == 4 works better.
Update 2
Replace if(isset($_FILES['image'])) { in your file with:
if ($_FILES['image']['error'] != 4)}{
This will then only run the following code if there is a file given, although there may still be errors such as filesize etc.
Also SQL insert:
Replace original with:
$query_params = array(
':email' => $_POST['email'],
':username' => $_POST['username'],
':name' => $_POST['name'],
':description' => $_POST['description'],
':moderatedcheck' => $moderatedcheck,
':user_id' => $_SESSION['user']['id']
);
$query = " UPDATE users SET email = :email, username = :username, name = :name, description = :description, moderatedcheck = :moderatedcheck";
and add a qualifier:
if ($_FILES['image']['error'] == 0 ){
$query_params[':image'] = $_FILES['image']['name'];
$query = " UPDATE users SET email = :email, username = :username, name = :name, image = :image, description = :description, moderatedcheck = :moderatedcheck";
}
this will then only add the filename data to the insert array if the file is i) present and ii) not with an error. Alternatively saving the file to the database if it does have an error will probably be rather pointless, but would be done replacing that if statement with if ($_FILES['image']['error'] != 4 ) .
Your Sql can be built dynamicly, define a variable like $imageSql = ''; at the start of the code, when $_FILES['image'] issetted overwrite your $imageSql = ', image = :image'; and your $query_params[':image'] = $_FILES['image']['name'] and lastly your query will be like :
$query = " UPDATE users SET email = :email, username = :username, name = :name".$imageSql.", description = :description, moderatedcheck = :moderatedcheck";
I use this:
if(is_uploaded_file($_FILES["image"]["tmp_name"])){
//query to update the data with the image
}else{
//query to update the data without the image
}