Delete file a file on the server(not local) with CodeIgniter(3) - php

I have a view named home_view, where there are several lists, for example libri(books).The user can upload and delete the files.
This is a snippet of home_view.php
<?php
echo "<table>";
echo "<tbody>";
echo "</br>";
foreach ($libri as $row):
?>
<tr>
<td>
<div>
</br>
<img src="<?php echo base_url('Immagini/book.png'); ?>" />
<a class="pdf" data-fancybox-type="iframe" rel="group" href="<?php echo base_url($row['Url_suffix']) ?>"><?php echo $row['Nome']; ?> </a>
<a class="deleteUser" href="javascript:void(0)" rel="<?php echo site_url('libro/elimina/'.$row['ID']) ?>"><img src="<?php echo base_url('Immagini/button_close.png'); ?>"/></a>
</div>
</td>
</tr>
<?php
endforeach;
?>
libri is a table of Mysql db and have different columns, Url_suffix is a Varchar(255) column where there's the folder/filename.pdf. IN the second anchor I delete with success, the row from the DB, but not the file. I tried to do something like this
<a class="deleteUser" rel="<?php unlink($row['Url_suffix']); ?>"><img src="<?php echo base_url('Immagini/button_close.png'); ?>"/></a>
but without success. What I'm wrong?
Update:
controller libro.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Libro extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper("file");
}
public function elimina($libri_id) {
//$libri_ID = $this->libri->get_one($libri_id);
$result=$this->libri->did_delete_row($libri_id);
redirect(site_url('admin/dashboard'), 'refresh');
}
}
?>

You can't use "unlink" in that way, basically you need to process which you want to delete on your controller, with some help of a model, example:
public function delete_file($route, $file){
unlink($route . "/" . $file);
}
In a model so you can use it anywhere, the $route parameter will be the path to your directory where the file is stored, for example:
htdocs/website/static/books/user/
And the $file parameter will be the name with extension that you want to delete, like:
myfirstbook.pdf
then you will have the full route to the file and it will be deleted, you only have to call that funcion from the models in your controller where the link was given by that anchor, like
Delete file
And your controller will have something like
public function delete_file($user, $file){
$this->load->model('YourModel', 'yourmodel');
$path = FCPATH . "static/books/user/".$user;
$this->yourmodel->delete_file($path, $file);
}
And its done.
Hope it helps.

Related

PHP if database has url echo URL using hyperlinked button

I am trying to see if a file in my database exists, and if it does, show that file as a hyperlinked button. The file is a URL. I am able to get the file to show accordingly, but the button shows even if there is no hyperlink. I have been researching everywhere to find out how I can echo the button only if there is a corresponding file but have had no luck. Just can get it right. Here is what I have and appreciate the help.
<?php if (file_exists($video))?><a class="videobutton" href="<?php echo $video; ?>"></a>
So based on Your Comment that you want to hide the whole button if the file is not found so this is how to do it :
<?php
if (file_exists($video)): ?>
<a class="videobutton" href="<?php echo $video; ?>"></a>
<?php endif; ?>
OR
if (file_exists($video)){ ?>
<a class="videobutton" href="<?php echo $video; ?>"></a>
<?php } ?>
<?php if (file_exists($video)){?>
<a class="videobutton" href="<?php echo $video; ?>"></a>
<?php }
else {
///
} ?>
In my opinion you missed the "{" brackets within the if statement.

Codeigniter URI routing is not working

I am using codeigniter framework in my web development and passing the value of image id using php code such below
<a href="<?php echo base_url('account/gallery/view'); ?>?id=<?php echo $imageDetail['imageId']; ?>">
<img src="" />
</a>
and getting the value at controller with this code $imageId = $this->input->get('id');
With the get method I used, it will display the url like this :
http://my-domain-name/account/gallery/view?id=1
But I want to display the url like this :
http://my-domain-name/account/gallery/1
So what I did is setting in the router with this code but it's not working.
$route['account/gallery/(:num)'] = 'default/Gallery_controller/view/$1';
My web still able to show the template of the web if I type http://my-domain-name/account/gallery/1 but display error in the field that I fetch from database because unable to get the imageId
use Regex instead of :num in route.php
$route['account/gallery/([0-9]+)'] = 'default/Gallery_controller/view/$1';
And in your template file:
<a href="<?php echo base_url('account/gallery/'.$imageDetail['imageId']); ?>">
<img src="" />
</a>
Then you can access directly in your gallary controller in view function $id.
eg:
class Gallery extends MY_Controller {
public function view($id){
// Your Image ID = $id;
}
}
Set this url http://my-domain-name/account/gallery/1 proper in href
<a href="<?php echo site_url('account/gallery/view'.$imageDetail['imageId']); ?>">
<img src="" />
</a>
Replace
<a href="<?php echo base_url('account/gallery/view'); ?>?id=<?php echo $imageDetail['imageId']; ?>">
with
<a href="<?php echo base_url();?>account/gallery/view/<?php echo $imageDetail['imageId']; ?>">
Check your config.php
$config['enable_query_strings'] = true;
to
$config['enable_query_strings'] = false;
In this try this (:any)
$route['account/gallery/(:any)'] = 'default/gallery_controller/view/$1';
Or
$route['account/gallery/view?(:any)'] = 'default/gallery_controller/view/$1';
In the routes lower case
This code is make your url like http://domain-name/account/gallery/1
Try this:
<a href="<?php echo base_url();?>account/gallery/view/<?php echo $imageDetail['imageId'];?>">
<img src="" />
</a>

Display image from php

I'm trying to display an image in an html file. Up to now i used an url : http://placehold.it/400x300, it worked fine, now when i try to replace it with image from database it doesn't display anything. the image path is : D:/uwamp/www/project/upload/tcf_animal17.jpg i tried with different path but it doesn't work. i'm not sure where is the problem. i printed the data , this is the good path
html
<?php foreach ($data[0] as $film):?>
<div class = <?= $film['id_film'] ?> >
<div class= "col-lg-3 col-md-4 col-xs-6 thumb filmDiv" >
<a class="thumbnail " id = "filmShow" href= <?= "/project/admin/showFilm/" . $film['id_film']?>>
<p> <?= $film['title_film'] ?> </p>
<img class="img-responsive overlay" src= <?= $film['img'] ?> alt="">
</a>
<a class="" href =<?= "/project/admin/update/" . $film['id_film'] ?> >
<button name="upd" id="upd" type="button" class="btn btn-default">Update</button>
</a>
<a class="delete"name= <?= $film['id_film'] ?> >
<button id="delete" type="button" class="btn btn-default">Delete</button>
</a>
</div>
</div>
<?php endforeach; ?>
Controler :
public function GetLastFilms()
{
$films = $this->film->getFilms();
$lastFilms = $this->film ->getLastFilm();
$dict[0] = $films;
$dict[1] = $lastFilms;
return $dict;
}
public function index()
{
if(isset($_SESSION['login']))
{
$this->generateView($this->GetLastFilms());
}else
{
header('Location: /project/admin/login');
}
}
protected function generateView($data = array())
{
$classeControler = get_class($this);
$controler = str_replace("Controler", "", $classeControler);
$view = new View($this->action, $controler);
$view->generate($data);
}
View :
public function generate($data)
{
$contenu = $this->generateFile($this->viewFile, $data);
$racineWeb = Configuration::get("racineWeb", "/");
$view = $this->generateFile('View/Template/index.php',
array('title' => $this->viewTitle, 'contenu' => $contenu,
'racineWeb' => $racineWeb));
echo $view;
}
private function generateFile($viewFile, $data)
{
if (file_exists($viewFile))
{
extract($data);
ob_start();
require $viewFile;
return ob_get_clean();
}
else
{
throw new Exception("can't find '$viewFile'");
}
}
Your problem is that the path to the image in the database is stored as local path from your machine (D:/uwamp/www/project/upload/tcf_animal17.jpg), where for it to display correctly it needs to be a path relative to the root of your web server documents.
For example, if your web server document root is D:/uwamp/www, then the path of the image you need to store should be project/upload/tcf_animal17.jpg.
Of course if you can't get the image to be stored within the web root, then you always have an option to just dump the content directly, however it's really not a good idea, for performance reasons:
<?php
$mime = image_type_to_mime_type(exif_imagetype(string $image_path));
$data = "data:$mime;base64," . base64_encode(file_get_contents($image_path)); ?>
?>
<img src="<?= $data ?>">
This code is very crude and does no error checking - you'll need to add that for a production-level application.

PHP Code is printing text not typed code

I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);

passing arguments to zend partial and zend partialLoop

I'll try to describe this as best as possible, i haven't encountered this problem before but maybe i'm doing something wrong.
In my controller: i have:
public function indexAction() {
$this->view->projects = $this->projects->getProjects();
}
In the view file corresponding to this controller i have:
<?php echo $this->partial('partials/sidebar/_home.phtml', array($this->projects)); ?>
My _home.phtml contains the current code:
<div class="sidebar-content">
<p class="sidebar-title">Projects Portfolio</p>
<div id='coin-slider' style="margin:0 auto;">
<?php echo $this->partialLoop('partials/sidebar/_projects-slideshow.phtml', $this->projects);?>
</div>
</div>
And my _projects-slideshow.phtml has this code:
<a href="<?php echo $this->baseUrl($this->pimage); ?>">
<img src="<?php echo $this->baseUrl($this->pimage); ?>" alt="1" />
<span>
<?php echo $this->pname . ' by ' . $this->group . '. Client: ' . $this->client; ?>
</span>
</a>
The problem is that the variable is not passed to _home.phtml. I tried a Zend_Debug::dump($this->projects) and the result was NULL. I tried a Zend_Debug::dump($this) and I found the projects array. What am I doing wrong? The variable is not being passed, or maybe it is, to _home.phtml, not to mention that _projects-slideshow.phtml has no idea what $this->projects is.
If $this->projects in your _home.phtml is empty I think you should change
in index.phtml
<?php echo $this->partial('partials/sidebar/_home.phtml', array($this->projects)); ?>
into
<?php echo $this->partial('partials/sidebar/_home.phtml', array('projects' => $this->projects)); ?>
Here how it should has been:
$variables = array (
'records' => $result
);
$this->view->partial ("nodes/relations.php", $variables);
The variables in the array are named. What exactly is in your $this->projects->getProjects() ?

Categories