I'm trying to allow my users to upload a profile picture and display it on their profile.
I've created profilepic.php and added a new function in classes/User.php
So far I'm trying to submit a string via text input and associating it with the current user_id that is logged in.
The function inside 'classes/User.php'
public function uploadPhoto($fields = array()) {
$photo = $this->_db->insert('userPhotos', array('user_id' => $this->data()->id));
if(!$photo) {
throw new Exception('There was a problem creating your account.');
}
}
ProfilePic.php
<?php
require_once 'core/init.php';
include('includes/header.php');
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'url' => array(
'required' => false
)
));
if(!$validation->passed()) {
try {
/* $user->uploadPhoto(array(
'url' => Input::get('url'),
)); */
//This is the directory where images will be saved
$target = 'var/www/app/img';
$target = $target . basename($_FILES['url']['name']);
$pic= ($_FILES['url']['name']);
//Writes the information to the database
//$this->data()->query('INSERT INTO userPhotos (photo) VALUES (‘$pic’)');
$user->uploadPhoto(array(
'url' => Input::get($pic)
));
//Writes the photo to the server
if(move_uploaded_file($_FILES['url']['tmp_name'], $target))
{
echo 'Ok' . basename( $_FILES['uploadedfile']['name']);
}
else {
//Gives and error if its not
echo 'Sorry, there was a problem uploading your file.';
}
Session::flash('home', 'Your profile photo has been uploaded.');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<div class="container">
<div class="row row-offcanvas row-offcanvas-right">
<div class="col-xs-12 col-sm-9">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Toggle nav</button>
</p>
<div class="jumbotron">
<h1>Edit Profile</h1>
<p>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="url">URL</label>
<input type="file" id="url" name="url" value="">
<p class="help-block">Example block-level help text here.</p>
<input type="submit" value="Update">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
</div>
</form>
</p>
</div>
<div class="row">
</div><!--/row-->
</div><!--/span-->
<?php include 'includes/sidebar.php'; ?>
</div><!--/row-->
<hr>
<?php include('includes/footer.php'); ?>
userPhotos table has 4 fields: id, user_id (relationship with id in users table), url, date
users table has 6 fields: id, username, password, salt, name, group
So far if I navigate to profilepic.php select a picture and click upload, it will display a success message that my photo has been uploaded. I look into the database, only the row id (auto_increment) and my id (logged_in user id) are being submitted while the "url" field which is supposed to hold the name of the image is not registering.
Related
Let me explain my problem briefly.I have image names in MYSQL database.
I need to change the image name when user uploads a new image using file input field.Otherwise the image name in database remain same.But My problem is when user doesn't upload any images the image name becomes empty in database.
My HTML code for changing a image
<form method="post" action="edit_store_img.php?id=<?php echo (int)$store['id'] ?>" class="clearfix" enctype="multipart/form-data">
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a store image</label>
<input type="file" name="storepic" value="<?php echo $store['pic']; ?>"/>
</div>
</div>
<hr>
<br>
<h3>Change Map Image For Store <?php echo remove_junk($store['name']);?></h3>
<hr>
<!-- below code is for map image -->
<?php if($store['pic'] === '0'): ?>
<img class="img-avatar img-circle" src="uploads/mapimg/no_image.jpg" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php else: ?>
<img class="img-avatar img-circle" src="uploads/mapimg/<?php echo $store['map']; ?>" alt="Store_map_picture" style="width: 200px;height: 200px;">
<?php endif;
?>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-th-large"></i>
</span>
<label for="file">Upload a Store map location image</label>
<input type="file" name="mappic" value="<?php echo $store['map']; ?>"/>
</div>
</div>
<div class="col-md-12">
<button type="submit" name="edit_store_img" class="add-btn">Update Store image</button>
</div>
</form>
This is my PHP file for getting ID for that particular image
<?php
$store = find_by_id('store',(int)$_GET['id']);
if(!$store)
{
$session->msg("d","Missing store id.");
redirect('store.php');
}
?>
This is my PHP code for Storing image name in database
<?php
if(isset($_POST['edit_store_img']))
{
if(empty($errors))
{
/*below queries is for image upload */
$msg = "";
$map = $_FILES["mappic"]["name"];
$tempname = $_FILES["mappic"]["tmp_name"];
$mapfolder = "uploads/mapimg/".$map;
// Now let's move the uploaded image into the mapfolder: image
if (move_uploaded_file($tempname, $mapfolder)) {
$msg = "map Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$message = "";
$pic = $_FILES["storepic"]["name"];
$tempname = $_FILES["storepic"]["tmp_name"];
$picfolder = "uploads/storeimg/".$pic;
// Now let's move the uploaded image into the folder image
if (move_uploaded_file($tempname, $picfolder)) {
$message = "Image uploaded successfully";
}else{
$message = "Failed to upload image";
}
$query = "UPDATE store SET";
$query .=" map ='{$map}', pic ='{$pic}'";
$query .=" WHERE id ='{$store['id']}'";
$result = $db->query($query);
if($result && $db->affected_rows() === 1){
$session->msg('s',"store updated ");
redirect('store.php', false);
} else {
$session->msg('d',' Sorry failed to updated!');
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
else
{
$session->msg("d", $errors);
redirect('edit_store_img.php?id='.$store['id'], false);
}
}
?>
I Need to store image name when user doesn't upload image.I need to avoid the image name db field becomes empty.
Below quirky will somehow fix your problem; however, this is not the correct way I think;
$query .=" map = IF('{$map}' != '', '{$map}', map), pic = IF('{$pic}' != '', '{$pic}', pic)";
We are just asking the database to update with the exiting column value if the passed value is empty.
The correct way should be not to take it for granted that the user have uploaded a file; as you are doing with these below lines in your code;
$map = $_FILES["mappic"]["name"];
...
$pic = $_FILES["storepic"]["name"];
You should be actually using IF conditions to check if some viable value has been set for those _FILES variables so you know what to process for and what not, and prepare your SQL UPDATE statement accordingly.
Actually while uploading a file I am creating folder with timestamp and also saving folder name along with filename to the database this is working fine. While editing I have input type hidden in this I am posting value if user do not change files and also if folder exits already it should not create folder and If user change files that time it should create a new folder.Only it is going to if condition. not else part.Please help me someone.
Below is PHP code,
if(isset($_FILES['event_image']['name'])&& $_FILES['event_image']['name']!="")
{
$folder_name =$_FILES['event_image']['name'];
echo $folder_name;
}
else
{
$folder_name =$_POST['image_exists'];
echo $folder_name;
}
//print_r($pathToUpload);die;
$old = umask(0);
if (!file_exists($folder_name))
{
//echo "djfgd";die;
$folderName = $_POST['event_name'].time();
$pathToUpload = 'images/events/' . $folderName;
$create = mkdir($pathToUpload, 0777,true);
//chmod($pathToUpload,0755,true);
if ( ! $create )
return;
}
else{
//echo "dqqqqqq";die;
//$folderName = $_POST['event_name'].time();
//$pathToUpload = 'images/events/' . $folderName;
//$create = mkdir($pathToUpload, 0777,true);
echo "already exits";die;
}
umask($old);
HTML code:
<div class="col-md-6">
<div class="form-group">
<label for="event_image">Event Banner</label>
<input type="file" value="<?php echo $event_image; ?>"
class="form-control" id="eventimage" name="event_image">
<input type="hidden" name="image_exists" value="<?php echo $event_image;?>"
class="form-control" id="eventimage" placeholder="Enter Image Text" aria-describedby="fileHelp">
<div><?php echo $event_image;?></div>
</div>
</div>
Alright I have simulated your case on my machine using Codeigniter and simple PHP is_dir function.
Here is my test view
Created with Following Markup
<div class="container" style="margin-top:100px; ">
<div class="col-md-6" style="border: 1px dotted red; ">
<?php if(isset($errors)){?>
<div class="alert alert-danger">
<?php print_r($errors);?>
</div>
<?php }?>
<?php if(isset($success)){?>
<div class="alert alert-success">
<?php print_r($success);?>
</div>
<?php }?>
<form action="" method="post" id="form1">
<div class="form-group">
<label > Directory Name</label>
<input type="text" name="name" class="form-control" >
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" >Create</button>
</div>
</form>
</div>
</div>
My Controller
public function index()
{
$data['title']='Multiple submit';
if($_POST)
{
$path='uploads/'.$_POST['name'];
if (!is_dir($path)) {
mkdir($path);
$data['success']='Directory Created Successfully';
$this->load->view('form',$data);
}
else
{
$data['errors']='Directory Already Exist';
$this->load->view('form',$data);
}
}
else
{
$this->load->view('form',$data);
}
}
I create a directory, which is success.
I try it again, get an error
The Directory created in my path is
I hope you can modify this code as per your requirements.
I am trying to upload 2 images and save the file name for each file to MySQL database. I have tried different options but I can't get this to work.
On my MYSQL table field name for file name is called file_name
varchar 500
I can save the other form data into my database without a problem.
However I can't get the image(s) uploaded.
Following is my image portion of the web form.
Here is the FORM action area
<form method="post" action="php/smartprocess.php" enctype="multipart/form-data" id="smart-form">
My image upload section as following
smartprocess.php section is
<?php
if (!isset($_SESSION)) session_start();
if(!$_POST) exit;
require 'database.php';
include dirname(__FILE__).'/settings/settings.php';
include dirname(__FILE__).'/functions/emailValidation.php';
$TechName = strip_tags(trim($_POST["TechName"]));
$FullAssembly = strip_tags(trim($_POST["FullAssembly"]));
$Notes = strip_tags(trim($_POST["Notes"]));
$SignedDate = strip_tags(trim($_POST["SignedDate"]));
$captcha = strip_tags(trim($_POST["captcha"]));
try {
$q = "INSERT INTO tportal (TechName, FullAssembly, Notes, SignedDate)
VALUES (:TechName, :FullAssembly, :Notes, :SignedDate)";
$query = $conn -> prepare($q);
$results = $query -> execute(array(
":TechName" => $TechName,
":FullAssembly" => $FullAssembly,
":Notes" => $Notes,
":SignedDate" => $SignedDate,
));
if ($conn->query($q)) {
$errors = array();
echo '<div class="alert notification alert-success">Problem has accured please try again.</div>';
//Javascript alert top
/*echo "<script type= 'text/javascript'>alert('Issue adding data');</script>";*/
}
else{
echo '<div class="alert notification alert-success">Your message has been sent successfully!</div>';
//Javascript alert top
/*echo "<script type= 'text/javascript'>alert('Data not successfully Inserted. $PocketCond');</script>";*/
}
$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
if(isset($_POST["captcha"])){
if (!$captcha) {
$errors[] = "You must enter the captcha code";
} else if (($captcha) != $_SESSION['gfm_captcha']) {
$errors[] = "Captcha code is incorrect";
}
}
?>
<div class="section">
<label for="file1" class="field-label">
Upload another image - <span class="small-text fine-grey"> (ONLY JPG : PNG : PDF) </span>
</label>
<label class="field prepend-icon file">
<span class="button btn-primary"> Choose File </span>
<input type="file" class="gui-file" name="image" id="file1"
onChange="document.getElementById('uploader1').value = this.value;">
<input type="text" class="gui-input" id="uploader1" placeholder="no file selected" readonly>
<span class="field-icon"><i class="fa fa-upload"></i></span>
</label>
</div><!-- end section -->
Your help and time is much appreciated.
Sincerely,
Use $_FILES variable of php to help your files uploaded. There is a simple tutorial on file upload in php here
I am using a form that posts a profile picture, then a functions file which parses the data and sends it to a rest service which is developed with the slim framework.
Here is my code:
form.php:
<form action="<?php echo url('functions.php'); ?>" method="post" class="validate form-horizontal">
<input type="hidden" name="action" value="save_account_settings">
<div class="form-group">
<label class="col-sm-3 control-label"><span class="colordanger">*</span>Profile picture</label>
<div class="col-sm-9">
<input type="file" name="profile_picture" class="form-control" value="<?php echo $user->profile_picture; ?>" data-rule-required="true">
<span class="help-block">Upload your profile picture here</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button type="submit" class="btn btn-primary" data-loading-text='<i class="fa fa-spinner fa-spin"></i> Saving...'><i class="fa fa-check"></i> Save</button>
</div>
</div>
</div>
</form>
functions.php:
case 'save_account_settings':
try {
$input = array (
"profile_picture" => "#" . post('profile_picture')
);
$extension = '/save_account_settings';
$result = process_api_put($input,$base_url,$extension);
msg($result->message, $result->status);
}
catch (Exception $e)
{
msg($e->getMessage(), "danger");
}
break;
And then rest.php:
$app->put("/save_account_settings", function() use ($app)
{
$input = $app->request()->getBody();
$input = json_decode($input);
try {
if ($input->username && $input->email)
{
//save the file
$file_extension = pathinfo($input->profile_picture, PATHINFO_EXTENSION);
$server_file_address = realpath('./') . '/uploads/profile_pictures/' . $_SESSION['id'] . date('Y-m-d H:i:s') . $file_extension;
move_uploaded_file( $input->profile_picture, $server_file_address );
//save to database
$users = Model::factory('Users')->where('id', $_SESSION['id'])->find_one();
$users->set('profile_picture', '/uploads/profile_pictures/' . $_SESSION['id'] . date('Y-m-d H:i:s') . $file_extension);
$users->save();
$status = "success";
$message = 'Your settings have been saved successfully.';
}
else
{
$status = "danger";
$message = 'Some error has occured. Please try again.';
}
}
catch (Exception $e)
{
$status = "danger";
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
It saves the filename in the database but doesnot save the file in the uploads directory. Does anyone see where I am going wrong?
I need some help getting the login in my footer to change to logout if the user is logged in. I got it working on the login.php page, when the user logs in, it will label Log out, but if I go to About page, then it still says login. In my footer I have
<?php
if(isset($_SESSION['user'])) {
print("Log Out");
}
else{
print("Login");
}
?>
but it does not seem to work, only on the login page. I will post the code for the about,login, and footer pages below. I must be doing something amiss with sessions since its only working on the one page, but I cannot seem to find where. Sorry its a lot of code, but I wanted to paste it all just in case i didnt paste the part where the problem was occurring
Thank you so much
login.php
<?php
include "db.php";
if (isset($_POST['username']) && isset($_POST['password']))
{
$loginQuery = mysqli_query($con, "SELECT * FROM `users` WHERE `hashpassword` = '".sha1($_POST['password'])."' AND `username` = '".$_POST['username']."'");
if (mysqli_num_rows($loginQuery) == 1) $_SESSION['user'] = $_POST['username'];
}
?>
<?php
$pageName = "Administrator Login";
include 'header.php';
?>
<div class="one">
<?php
if(isset($_SESSION['user'])) {
echo "Welcome! You are logged in as : ".$_SESSION['user'];
//adding photos
print("<br/>Add A Photo");
$mysqli = new mysqli(DB_HOST,DB_USER, DB_PASSWORD, DB_NAME);
$result = $mysqli->query("SELECT DISTINCT photoYear FROM Photos");
print('<form method="post" enctype="multipart/form-data"><table>
<tr><td>*Upload Image</td><td><input type="file" name="newphoto"/></td></tr>
<tr><td>*Year To Upload To</td><td><input type="text" name="year"></td></tr><tr><td></td><td class="left"><input type="submit" name="sub" value="Add Photo" /></td></tr></table></form>');
}
else {
?><h1>Please Login Here To Make Administrative Changes</h1>
<form action="" method="post">
Username: <input type="text" name="username"> <br>
Password: <input type="password" name="password"> <br>
<input type="submit" value="Log In">
</form>
<?php } ?>
<?php
/* creating new year albums and uploading photos
if(isset($_SESSION['user'])){
//once user is logged in... can upload photos to certain years
/* Adding photo to year albums
print('<form method="post" enctype="multipart/form-data"><table>
<tr><td>*Upload Image</td><td class="left" ><input type="file" name="newphoto"/></td></tr>
<tr><td>*Year To Upload To</td><td class="left" ><select name="yearz">');
while($row = $result -> fetch_assoc()){
$year=$row[ 'photoYear'];
print("<option value=".$year.">".$year."</option>");
}
print('</select></td></tr><tr><td></td><td class="left"><input type="submit" name="sub" value="Add Photo" /></td></tr></table></form>');
if (!empty($_FILES[ 'newphoto' ]) && isset($_POST['yearz']) && isset($_POST['sub'])){
$newPhoto = $_FILES[ 'newphoto' ];
$year = $_POST['yearz'];
$errors= array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['newphoto']['size'] >= $maxsize) || ($_FILES["newphoto"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES['newphoto']['type'], $acceptable) && (!empty($_FILES['newphoto']['type']))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
//next
if(count($errors) ===0){
$originalName = str_replace(" ","_",$newPhoto[ 'name' ]);
$result = $mysqli->query("SELECT photoURL FROM Photos WHERE photoURL =".$originalName);
if (!($row = $result -> fetch_assoc())){
$test = explode('|', $_POST['alb']);
$albumid = $test[0];
$caption = $_POST[ 'caption' ];
if ($newPhoto['error'] == 0){
$tempName = $newPhoto[ 'tmp_name' ];
move_uploaded_file( $tempName, "$originalName");
$_SESSION[ 'photos'][] = $originalName;
print("File was uploaded.");
$adding = "INSERT INTO Photos (`photoURL`,`photoYear`)
VALUES('$originalName', '$yearz');";
$mysqli -> query($adding);
}
}
else{
print("This photo is already in the database. Try uploading another.");
}
}
else{
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die();
}
}
//outer
}
*/
?>
</div>
<?php
include "db.php";
include 'footer.php';
session_unset();
session_destroy();
?>
</html>
about.php
<?php
$pageName = "About RFYC";
include 'header.php';
?>
<div class="one">
<img class="center" src="images/logo/black.png" alt="logo">
<p>
Root For Your Cause is an annual charity root beer pong tournament held at Cornell University. The event is sponsored by Alpha Phi Omega - Gamma Chapter, a national community service fraternity. When registering for the event each team or organization selects a charity to play for. At the end of this single-elimination tournament, the entire sum of money earned through registration is then donated to the winning team's charity of choice!<br/>
</p>
<p>
The event is also friendly to spectators. There is music, plenty of chairs to watch friends compete, and we sell root beer floats throughout the competition.
The registration fee is $10 per two-person team for individual teams, and $8 per two-person team for organizations registering 5 or more teams who will all be competing for the same charity.
For more information, contact <span id="email">philanthropy#apogamma.org</span>
</p>
</div>
<div class="winners">
<h1>Past Winners</h1>
<figure>
<figcaption>2011<br/>
<img src="images/icons/placeholder_circle.png" alt="winner"><br/>
Team Name<br/>Charity</figcaption>
</figure>
<figure>
<figcaption>2012<br/>
<img src="images/icons/placeholder_circle.png" alt="winner">
<br/>Team Name<br/>Charity</figcaption>
</figure>
<figure>
<figcaption>2013<br/>
<img src="images/icons/placeholder_circle.png" alt="winner">
<br/>Team Name<br/>Charity</figcaption>
</figure>
</div>
<?php
include 'footer.php';
?>
</html>
footer.php
<div id="wrapper">
<div id="footer">
<div class="footerFloat">
<h4>Site Map</h4>
About <br/>
Rules<br/>
Gallery<br/>
Bracket<br/>
Register
</div>
<div class="footerFloat">
<h4>Connect With Us</h4>
<ul>
<li><img src="images/icons/email.png" alt="email"></li>
<li><img src="images/icons/fb.png" alt="fb"></li>
<li><img src="images/icons/twitter.png" alt="twitter" ></li>
</ul>
</div>
<div class="footerFloat">
<h4>Manage</h4>
<?php
if(isset($_SESSION['user'])) {
print("Log Out");
}
else{
print("Login");
}
?>
</div>
<div class="footerFloat">
<h4>Brought to You By</h4>
Alpha Phi Omega - Cornell Chapter
</div>
</div>
</div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/interactivity.js" type="text/javascript"></script>
session_start() needs to be included on all pages, or your session will not exist.