I need to upload an image and add it to my slideshow and give it related newsTitle in front of my uploaded picture. I'm a new in PHP and trying to learn how to send data from my admin.php file to my index.php file and add more image with a <form> in html.
My problem is that I can upload images but can't get my newsTitle printed to my home page which is index.php.
This is my PHP code in index.php:
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
$newsImage = $_POST['newsImage'];
echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
echo'<h2'.'>'.htmlspecialchars($newsImage["newsImage"]).'</h2>';
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
This is my html code in admin.php:
<form action="index.php" method="post" enctype="multipart/form-data">
<br><br>
<tr>
<td> NewsTitle: </td>
<td> <input type="text" name="newsTitle" placeholder="newsTitle"> </td>
</tr>
<br><br>
Select image to upload:
<input type="file" name="image">
<br><br>
<br><br>
NewsText: <textarea name="newsImage" placeholder="newsImage" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" value="Send" name="send_object">
</form>
I'm trying to do this without connection to the database, just to my apache server. I have tried with another global variable $_REQUEST but it didn't work. What I know it can use for $_POST , $_GET and $_COOKIES
Firstly, if you are trying to make each news with a text you collect it separately with the $_POST , but note once you refresh the page the parameters are gone cause the form processes everything so there is no space for output in text but if you use the get the parameters remain because you are not storing both the post method and get method in the database. Try this
<?php
if (isset($_POST['send_object'])) {
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_tmp_name = $_FILES['image']['tmp_name'];
//$newsTitle = $_POST['newsTitle'];
if (move_uploaded_file($file_tmp_name,"uploader/$file_name")) {
}
}
$folder = "uploader/";
if (is_dir($folder)) {
if($handle = opendir($folder)) {
while (($file = readdir($handle)) != false) {
if ($file ==='.' || $file=== '..') continue;
echo '<img class="slider mySlides" width="100" src="uploader/'.$file.'" alt="">';
}
closedir($handle);
}
}
?>
<?php
$newsImage = $_POST['newsImage'];
//this would give a parse error echo '<h2><?php echo 'htmlspecialchars($_POST['newsImage']);'';
try
echo <?php echo $newsimage; ?>
?>
Related
I added the images with image upload page and show the image and thumbnail images in another web page. I used the resize name with time() function. And I want this: I want each image I add to appear on the html page in order, according to the names I have just given. However, as I add the photos with the code I wrote, the order in my html page is distorted, but I always want it to continue in the order I added. How can I show the pictures I renamed with the Time() function in order on my html page?
home.php
<div class ="gallery-items">
<?php
$image_extensions = array("png","jpg","jpeg","gif");
$dir = 'image/';
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
$thumbnail_path = "image/thumbnailkamu/".$file;
$image_path = "image/".$file;
$thumbnail_ext = pathinfo($thumbnail_path, PATHINFO_EXTENSION);
$image_ext = pathinfo($image_path, PATHINFO_EXTENSION);
if (array_key_exists('delete_file', $_POST)) {
$filen = $_POST['delete_file'];
if (file_exists("image/".$filen)){
unlink("image/".$filen);
unlink("image/thumbnailkamu/".$filen);
}
}
if(!is_dir($image_path) &&
in_array($thumbnail_ext,$image_extensions) &&
in_array($image_ext,$image_extensions)){
?>
<div class ="item">
<a href="<?= $image_path; ?>" data-lightbox="mygallery">
<img src="<?= $thumbnail_path; ?>">
</a>
<a class="btn btn-primary" href="<?= $image_path; ?>" download>Download</a>
<form action = "" method="post">
<input type="hidden" value="<?= $file; ?>" name="delete_file" />
<input class = "button" type="submit" value="Delete" />
</form>
</div>
<?php
}
}
}
}
closedir($dh);
}
?>
</div>
Since you're having trouble following the other S.O. answer, try this. First stick the files in an array with the filemtime as the key, then use ksort to sort it before you start iterating
<div class="gallery-items">
<?php
$image_extensions = array("png", "jpg", "jpeg", "gif");
$dir = 'image/';
if (is_dir($dir)) {
$thefiles = [];
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file != "" && $file != "." && $file != "..") {
$thefiles[filemtime('image/' . $file)] = $file;
}
}
closedir($dh);
}
// sort the by most recent at the top
ksort($thefiles);
// now loop through
foreach ($thefiles as $file) {
$thumbnail_path = "image/thumbnailkamu/" . $file;
$image_path = "image/" . $file;
$thumbnail_ext = pathinfo($thumbnail_path, PATHINFO_EXTENSION);
$image_ext = pathinfo($image_path, PATHINFO_EXTENSION);
if (array_key_exists('delete_file', $_POST)) {
$filen = $_POST['delete_file'];
if (file_exists("image/" . $filen)) {
unlink("image/" . $filen);
unlink("image/thumbnailkamu/" . $filen);
}
}
if (!is_dir($image_path) &&
in_array($thumbnail_ext, $image_extensions) &&
in_array($image_ext, $image_extensions)) {
?>
<div class="item">
<a href="<?=$image_path;?>" data-lightbox="mygallery">
<img src="<?=$thumbnail_path;?>">
</a>
<a class="btn btn-primary" href="<?=$image_path;?>" download>Download</a>
<form action="" method="post">
<input type="hidden" value="<?=$file;?>" name="delete_file" />
<input class="button" type="submit" value="Delete" />
</form>
</div>
<?php
}
}
}
?>
</div>
i have a script which loads all files within a specific directory folder into a viewable table. I have also been able to successfully get the date uploaded element integrated and am using the $iterator function as seen in the code below
UPDATE
edited value to checkbox input but still not working
Removed unnecessary code snippets from past attempts
Updated code to most recent and added full script for better understanding including CD001's suggestions
// Begin Adding Uploader Page Content
function pdfupload_admin_page(){
?>
<style>
<?php include '../wp-content/plugins/PDF-Uploader/support-files/stylesheet.css'; ?>
</style>
<div class="wrap">
<div id="contact">
<div style="text-align:center;">
<h1>Secure PDF File Upload</h1>
<p>Adding a watermark to your PDF files is as easy as uploading the file using the form below.<br>
Upon successful submission of your PDF file you will receive the uploaded PDF files URL which you can then use when linking to the PDF within any page or post you desire.</p>
<p>The PDF file when linked to using the URL provided will automatically acquire a watermark when loaded within the browser of the specific logged in user as well as the current date and time.</p>
<form action="" method="post" enctype="multipart/form-data">
<h3>Select PDF File To Upload:</h3><br>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload PDF File" name="submitUpload">
</form>
<?php
$target_dir = "../wp-content/plugins/PDF-Uploader/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submitUpload"])) {
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
// if ($_FILES["fileToUpload"]["size"] > 10000000) {
// echo "Sorry, your file is too large.";
// $uploadOk = 0;
// }
// Allow certain file formats
if($FileType != "pdf") {
echo "Sorry, only PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "File uploaded successfully use the following URL when linking to your PDF <br> https://website.com/wp-content/plugins/PDF-Uploader/watermarked.php?filename=" . basename( $_FILES["fileToUpload"]["name"]). "";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
// Check if file already exists
/**
* FILE DELETION HANDLER
*/
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
function delete_file($iterator, $file) {
if(!unlink($iterator->getPath() . '/' . $file)) {
echo "Sorry! your file cannot be deleted. Please try again later";
}
else {
echo "File deleted successfully!";
}
}
if(isset($_POST['submit'])){
if(!empty($_POST['file'])) { // check if the checkbox was checked.
foreach($_POST['file'] as $file) {
// call delete function here.
delete_file($iterator, $file);
}
}
else{
echo "No file selected. You must select at least one PDF file to be deleted.";
}
}
?>
</div>
<?php
// if ($handle = opendir('../wp-content/plugins/PDF-Uploader/')) {
// while (false !== ($file = readdir($handle)))
// {
// if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
// {
// $thelist .= '<td><input type="checkbox" name="file[]" value="https://website.com/wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
// }
// }
// closedir($handle);
//}
?>
<form id="deletionForm" method="post" action="">
<table>
<thead>
<tr style="width:100%;">
<th style="width:25px;"></th>
<th style="text-align:left;width:625px;">Filename</th>
<th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
</tr>
</thead>
<?php
// $iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/pdf-watermarker/');
foreach($iterator as $file){
//if($file->isFile()){
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
//echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
?>
<tr>
<td style="width:25px;"><input type="checkbox" name="file[]" value="wp-content/plugins/PDF-Uploader/<?php echo $file->getFileName(); ?>"></td>
<td style="text-align:left;width:625px;"><?php echo $file->getFileName(); ?></td>
<td style="text-align:right;width:100px;padding-right:20px;"><?php echo $cTime->format('Y-m-d h:i:s'); ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>
</div>
<?php
}
// End Adding Secure PDF Upload Page Content
So all in a nutshell, I need to figure out why the delete functionis not working and add a sort order to the script to product the results in alphabetical order.
Any code samples would be greatly appreciated.
File handling require a valid enctype in <form>, being enctype="multipart/form-data" as per the manual:
https://secure.php.net/manual/en/features.file-upload.post-method.php
An example from the manual:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
You need to change all references of $_POST['file'] to $_FILES['file']['name'] / $_FILES['file']['tmp_name'] respectively.
Handling multiple files is also included in the manual, and here is an example pulled from it:
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Use PHP's error reporting to help you debug:
https://php.net/manual/en/function.error-reporting.php
However, when dealing with checkboxes, don't use empty(), use isset():
if(isset($_POST['file'])) { // check if the checkbox was checked.
It's a bit unclear if you want to upload files. If so, then you need to change the <input type="checkbox" to an file input type <input type="file"
Edit:
This part of your code should error out, since there needs to be an empty variable declaration using $thelist = "";
I.e.:
<?php
if ($handle = opendir('../wp-content/plugins/PDF-Uploader/.')) {
$thelist = "";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$thelist .= '<td><input type="checkbox" name="file[]" value="../wp-content/plugins/PDF-Uploader/'.$file.'"></td>';
}
}
closedir($handle);
}
?>
Solution (explanation follows)
<?php
// global iterator
$iterator = new FilesystemIterator('../wp-content/plugins/PDF-Uploader/');
function delete_file($iterator, $file) {
if(!unlink($iterator->getPath() . '/' . $file)) {
echo "Sorry! your file cannot be deleted. Please try again later";
}
else {
echo "File deleted successfully!";
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
</head>
<body>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['file'])) { // check if the checkbox was checked.
foreach($_POST['file'] as $file) {
// call delete function here.
delete_file($iterator, $file);
}
}
else{
echo "No file selected. You must select at least one PDF file to be deleted.";
}
}
?>
<form method="post" action="">
<table>
<thead>
<tr style="width:100%;">
<th style="width:25px;"></th>
<th style="text-align:left;width:625px;">Filename</th>
<th style="text-align:right;width:100px;padding-right:20px;">Date Uploaded</th>
</tr>
</thead>
<?php
foreach($iterator as $file) {
//if($file->isFile()){
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
{
$cTime = new DateTime();
$cTime->setTimestamp($file->getCTime());
//echo $file->getFileName() . " file Created " . $cTime->format('Y-m-d h:i:s') . "<br/>\n";
?>
<tr>
<td style="width:25px;"><input type="checkbox" name="file[]" value="<?= $file->getFileName(); ?>"></td>
<td style="text-align:left;width:625px;"><?= $file->getFileName(); ?></td>
<td style="text-align:right;width:100px;padding-right:20px;"><input type="text" name="date[]" value="<?= $cTime->format('Y-m-d h:i:s'); ?>"></td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="Delete Selection">
</form>
</body>
</html>
Explanation
Since the FilesystemIterator holds the path to the directory for your PDF repository I've defined that as a global variable at the top of the script. It's then referenced wherever required so should you ever need to change the filepath, you just change it in the $iterator.
For instance, it's used in the loop and passed to the delete_file function. The form itself is only posting the filenames rather than the full paths.
Otherwise you weren't really a long way off.
Couple of thoughts
The FilesystemIterator class has methods for detecting the extension and whether the file is . or .. so you can replace:
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'pdf')
With:
if(!$file->isDot() && $file->getExtension() == 'pdf')
Which is a little neater.
There is also a security concern with having a directory that's both web server readable and writeable - if there's a vulnerability in your application an unauthorised user could upload and execute anything (open it in the browser); a malicious PHP script for instance.
You can mitigate this through your Apache configuration - one common thing to do is to disable PHP via an .htaccess file:
php_flag engine off
have an upload script where I can delete an image I have to write manually its name in an input box in a form.I read the images' names directly from a folder in my server. I'd like to copy the name of the image that I want to delete by clicking on the image or on its name for each image that I want to delete. It's not easy to explain it, I will show you the code:
EDIT2: It'working:
<?php
if ( $_SERVER["REQUEST_METHOD"] == 'GET' ) {
if (isset($_GET['name']) && $_GET['name'] != '') {
$img_file = $_GET['name'];
if($img_file){
unlink("img/$img_file");
header('Location: index.php');
}
}
}
?>
<?php
if(isset($_POST['upload_img'])){
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$file_tmp_name = $_FILES['image']['tmp_name'];
if($file_name){
move_uploaded_file($file_tmp_name,"img/$file_name");
}
}
?>
<body>
<form action="" method="post" enctype="multipart/form-data">
<label>upload image </label><br>
<input type="file" name="image"><br>
<input type="submit" value="Upload Image" name="upload_img">
</form>
<?php
$folder = "img/";
if(is_dir($folder)){
if($handle = opendir($folder)){
while(($file=readdir($handle)) != false){
if($file==='.' || $file==='..') continue;
echo '<a href="index.php?name='.$file.'">';
echo '<img src="img/'.$file.'" width="150" height="150" alt="">';
echo '</a>';
}
closedir($handle);
}
}
echo '<br>'.$file_names;
?>
</body>
You need to wrap your img tag in an anchor tag like so
Assuming your current script is called mypics.php you could do this.
echo '<a href="mypics.php?name="' . $file . '">';
echo '<img src="img/'.$file.'" width="150" height="150" alt="">';
echo '</a>';
Now at the top of your current script you add
<?php
// picture clicks will be returned as GET requests
if ( $_SERVER["REQUEST_METHOD"] == 'GET' ) {
if (isset($_GET['name']) && $_GET['name'] != '') {
// do any sanity checks that you are only
// deleting a sensible file name etc
// delete the file
}
// your existing script follows, which should re-paint the page
// without the deleted image
You can now delete the code you were using for entering the name and processing the delete that way
You can put the img tag inside a tag, with a link to a script that deletes the file, something like:
echo <<< EOF
<img src="img/$file" width="150" height="150" alt="">
EOF;
Then create a file called, deleteFile.php
if(isset($_GET['fileToDelete')){
//NOTE: Make SURE you filter and restrict the content of $_GET['fileToDelete'), or may get all the files removed...
//remove the file here
}
I have a script that deletes images from a folder using PHP.
The problem is the images arenot being displayed on the page.
My code is as below
<?php
// directory separator
defined("DS")
|| define("DS", DIRECTORY_SEPARATOR);
// root path
defined("ROOT_PATH")
|| define("ROOT_PATH", realpath(dirname(__FILE__)));
// upload folder directory
defined("UPLOAD_DIR")
|| define("UPLOAD_DIR", "uploads");
// path to the upload folder
defined("UPLOAD_PATH")
|| define("UPLOAD_PATH", ROOT_PATH.DS.UPLOAD_DIR);
function getAllFiles($folder = null) {
if(!empty($folder) && is_dir($folder)) {
if($handle = opendir($folder)) {
$out = array();
while($file = readdir($handle)) {
if(is_file($folder.DS.$file)) {
$out[] = $file;
}
}
closedir($handle);
return $out;
}
return false;
}
return false;
}
$files = getAllFiles(UPLOAD_PATH);
if (!empty($_POST['file'])) {
foreach($_POST['file'] as $file) {
unlink(UPLOAD_PATH.DS.$file) or die("Failed to <strong class='highlight'>delete</strong> file");
}
header("location: " . $_SERVER['REQUEST_URI']);
}
?>
<?php if (!empty($files)) { ?>
<form name="form1" method="post">
<?php foreach($files as $key => $file) { ?>
<label for="file_<?php echo $key; ?>">
<input type="checkbox" name="file[]" id="file_<?php echo $key; ?>" value="<?php echo $file; ?>" />
<?php echo $file; ?>
</label>
<?php } ?>
<input type="submit" name="delete" value="Delete" />
</form>
The code works fine to delete the images but does not display the images on the page.
Your help is much apprecited.
Thank You
I think the images are still in the browser cache, so deleting the cache will result in not seeing any deleted images.
i have this page for upload:
<?php
require ('incs/db.php');
require_once ('incs/funcs.php');
?>
<?php
if (array_key_exists('upload', $_POST)) {
$directory = str_replace(basename($_SERVER['PHP_SELF']),'',$_SERVER['PHP_SELF']);
$uploadHandler = $_SERVER['DOCUMENT_ROOT']. $directory . 'images/';
// $uploadHandler = "echtitipi".$_SERVER['HTTP_HOST']. '/images/';
$max_file_size = 30000;
define('UPLOAD_DIR', $uploadHandler);
$ext= end(explode(".", $_FILES['image']['name']));
$name = rand(1111111,9999999).'.'.$ext;
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadHandler. $name))
{
$upload = true;
$title = $_POST ['title'];
$sql = "INSERT INTO photo (id, keyword, photoName)
VALUES ('','$title','$name')
";
$result = mysql_query ( $sql, $con );
}
else
{
$upload = false;
$msg = 'Cant Upload!';
}
}
?>
<?php
include ('incs/header.php');
?>
<?php
getUrlQuery();
?>
<script language="javascript">
<!--
function pick(symbol, path) {
if (window.opener && !window.opener.closed)
window.opener.document.form.img.value = symbol;
window.opener.document.form.imgbox.src = path;
window.close();
}
// -->
</script>
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">
Tanım:
</label>
<input type="text" name="title" id="title" />
<label for="image">
Upload image:
</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<?php
if($upload == true)
{
echo "<a hrf(because spam!)=\"javascript:pick('$name','images/$name')\"><im(g) src=\"images/$name\" border=\"0\" alt=\"use\"></a>";
}
?>
<?php
include ('incs/footer.php');
?>
`
this upload image to curretnt root's images folder. My current folder is admin:
root/admin/images
root/images
when i use
$uploadHandler = "http://".$_SERVER['HTTP_HOST']. '/images/';
script doesnot work.
<?php
if($upload == true)
{
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
}
?>
the image couldnot add to editor. I guess There is a problem with javascript.
what is wrong in script
echo "<a hrf=\"javascriptick('$name','{$uploadHandler}$name')\"><im(g) src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\"></a>";
change into
echo "<img src=\"{$uploadHandler}$name\" border=\"0\" alt=\"use\">";
I guess this will help...
Im sorry for bad dictation because i cant write the right script because sending errors(link and images)
above code uploaded code to
/www/admin/images
and save information to database and add image to tinymce editor. But I want to upload code to:
www/images
when I use :
$uploadHandler = $_SERVER['DOCUMENT_ROOT'].'/images/';
and
"<img src=\"images/$name\" border=\"0\" alt=\"use\">"
the image couldnot add to editor. This is my problem.