I have a board_directors.php page,
When I update my page from admin panel, It' showing
Forbidden
You don't have permission to access /new/admin/board_directors.php on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Here has 6 form fields and 2 textarea field.
and my code is:
if(isset($_REQUEST['submitted']) && $_GET['edit'] == "yes"){
$id = $_GET['id'];
$yes = $_GET['edit'];
$dir_sl = $_POST['dir_sl'];
$dir_name = $_POST['dir_name'];
$dir_position = $_POST['dir_position'];
$dir_email = $_POST['dir_email'];
$dir_mobile = $_POST['dir_mobile'];
$dir_details = $_POST['dir_details'];
$file2 = $_FILES['file']['name'];
if(!empty($file2)){
$file = $_FILES['file']['name'];
// Uploade Image Directory start
$add="board_directors_images/".$_FILES['file']['name']; // the path with the file name where the file will be stored, upload is the directory name.
//echo $add;
if(move_uploaded_file ($_FILES['file']['tmp_name'],$add)){
//echo "Successfully uploaded the image";
chmod("$add",0777);
}
///////// Start the thumbnail generation//////////////
$n_width=100; // Fix the width of the thumb nail images
$n_height=140; // Fix the height of the thumb nail imaage
////////////////////////////////////////////
$tsrc="board_directors_images/thumb/".$_FILES['file']['name']; // Path where thumb nail image will be stored
/////////////////////////////////////////////// Starting of png thumb nail creation///////////
if (#$_FILES['file']['type']=="image/png")
{
$im=ImageCreateFrompng($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$n_height=($n_width/$width) * $height; // Add this line to maintain aspect ratio
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
if (function_exists("imagepng")) {
Header("Content-type: image/png");
Imagepng($newimage,$tsrc);
}
elseif (function_exists("imagejpeg")) {
Header("Content-type: image/jpeg");
ImageJPEG($newimage,$tsrc);
}
chmod("$tsrc",0777);
}////////// end of png file thumb nail creation//////////
////////////// starting of JPG thumb nail creation//////////
if($_FILES['file']['type']=="image/jpeg"){
$im=ImageCreateFromJPEG($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$n_height=($n_width/$width) * $height; // Add this line to maintain aspect ratio
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImageJpeg($newimage,$tsrc);
//chmod("$tsrc",0777);
}
} else {
$sql1 = "SELECT * FROM tbl_board_directors WHERE fld_id =' ".$_GET['id']."' limit 1";
$result1 = mysql_query($sql1);
$test = mysql_fetch_array($result1);
$file = $test['fld_pic'];
$file = $file;
}
// End upload image direcotory
$sql = mysql_query("update tbl_board_directors set fld_sl_no = '".$dir_sl."', fld_name = '".$dir_name."', fld_post = '".$dir_position."', fld_email = '".$dir_email."', fld_mobile = '".$dir_mobile."', fld_details = '".$dir_details."', fld_pic = '".$file."' where fld_id = '".$id."' ");
if($sql){
//echo "<strong style='color:green; font-size:14px;'>Board of directors Updated!</strong>";
header("Location: board_directors.php?id=".$id."&edit=".$yes."&confirm=Content Updated!");
}
}
Related
We have a feature that lets users upload images on a website, which can be from a desktop or taken from any cellphone. But from some phones like Iphone images taken vertically end up rotated the wrong way. We need them to be displayed correctly on any device when uploaded from any device.
I found some similar questions but their solution didn't seem to work completely. I need to either rotate them correctly in php as soon as they are uploaded:
if(isset($_FILES["submit_image"])) {
$target_dir = "uploads/images/";
$name = $_FILES['submit_image']['name'];
$size = $_FILES['submit_image']['size'];
$tmp_name = $_FILES['submit_image']['tmp_name'];
//make sure the image is roated correctly? I tried this code that I found in other SO questions but then it doesn't seem to be saving it
// START ORIENTATION FIX
$info = getimagesize($tmp_name);
$image = imagecreatefrompng($tmp_name);
if($info['mime'] == 'image/jpeg') {
$exif = exif_read_data($tmp_name);
if(isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
}
}
if(isset($orientation)) { //rotate to match the orientation
switch($orientation) {
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, -90, 0);
break;
case 8:
$image = imagerotate($image, 90, 0);
break;
}
}
if(isset($image)) { //get the variables of the rotated image
$tmp_name = $image["tmp_name"];
$name = $image['name'];
$size = $image['size'];
}
// END ORIENTATION FIX
/*doing some other checks here for image name, size, and mime type
...
*/
$path = calculate_file_path($target_dir, $name);
if (move_uploaded_file($tmp_name, $path) == true) {
$query = "UPDATE {$table} SET {$column} = '{$path}' WHERE id = {$new_pro_id}";
$result = mysqli_query($db, $query);
if ($result) {
//saved
}
else{
//failed
}
}
}
Or maybe fix them later with css whenever the site needs to display them:
.profile_img
{
image-orientation: from-image;
}
But neither seemed to work. the php option broke them completely, and the css option didn't fix the orientation.
EDIT
I get a warning/error message:
exif_read_data() expects parameter 1 to be a valid path, array given in...
But there is no file path anywhere at that point. All I have is $_FILES['submit_image'] which comes from a type="file" field in an html form. I'm sure this variable has all the information which would be in the file path because I use it later to save to the server.
Any ideas?
Thanks :)
I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
I have been developing my website for some time now, and I am looking to make it even better with one small detail. Currently, when a user creates and account, they can view their "My Page" and do all sorts of things, including change their profile picture from the default one I have provided, to whatever they want. Unfortunately, if they were to upload an image with a ratio of anything greater than or less than 1:1, i.e. 300x200, then my script will re-size it to fit the avatar form, but it keeps the ratio, and makes the image float to the top of the box. Here is an image of an avatar that does not have a 1:1 ratio:
As you can see, the image is as I describe it above. The only time it makes a perfect square is when the image that the user uploads has a 1:1 ratio. Here is an example:
Obviously, it is unreasonable to expect that a user will always upload a 1:1 image. So what I am looking for is someone to help me tweak my script, which I will provide, so that on all avatar uploads, even if the image has a 1:1 ratio, will pretty much mount the image into a black "canvas", for lack of better wording, and center the image on that canvas both vertically and horizontally. Here is what I mean, using an image that I edited in Photoshop to give it the black canvas:
As you can see, the profile picture in this last image is exactly what I need my script to do. I will provide my script:
PHP
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 2048576) {
header("location: ../message.php?msg=ERROR: Your image file was larger than 2MB");
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
} else if ($fileErrorMsg == 1) {
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../user.php?u=$log_username");
exit();
}
?>
Thanks in advance, any help will be much appreciated!
Insert the image as a background instead of an img tag, then you can position it center.
<div class="avatar"></div>
.avatar {
width: 200px;
height: 200px;
background-image: url("avatar.png");
background-repeat: no-repeat;
background-position: center center;
border-radius: 50%; // If you want it to be a circle
}
This script will load an image (jpg, gif or png) and then save a PNG local copy for caching.
I'm trying to find a way to resize the image to 300x300 before saving it as a PNG.
I tried to use the function imagecopyresampled() but the image is still not resized.
2 problems now :
The script saves a resized PNG image in the correct folder, but the image is empty (it's all black)
The first time i will load the image, i will get an error (image cannot be displayed because it contains error) but the image will still be saved as PNG in the cache folder. Second time i load the image, it will be displayed correctly (using the cached version) but it isn't resized.
Here's the full code of my page. The first part is used to cache the image, the second part is used to display the non-cached image (it reads an image from a ZIP file and output the content without extracting anything)
if (empty($_GET['display'])) {
header('Content-Type: image/png');
$imgpochette = $_GET['i'];
$ENABLE_CACHE = true;
$CACHE_TIME_HOURS = 744;
$CACHE_FILE_PATH = "pochette_album/$imgpochette.png";
if($ENABLE_CACHE && file_exists($CACHE_FILE_PATH) && (time() - filemtime($CACHE_FILE_PATH) < ($CACHE_TIME_HOURS * 60 * 60))) {
echo #file_get_contents($CACHE_FILE_PATH);
} else {
// Load the requested image
$imgdisplay = "http://www.pirate-punk.com/pochette.php?i=$imgpochette&display=1";
$image = imagecreatefromstring(file_get_contents($imgdisplay));
$width = "30";
$height = "30";
list($originalWidth, $originalHeight) = getimagesize($CACHE_FILE_PATH);
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
// Send the image
imagepng($new_image, $CACHE_FILE_PATH);
exit();
#file_put_contents($CACHE_FILE_PATH, $output);
echo $output;
}
}
if (!empty($_GET['display'])) {
function showimage($zip_file, $file_name) {
$z = new ZipArchive();
if ($z->open($zip_file) !== true) {
echo "File not found.";
return false;
}
$stat = $z->statName($file_name);
$fp = $z->getStream($file_name);
// search for a path/to/file matching file, returning the index of it
$index = $z->locateName($file_name, ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR);
// get the name of the file based on the index
$full_file_name = $z->getNameIndex($index);
// now get the stream
$fp = $z->getStream($full_file_name);
if(!$fp) {
echo "Could not load image.";
return false;
}
header('Content-Type: image/jpeg');
header('Content-Length: ' . $stat['size']);
fpassthru($fp);
return true;
}
$imgsrcencoded = $_GET['i'];
$imagesrc = base64_decode($imgsrcencoded);
$explodez = explode("#",$imagesrc);
$imgg = utf8_encode($explodez[1]);
$dirnfile = $explodez[0];
$zipp = end((explode('/', $dirnfile)));
$dirr = str_replace($zipp,"",$dirnfile);
$dirr = rtrim($dirr,"/");
$imgg = rtrim($imgg);
chdir($dirr);
if (empty($_GET['debug'])) {
echo showimage($zipp,$imgg);
}
}
Get the solution for .png images
I have a script which uploads an image to the server under the id of the user. To change teh picture the first gets overwritten. The problem is that the old picture, with the dimensions of the new one, shows for a while until they refresh their browser. How can I prevent this from happening?
Script:
function uploadProfilePicture($memberID,$extension)
{
##### FIND ERRORS #####
$error = "";
// check if larger than 5mb
$avatar = $_FILES['uploadedAvatar'];
if( $avatar["size"] > 5000000 ){ //5mb
$error = SETTINGSphoto_less_5meg;
}
//check if member selected a photo
if( $avatar['name'] == "" ){
$error = SETTINGSphoto_no_upload;
}
//check if photo is of allowed formats
if( $avatar["type"] != "image/png" ){
if( $avatar["type"] != "image/gif" ){
if( $avatar["type"] != "image/jpg" ){
if( $avatar["type"] != "image/jpeg" ){
if( $avatar["type"] != "image/pjpeg" ){
$error = SETTINGSphoto_file_type;
}
}
}
}
}
#### END FIND ERRORS #####
##### DISPLAYS ERRORS ######
if( $error != ""){
echo '<span style="background-color:#E05641;" class="pint2">'.$error.'</span>';
##### END DISPLAYS ERRORS ######
##### PROCESS THUMBNAIL AND UPLOAD PICTURE #####
}else{
$ext = substr($avatar["name"], -4); //take off extention.
$fileName = $memberID.$extension.$ext; // rename picture with member's ID.w
unlink("photos/".$memberID.$extension.".jpg");
unlink("photos/".$memberID.$extension."Thumb.jpg");
copy($avatar['tmp_name'], "photos/".$fileName); //upload temp
//create virual image
if(preg_match('/[.](jpg)$/',strtolower($avatar["name"]))) {
$im = imagecreatefromjpeg("photos/".$fileName);
} else if (preg_match('/[.](gif)$/', strtolower($avatar["name"]))) {
$im = imagecreatefromgif("photos/".$fileName);
} else if (preg_match('/[.](png)$/', strtolower($avatar["name"]))) {
$im = imagecreatefrompng("photos/".$fileName);
} else if (preg_match('/[.](jpeg)$/',strtolower($avatar["name"]))) {
$im = imagecreatefromjpeg("photos/".$fileName);
}else{
$im = imagecreatefromjpeg("photos/".$fileName);
}
//get height and width
$ox = imagesx($im); $oy = imagesy($im);
$final_width_of_image = 200;
$final_height_of_image = 200;
//$ratio = $final_width_of_image / $ox; //find ratio to apply to height
//$nx = $final_width_of_image; $ny = $oy * $ratio;
if( $ox < $oy ){
$nx = 200;
$ny = floor($oy * (200 / $ox));
}else{
$ny = 200;
$nx = floor($ox * (200 / $oy));
}
//$nm = imagecreatetruecolor($nx, $ny);
//imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy); //create new pic
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
unlink("photos/".$fileName); //delete temp image
imagejpeg($nm, "photos/".$memberID.$extension.".jpg",100); //save image // 100 = quality
$im = imagecreatefromjpeg("photos/".$memberID.$extension.".jpg");
$nm = imagecreatetruecolor(200, 200);
imagecopyresampled($nm, $im,0,0,0,0,200,200,200,200);
imagejpeg($nm, "photos/".$memberID.$extension."Thumb.jpg",100);
$sql = "UPDATE exchange SET photo = 1 WHERE id = '$memberID'"; //update db
$mysql = new mysql();
$mysql->query($sql);
##### END PROCESS THUMBNAIL AND UPLOAD PICTURE #####
echo '<span class="pint2">'.SETTINGSphoto_chage_success.' <a style="color:#ffffff" href="'.$_ENV['rootURL'].'/'.( in_array($_GET['lang'],$_ENV['supportedLanguages']) ? $_GET['lang']."/" : $nothing).HEADlanguage_exchange.'/id/'.$memberID.'">'.SETTINGSphoto_view_profile.'</a></span>';
}
}
The problem is that the old picture, with the dimensions of the new one, shows for a while until they refresh their browser. How can I prevent this from happening?
You can solve this by telling the user she should clear the browser cache.
If that is not an option, you want to actually prevent the user to cache the image.
So you need to make a difference between each revision of the image. Add a integer field to your database you store the revision number of the image. Then each time you output the user's image, fetch the actual revision number from the database as well. Add it as the query-info-part of the image URL:
<img src="avatars/user/929292/photo.jpg?revision">
^^^^^^^^
The browser will still cache profile pictures but you make him aware of the revision, so a specific revision is cached.
Old avatar picture:
<img src="avatars/user/929292/photo.jpg?1">
Then the user uploads a new image, you increment the revision field, the new avatar image is:
<img src="avatars/user/929292/photo.jpg?2">
If the revision changes, the browser notices that and will pick the image from the server.
You could give the new image a slightly different filename, so the browser loads the new image rather than using the old cached one.
In your PHP code for the image source you can append a timestamp to force the photo to always appear as a new photo. Throw some logic in to only do this for updated records and you'll be more cache friendly.
<img src="your_profile_url.jpg?<?= time(); ?>"/>