Essentially, the following code works fine except for the 'unlink' sections. The record is located and deleted in the database, but the file in the server directory remains untouched.
I know that 'pageLocation' is accurate because I've used it to load files.
<?php
session_start();
if(isset($_POST['btnSubmitEdit']))
{
$allowed_filetypes = array('.jpg','.jpeg','.png');
$max_filesize = 10485760;
$setComic = $_SESSION['comicID'];
$setPage = $_SESSION['currentPage'];
$upload_path = 'comics/'.$setComic.'/';
$filename = $_FILES['fileToEdit']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
if(filesize($_FILES['fileToEdit']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
include_once('includes/conn.inc.php');
$query1 = ("SELECT pageLocation FROM page WHERE pageID = '$setPage'");
$result1 = mysqli_query($conn, $query1);
while ($row = $result1->fetch_assoc())
{
unlink('/"'.$row['pageLocation'].'"');
}
if(move_uploaded_file($_FILES['fileToEdit']['tmp_name'],$upload_path . $filename))
{
mysqli_query($conn, "UPDATE page SET pageLocation='".$upload_path . $filename."' WHERE pageID=".$setPage."");
mysqli_close($conn);
}
else
{
echo 'There was an error during the file upload. Please try again.';
}
header('Location: uploadPage.php');
}
if(isset($_POST['btnSubmitDelete']))
{
$setPage = $_SESSION['currentPage'];
include_once('includes/conn.inc.php');
$query2 = ("SELECT pageLocation FROM page WHERE pageID = '$setPage'");
$result2 = mysqli_query($conn, $query2);
while ($row = $result2->fetch_assoc())
{
unlink('/"'.$row['pageLocation'].'"');
mysqli_query($conn, "DELETE FROM page WHERE pageID = '$setPage'");
}
header('Location: uploadPage.php');
}
?>
Related
I am working with php on my localhost server. I want to unlink the image from my server folder whenever I change the image when edit. The picture is changing when I update but the past picture stays in folder.
if (isset($_POST['update'])) {
$image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if (!empty($image)) {
$del_is = $_GET['deleteUser'];
$sql = "SELECT * FROM users WHERE id = '$del_is'";
$del_user = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($del_user)) {
$user_image = $row['image'];
}
unlink("dist/img/users/$user_image");
}
I want to change the uploaded image filename to a certain name for example:
Original name:city.jpg -> D0000_04042018094730121.jpg (D0000 is kodeDosen and the other is a microtime timestamp.)Here is my php code:uploadDosen.php
<?php
include 'connectdb.php';
if (isset($_POST['upload_Btn'])) {
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
$kodeDosen = $_POST['kodeDosen'];
$namaJurnal = $_POST['namaJurnal'];
$tipePublikasi = $_POST['tipePublikasi'];
$status= $_POST['status'];
$gambar = $_FILES['gambar']['name'];
$sql = "INSERT INTO tbl_publikasi (kodeDosen,gambar,namaJurnal,tipePublikasi,status) VALUES ('$kodeDosen','$gambar','$namaJurnal',
'$tipePublikasi','$status')";
// execute query
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['gambar']['tmp_name'],$target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
header("location:uploadTest.php");
}
?>
Instead of using
$target = "uploaddosen/".basename($_FILES['gambar']['name']);
Put your desired name in
$ext = end((explode(".", $_FILES['gambar']['name'])));
$target = "uploaddosen/MYNEWNAME." . $ext
$ext is taking the uploaded file name and getting the file extension. Then adding it together with your new name.
Just change the value of $target to your preferred filename.
You can try:
$extention = explode(".", $_FILES['gambar']['name']);
$extention = end($extention);
$target = $kodeDosen."_".str_replace(array(".", " "), "", microtime() ).".".$extention;
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've run into a conundrum and was wondering if anyone might be able to give me a straight answer. So I built a photo upload script using PHP/MySQL. Within the script photos are re-sized and given a temporary name while being uploaded. I tested it using several pictures (file size 220 KB | 960 x 720) and everything was working just fine. Then I attempted to upload several pictures from my digital camera (file size 2.47 MB | 3000 x 4000) and all of a sudden I got this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /php_parsers/photo_system.php on line 94
Warning: Cannot modify header information - headers already sent by (output started at /php_parsers/photo_system.php:94) in /php_parsers/photo_system.php on line 96
I checked stackoverflow for a post with a similar issue and came upon one however it didn't seem to apply to the scenario I'm experiencing.
Here is the applicable code for "photo_system.php". I have commented the offending lines 94 and 96. Any help/ideas you could give would be greatly appreciated!
<?php
if (isset($_FILES["photo"]["name"]) && isset($_POST["gallery"])){
$sql = "SELECT COUNT(id) FROM photos WHERE user='$log_username'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] > 79){
header("location: ../message.php?msg=The system allows only 80 pictures total");
exit();
}
$gallery = preg_replace('#[^a-z 0-9,]#i', '', $_POST["gallery"]);
$fileName = $_FILES["photo"]["name"];
$fileTmpLoc = $_FILES["photo"]["tmp_name"];
$fileType = $_FILES["photo"]["type"];
$fileSize = $_FILES["photo"]["size"];
$fileErrorMsg = $_FILES["photo"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = date("DMjGisY")."".rand(1000,9999).".".$fileExt; // WedFeb272120452013RAND.jpg
list($width, $height) = getimagesize($fileTmpLoc); //Offending Line 94
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions"); //Offending Line 96
exit();
}
if($fileSize > 4194304) {
header("location: ../message.php?msg=ERROR: Your image file was larger than 4mb");
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();
}
$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");
$wmax = 800;
$hmax = 600;
if($width > $wmax || $height > $hmax){
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
}
$sql = "INSERT INTO photos(user, gallery, filename, uploaddate) VALUES ('$log_username','$gallery','$db_file_name',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../photos.php?u=$log_username");
exit();
}
?><?php
if (isset($_POST["delete"]) && $_POST["id"] != ""){
$id = preg_replace('#[^0-9]#', '', $_POST["id"]);
$query = mysqli_query($db_conx, "SELECT user, filename FROM photos WHERE id='$id' LIMIT 1");
$row = mysqli_fetch_row($query);
$user = $row[0];
$filename = $row[1];
if($user == $log_username){
$picurl = "../user/$log_username/$filename";
if (file_exists($picurl)) {
unlink($picurl);
$sql = "DELETE FROM photos WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
mysqli_close($db_conx);
echo "deleted_ok";
exit();
}
?>
OK everyone. I figured out what the issue was. Hopefully this will help someone in the future. So I checked my phpinfo() and found that upload_max_filesize was only set to 2M. I added php.ini to the directory of the offending file and included:
upload_max_filesize = 250M
post_max_size = 250M
max_execution_time = 300
date.timezone = "America/Los_Angeles"
I had to add the date.timezone because my system didn't like the fact that I didn't have it defined. Anyway this has resolved the issue.
<?php
error_reporting(E_ALL);
include "func.php";
connectToDatabase("localhost","root","","test");
$fileName = $_FILES['name'];
$fileSize = $_FILES['size'];
$fileType = $_FILES['type'];
$fileTempName = $_FILES['temp_name'];
$uploaderID = $_SESSION['id'];
$date = date("d/m-Y");
$uploadDir = "avatarStor/";
$filePath = $uploadDir . $fileName;
if(!$fileName){
echo "Error: value 'fileName' was undefined<br>";
}
$result = move_uploaded_file($fileTempName, $filePath);
if (!$result) {
echo "Error: File could not be uploadet: ".$fileName;
exit;
}
if(!get_magic_quotes_gpc()){
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$result = mysql_query("UPDATE users SET profilepicture='$fileName' WHERE id='$uploaderID'") or die(mysql_error());
?>
I am unable to move_uploaded_file(); in this uploading script. I went ahead and chmod 777 the folder, but nevertheless, it failed. PHP provides no errors when running.
Change $fileTempName = $_FILES['temp_name']; to $fileTempName = $_FILES['that_input_name']['tmp_name'];