How to check image extension - javascript

$image= addslashes(file_get_contents(basename($_FILES['image']['tmp_name'])));
if(!empty($_FILES['image']['tmp_name']) && file_exists($_FILES['image']['tmp_name'])) //image is selected
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext == 'png' ||$ext == 'jpeg'||$ext == 'jpg')
{
//$insertQuery
}
else
{
echo '<script language="javascript">';
echo 'alert("Please select correct picture format")';
echo '</script>';
}
The problem is that I can't get/validate the file extension. Every time I upload a photo that matches the condition, it will only show me the "select correct picture" message.
What's wrong with my code?

you can use php built-in pathinfo function.
<?php
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$src_file_name = 'abskwlfd.PNG';
$ext = strtolower(pathinfo($src_file_name, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
if (in_array($ext, $supported_image)) {
echo "it's image";
} else {
echo 'not image';
}
?>

Related

Returning array values (image file names to javascript) from php

Hi I have a php file which is reading all the image files in a directory as so:
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
and I want to get the resulting array in javascript. This code is not working. Any idea why?
<script type = "text/javascript">
$(function() {
$.getJSON('fileNames.php', function(data) {
console.log('yaa');
$(data).each(function(key, value) {
console.log(value);
});
});
});
</script>
getJson performs an ajax call, which will read the contents of the file as its written/displayed, so your echo "filename:" . $file . "<br>"; is becoming part of that meaning your json is becoming invalid
comment out that line and you should be fine
<?php
$dir = "Images/";
$arrayjs = array();
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != "." && $file != ".."){
$arrayjs[] = $file;
//echo "filename:" . $file . "<br>";
}
}
closedir($dh);
}
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($arrayjs);
?>
The method wants nothing but valid json to be echo'd/displayed

Displaying errors when uploading files PHP

im making a user profile edit page and i have added a profile pic upload option but it does not show error message when file size is above limit
if(isset($_POST["submits"]))
{
$target_dir = "uploads/";
$target_maxsize=2000000;
if(!($_FILES['fileToUpload']['name']==""))
{
$target_file = $target_dir.basename($_FILES['fileToUpload']['name']);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg")
{
$_SESSION['uperr']="Please select an image file (.jpg, .jpeg & .png)";
header('Location: http://localhost/VULCAN/dashboard.php?q=setting');
}
else
{
if($_FILES['fileToUpload']['size'] < $target_maxsize)
{
if(file_exists($target_file))
{
$_SESSION['uperr']="File Already Exists!";
header('Location: http://localhost/VULCAN/dashboard.php?q=setting');
}
else
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file))
{
$_SESSION['uperr']="File has been uploaded successfully!";
header('Location: http://localhost/VULCAN/dashboard.php?q=setting');
}
else
{
$_SESSION['uperr']="File could not be uploaded!";
header('Location: http://localhost/VULCAN/dashboard.php?q=setting');
}
}
}
else
{
$_SESSION['uperr']="File is too large!";
header('Location: http://localhost/VULCAN/dashboard.php?q=setting');
}
}
}
else
{
$_SESSION['uperr']="Please select a file first!";
header('Location: http://localhost/VULCAN/dashboard.php?q=setting');
}
}
this is what i use for displaying error message if any
<body>
<?php
if(isset($_SESSION['uperr'])/*$sesfilerr!=""*/)
{
?><script>
$( document ).ready(function() {
alert("<?php echo $_SESSION['uperr']; ?>");
});
</script><?php
unset($_SESSION['uperr']);
}
?>
</body>
help anybody?
also when i refresh the page the error message is displayed again. anything to prevent this?
Please try this below code
if(isset($_SESSION['uperr']))
{
?><script>
$( document ).ready(function() {
alert("<?php echo $_SESSION['uperr']; ?>");
});
</script><?php
unset($_SESSION['uperr']);
$_SESSION['sett']=1;
}
?>

PHP - Auto-submit forms in PHP using onchange

I am trying to create a form where when the user chooses a file, the file chosen will automatically upload to the database by going to the action in form. I used the onchange function and it just sends me to my php file in which that file contains my uploading system. What i think my problem is about my $_POST['asdasd'], but i cant really think of any other solutions to this.
Here is my form:
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
</form>
The PHP File:
if (isset($_POST['submit'])) {
$target_dir = "../users/".$_SESSION['u_id']."/image/";
$str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$rand = substr(str_shuffle($str), 0, 10);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($temp);
$target_file = $target_dir . $newfilename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ". <br/>";
$uploadOk = 1;
} else {
echo "File is not an image. <br/>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. <br/>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
echo "Sorry, your file is too large. <br/>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. <br/>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. <br/>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
require 'database_inc.php';
$sql = "UPDATE `users` SET `user_profile` = '$newfilename' WHERE 1";
if (mysqli_query($conn,$sql)) {
$_SESSION['profile_picture'] = $newfilename;
header("Location: ../profile.php");
} else {
echo "The query has not been updated. <br/>";
}
} else {
echo "Sorry, there was an error uploading your file. <br/>";
}
}
}
It is not saving because in the php file you have the line
if (isset($_POST['submit'])) {
add in the form a hidden field
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
<input type="hidden" name="submited" value="1" />
</form>
And in php change the line
if (isset($_POST['submit'])) {
to
if (isset($_POST['submited'])) {
That should do it
Instead of doing the $_POST['submit'] validation, try to check if the request is a $_POST.
To do that you can use something like
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }
or
if ($_SERVER['REQUEST_METHOD'] === 'POST') {…}
i recommend you to use the first one.
PHP doc: http://php.net/manual/pt_BR/function.filter-input.php

Delete file from a directory with php NO DATABASE

I am stuck on my codes from 2 days now. I have already tried more then 100 tutorials/guide but none of them solve my problem. Mostly guide is for database.
I am using ready made gallery plugin to display images on my website. This gallery does not use database. For that I made admin panel with upload function. Now i am looking for function to delete uploaded photos from admin panel. one pic at a time or multiple option will be more then good.
Right now with this code i am displaying images in Admin Page at main.php which i uploaded before:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,gif,png,bmp}", GLOB_BRACE);
$folder = opendir($folder_path);
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="250" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
And i am trying this delete code in delete.php
<?php
$filename = $_POST['fname'];
$path = $_POST['directory'];
if(file_exists($path."/".$filename)) {
unlink($path."/".$filename); //delete file
}
?>
So i need a function to delete file from server with confirmation and with delete button. Right now file just open with a click. This function will be only for admin, So i think i am safe with delete function as i read in similar topics.
Thanks in Advance.
EDIT 1:
So far this code successfully delete a file from server (Answer from #Jocelyn):
<h3>Delete Now!</h3>
<?php
if(isset($_GET['delete']))
{
unlink(__FILE__);
}
?>
Change this unlink(__FILE__); to unlink("$file_path");
EDIT 2:
Sorry, it does delete file from server but its deleting all the files in that directory.
Is there anyway to delete only one file which i click.
Right now all photos appearing from one link of code, i think thats the problem.
The link is this from which photos are appearing:
<img src="<?php echo $file_path; ?>" height="250" />
A very quickly cobbled together example of how you might achieve your goal using ajax to send the filename to the delete.php script. No doubt that because it's not tested there may well be issues - but it's a starting point.
<?php
/* delete.php */
$img=!empty( $_GET['name'] ) ? $_GET['name'] : false;
$result=false;
if( $img ){
/*
here you would typically check that the path sent via ajax exists
and then use unlink to delete the file before sending a response
to the ajax callback function - the callback would then inform the
user that the file has been deleted ( or not! )
For testing though a simple message will suffice so that files are not deleted unnecessarily!!!
-- uncomment the line below to actually attempt deletion of file.
*/
if( file_exists( $img ) ){
#$result = #unlink( $img );
clearstatcache();
}
echo $result ? 'The file '.$img.' was deleted' : 'The file '.$img.' could not be deleted';
}
?>
<?php
$root='c:/wwwroot';
?>
<!-- /* admin page that lists images */ -->
<html>
<head>
<title>Delete images - no database</title>
<script>
function ajax(imagename,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.status==200 && xhr.readyState==4 ){
callback.call( this, xhr.response );
}
};
xhr.open( 'GET', 'delete.php?name='+imagename, true );
xhr.send();
}
function deleteimage(e){
e.preventDefault();
ajax.call( this, e.target.dataset.path+'/'+e.target.dataset.name, cbdeleteimage );
}
function cbdeleteimage(r){
alert( r );
}
function bindEvents(){
var col=document.querySelectorAll('img.delete');
for( var n in col )if( col[ n ].nodeType==1 ) col[n].addEventListener( 'click', deleteimage, false );
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<?php
$dir = 'gallery-images/'; /* YOUR path */
$dir = $root . '/images/misc/'; /* MY test path */
$files=preg_grep( '#(\.jpg|\.jpeg|\.png|\.bmp|\.gif)#i', glob( $dir . '*.*' ) );
$html=array();
foreach( $files as $file ){
if( $blocal ) $file=str_replace( $root, '', $file ); /* remove MY site root from file names */
$name = pathinfo( $file, PATHINFO_BASENAME );
$path = pathinfo( $file, PATHINFO_DIRNAME );
$html[]="<img class='delete' src='{$file}' data-name='{$name}' data-path='{$path}' />";
}
echo implode( PHP_EOL, $html );
?>
</body>
</html>
So this is the final code which is perfectly fine for noobs like me who stuck with their work:
this is Delete.php to delete only a requested file
<?php
$file = $_GET['delete'];
if(isset($_GET['delete']))
{
unlink("./gallery-images/$file");
header("Location:home.php");
}
?>
This is upload.php to upload file with rename to auto increment value:
<?php
// Upload and Rename File
if (isset($_POST['submit']))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.png','.jpg','.jpeg');
$count = count (glob ('gallery-images/*'));
if (in_array($file_ext,$allowed_file_types) && ($filesize < 10000000))
{
// Rename file
$newfilename = ($count + 1) . $file_ext;
if(file_exists("gallery-images/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "gallery-images/" . $newfilename);
header("Location: home.php");
exit;
}
}
elseif (empty($file_basename))
{
// file selection error
echo "Please select a file to upload.";
}
elseif ($filesize > 10000000)
{
// file size error
echo "The file you are trying to upload is too large.";
}
else
{
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
unlink($_FILES["file"]["tmp_name"]);
}
}
?>
This is home.php to display image with delete feature:
Upload Form:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload: <br />
<input type="file" name="file" id="file"><br /><br />
<input type="submit" value="Upload Image" name="submit">
</form>
Display photos from directory:
<?php
$folder_path = 'gallery-images/'; //image's folder path
$num_files = glob($folder_path . "*.{jpeg,jpg,png}", GLOB_BRACE);
$folder = opendir($folder_path);
$file = '$file_path';
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'jpeg' || $extension == 'bmp')
{
?>
<img src="<?php echo $file_path; ?>" height="175" />
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
?>
Delete confirmation popup script:
<script>
function deleletconfig(){
var del=confirm("Are you sure you want to delete this record?");
if (del==true){
}
return del;
}
</script>
Hope this will be helpful for learners.
Thanks.

Image upload with ajax and php is failing (no error log)

The following code I'm using to upload images is failing for some reason...
Here is the HTML
<form id="image_upload" enctype="multipart/form-data" action="uploadImage.php" method="post" name="prof_picture">
<input id="image1" style="display:none;" name="image" accept="image/jpeg" type="file">
<input id="image2" value="Submit" type="submit" style="display:none;">
</form>
PHP (uploadImage.php)
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name'][0]);
echo $filename;
$size=filesize($_FILES['image']['tmp_name'][0]);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'][0], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}
JS
$('#image1').on('change', function() {
$("#image").attr('src',"profile/loading.gif");
$("#image_upload").ajaxForm({
target: '#image'
}).submit();
});
What I know for sure:
1º The php script is being achieved correctly because I failed part of the code on purpose and attained an error message regarding an internal php error.
2º The query is being done correctly (or at least by its syntax).
3º The javascript function related to #image is also working.
I only want to upload one image that the user selects (even if he selects 100 other items). But as I said, I don't even get an error message on the log... Any ideas on this one? Thank you very much!
EDIT
I've changed the code a bit
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)){
if ($size < (MAX_SIZE*1024)){
$image_name=time().$user_id."--pfi-".$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)){
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}else echo '<span class="imgList">This message appears </span>';
}else echo '<span class="imgList">You have exceeded the size limit!</span>';
}else echo '<span class="imgList">Unknown extension!</span>';
For some reason it now stops at if(move_uploaded_file($_FILES['image']['tmp_name'], $newname)). I've var_dump'ed this and it is indeed "false" but I can't get to understand why. Here is var_dump($_FILES):
array(1) { ["image"]=> array(5) { ["name"]=> string(21) "060424_hubble_big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpZYaDkm" ["error"]=> int(0) ["size"]=> int(35641) } }
EDIT 2
Warning:
move_uploaded_file(profile/uploads/1388794617.png):
failed to open stream: No such file or directory in
profile/uploadProfilePicture.php on line 37
Warning: move_uploaded_file(): Unable to move '/tmp/phppFfoL4' to
'profile/uploads/1388794617.png' in
profile/uploadProfilePicture.php on line 37
how should I specify $uploaddir or even $newname?
Edit
This is what I used. Notice the commented out conditional statements.
<?php
// include('../sqlconnection.php');
define ("MAX_SIZE","1000000000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
// {
$uploaddir = "profile/uploads/"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
// mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
// }
Original answer
Ok, I found the problem. Remove all [0] in your PHP and it will now work. Those are used for arrays and since you're only using it for single file uploads, is why it failed.
Sidenote: You may want to add a / at the end of $uploaddir = "profile/uploads"; as in $uploaddir = "profile/uploads/";
The following doesn't have the [0]'s and have tested it as pure PHP with no JS.
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}

Categories

Resources