I am using codeigniter to create the admin panel of my website. I am not using it for the front end because I have lots of static pages in the front end and only a few things need to be dynamic so I will be doing it with core PHP queries.
My link for unlinking photo is , images is the controller and unlinkPhoto is the function and 32 is the image ID.
localhost/admin/index.php/images/unlinkPhoto/32
EDIT
however my image is located at localhost/uploads/testimage.jpg.
How can I point to that folder to unlink the image in codeigniter.
You really need to make sure you're enforcing decent security protocols, otherwise anyone can fake the GET request and delete the entirety of your uploaded files. Here is a basic solution:
public function unlinkPhoto($photoId)
{
// Have they specified a valid integer?
if ((int) $photoId > 0) {
foreach (glob("uploads/*") as $file) {
// Make sure the filename corresponds to the ID
// Caters for all file types (not just JPGs)
$info = pathinfo($file);
if ($info['filename'] == $photoId) {
unlink($file);
}
}
}
}
If you're using PHP 5.4, you might be able to reduce this code down even more:
if (pathinfo($file)['filename'] == $photoId) {
unlink($file);
}
Because they've implemented array dereferencing (finally). Although I haven't tested this particular piece of code. This is just a geeky addendum.
Related
I will completely clarify my question, sorry to everybody.
I have code writed in files from a website that now is not working, the html code is on pages with php extension, in a folder of a Virtual Host in my PC using Wampserever. C:\wamp\1VH\PRU1, when the site was online there was a folder where was a file called image.php. This file was called from other pages inside the site like this: (a little code of a file, C:\wamp\1VH\PRU1\example.php)
"<div><img src="https://www.example.com/img/image.php?f=images&folder=foods&type=salads&desc=green&dim=50&id=23" alt="green salad 23"></div>"
And the result was that the images was showed correctly.
Now, like i have this proyect in local, and i HAVE NOT the code of that image.php file i must to write it myself, this way the images will be showed the same way that when the site was online.
When the site was online and i open a image returned by that image.php file the URL was, following the example, https://example.com/images/foods/salads/green_50/23.png.
Now how the site is only local and i have not that image.php file writed because i'm bot sure how to write it, the images obviously are not showed.
In C:\wamp\1VH\PRU1\example.php the code of files was changed deleting "https://www.example.com/img/image.php?" for a local path "img/image.php?".
And in the same folder there is anothers: "img" folder (here must be allocated the image.php file), and "images" folder, inside it /foods/salads/green_50/23.png, 24.png.25.png..............
So i have exactly the same folder architecture that the online site and i changed the code that i could only, for example replacing with Jquery "https://www.example.com/img/image.php?" for "img/image.php?" but wich i can not do is replace all the code after the image.php file to obtain a image file.
So i think that the easiest way to can obtain the images normally is creating that IMAGE.PHP file that i have not here in my virtual host.
I'd like to know how to obtain the parameters and return the correct URL in the image,php file.
The image of the DIV EXAMPLE must be C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
I have in my PC the correct folders and the images, i only need to write the image.php file.
Note that there are "&" and i must to unite the values of "desc=green&dim=50&" being the result: green_50 (a folder in my PC).
TVM.
You probably want something like this.
image.php
$id = intval($_GET['id']);
echo '<div><img src="images/foods/salads/green_50/'.$id.'.png" alt="green salad '.$id.'"></div>';
Then you would call this page
www.example.com/image.php?id=23
So you can see here in the url we have id=23 in the query part of the url. And we access this in PHP using $_GET['id']. Pretty simple. In this case it equals 23 if it was id=52 it would be that number instead.
Now the intval part is very important for security reasons you should never put user input directly into file paths. I won't get into the details of Directory Transversal attacks. But if you just allow anything in there that's what you would be vulnerable to. It's often overlooked, so you wouldn't be the first.
https://en.wikipedia.org/wiki/Directory_traversal_attack
Now granted the Server should have user permissions setup properly, but I say why gamble when we can be safe with 1 line of code.
This should get you started. For the rest of them I would setup a white list like this:
For
folder=foods
You would make an array with the permissible values,
$allowedFolders = [
'food',
'clothes'
'kids'
];
etc...
Then you would check it like this
///set a default
$folder = '';
if(!empty($_GET['folder'])){
if(in_array($_GET['folder'], $allowedFolders)){
$folder = $_GET['folder'].'/';
}else{
throw new Exception('Invalid value for "folder"');
}
}
etc...
Then at the end you would stitch all the "cleaned" values together. As I said before a lot of people simply neglect this and just put the stuff right in the path. But, it's not the right way to do it.
Anyway hope that helps.
You essentially just need to parse the $_GET parameters, then do a few checks that the file is found, a real image and then just serve the file by setting the appropriate content type header and then outputting the files contents.
This should do the trick:
<?php
// define expected GET parameters
$params = ['f', 'folder', 'type', 'desc', 'dim', 'id'];
// loop over parameters in order to build path: /imagenes/foods/salads/green_50/23.png
$path = null;
foreach ($params as $key => $param) {
if (isset($_GET[$param])) {
$path .= ($param == 'dim' ? '_' : '/').basename($_GET[$param]);
unset($params[$key]);
}
}
$path .= '.png';
// check all params were passed
if (!empty($params)) {
die('Invalid request');
}
// check file exists
if (!file_exists($path)) {
die('File does not exist');
}
// check file is image
if (!getimagesize($path)) {
die('Invalid image');
}
// all good serve file
header("Content-Type: image/png");
header('Content-Length: '.filesize($path));
readfile($path);
https://3v4l.org/tTALQ
use $_GET[];
<?php
$yourParam = $_GET['param_name'];
?>
I can obtain the values of parameters in the image.php file tis way:
<?php
$f = $_GET['f'];
$folder = $_GET['folder'];
$type = $_GET['type'];
$desc = $_GET['desc'];
$dim = $_GET['dim'];
$id = $_GET['id'];
?>
But what must i do for the image:
C:/wamp/1VH/PRU1/images/foods/salads/green_50/23.png
can be showed correctly in the DIV with IMG SRC atribute?
I tried to create a folder to store all my images but it will not upload on its specific upload folder inside my installed theme.
Here is my code:
if(isset($_FILES['file']['tmp_name']))
{
$num_files = count($_FILES['file']['tmp_name']);//count file upload
for($i=0; $i<$num_files; $i++)
{
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
echo "no file upload!!";
}else
{
if(#copy($_FILES['file']['tmp_name'][$i], "/upload/".$_FILES['file']['name'][$i]))
{
$path = "upload/".$_FILES['file']['name'][$i];
//$sql = "insert into tblImage value ('".$path."')";
}else
{
echo "cant upload";
}
}
}
}
It's difficult to figure out exactly what went wrong because I don't know your setup, but try these things:
It's inadvisable to use #copy in this case, especially while you're trying to figure out what's going wrong. Copy will return false on failures and show other error messages in exceptional situations, unless you prefix it with #. If your disk is full, for example, it'll fail silently. Just copy is likely more useful for this.
Your file naming is, at the very least, difficult to decipher. Specifically, what paths are you using? PHP file operations like copy require precise path information. Your path, /upload/, which is upload/ later, refers to something relative from some arbitrary place, that may change. To solve this, figure out a good absolute path. If you're uploading to WP uploads, start with wp_upload_dir and build from there.
Unless you absolutely need a copy of the file from the original location later, move it instead of copying it. Remember that you'd be moving it to the uploads folder, so it'd still be available later, just somewhere else. This also avails you to move_uploaded_file().
There are some great comments (like from #kabiir) about how to debug what you've got. It's hard to figure out exactly what's going wrong without some debugging information.
Try:
if(isset($_FILES['file']['tmp_name'])) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
$file = $_FILE['file']['tmp_name'][$i];
error_log('source: ' . $file);
if (is_uploaded_file($file) && isset($_FILE['file']['name'][$i])) {
$name = $_FILE['file']['name'][$i];
error_log('uploaded name: ' . $name);
$destination = trailingslashit(wp_upload_dir()) . $name;
error_log('destination: ' . $destination);
if (!move_uploaded_file($source, $destination)) {
echo 'failed to move file.';
continue;
}
// Now $destination contains where the file was moved to.
}
}
}
This code will output to your log (or wherever else you have error logging pointed to) the source file+path, the uploaded file name and destination file+path, per file.
Unless there's something very special you're doing, wp_handle_upload() should take care of all your needs without rewriting this. When it's done, it calls the wp_handle_upload filter. Hook to the end of that filter's chain to do your SQL or whatever else. There are also many plugins that do what you're trying to do and save you from having to code it yourself.
As a side note, you ought not create SQL entirely by hand in WP. Use the wpdb class, with the $wpdb->prepare() function. This also allows you to use $wpdb->prefix, which is the prefix for your table. (You've prefixed your table and created it according to WP standards, right?)
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);
Scenario :I am trying to build a Mobile Entertainment Portal. It will enable users to download Music & Movies to their Cell Phones...
Problem Exp : Suppose I upload 100 folders of Songs, each folder is for one Album. I want a way to generate a page with all the folders name (Album Name) in it. If user click on the page, they should be taken to a page where they get list of all songs in the album. Clicking on any song name will let them download it. Can it be done anyway or will I have to manually design each of the 3 pages for each album. If I do that, its time consuming and also will be difficult to change anything like footer, header...
First of all, this is a weighted question. But I will try to answer some of your questions to get you started.
You can scan for directories using scandir() in PHP.
$path = '/path/to/music';
$dir = scandir($path);
if (is_array($dir)) {
foreach ($dir as $directory) {
if (is_dir("{$path}/{$directory}")) {
// validate that it's among the directories you want
}
}
}
So, now that you know how to do that, perhaps instead of trying to create a separate page for each album folder you could use one script and based on the GET vars, display the appropriate content. e.g.
domain.com/index.php?album=Album+Name
Now let's see how that might work with the above example:
// assume your album folder names use underscores
$album = (isset($_GET['album']))
? str_replace('+', '_', $_GET['album'])
: null;
$path = '/path/to/music';
$dir = scandir($path);
if (is_array($dir)) {
foreach ($dir as $directory) {
if (is_dir("{$path}/{$directory}") && $album == $directory) {
// now, scan for files
}
}
}
Then to get the files, when you're looping through the directories, instead of checking if it is a directory, check that it's not a directory and that will give you your files. (e.g. if (!is_dir(...)
I am currently building a backend to a site using the codeigniter framework, I have hit a bit of a problem, I needing a way to allow the user to upload a zipped folder of images, on completing the form, zipped folder must be unzipped, and the files need to be moved to a folder else where on the server, have thumbnail version of each image created and have there file name add to the DB, and also if the images are for a content type that does not already exist then I need to make a directory with that content type.
I know there is an upload class in Codeigniter, but I am not sure that, that has the capabilities do what I need, I could really do with some advice please?
Thanks
As Jan pointed out, this is a broad question (like 3 or 4 questions). I'm not up to date with the CodeIgniter framework but to Unzip the files you can do something like this:
function Unzip($source, $destination)
{
if (extension_loaded('zip') === true)
{
if (file_exists($source) === true)
{
$zip = new ZipArchive();
if ($zip->open($source) === true)
{
$zip->extractTo($destination);
}
return $zip->close();
}
}
return false;
}
Unzip('/path/to/uploaded.zip', '/path/to/extract/');
You wont be able to do any of the image or file checking using the Upload class. The upload class will let you accept the file and check it is a ZIP but that's as far as it will go.
From there, unzip the file and just do some simple PHP on the files to check they are the right type and make your folders etc. I would put this logic in a new library to keep it separated correctly.