Can't see image, but, I know it's there - php

I have an image located on my site at:
www.blah.com/gallery/gallery/2244.jpg
If I type this URL directly I see the image.
Now, I have a small gallery where I want the image (and others) to show, but, using the following code it simply does not show:
$files = glob("/home/mysite/public_html/gallery/gallery/*.*");
for ($i=1; $i<count($files); $i++)
{
$num = $files[$i];
echo '<a class="fancybox-effects-a" rel="gallery" href="'.$num.'">';
echo '<img src="'.$num.'" class="gallery_img" alt=""></a>';
}
The image was uploaded without error like so (using http://www.verot.net/php_class_upload.htm):
if(isset($_FILES['image'])){
include('/home/mysite/php/lib/img_upload/class.upload.php');
// retrieve eventual CLI parameters
$cli = (isset($argc) && $argc > 1);
if ($cli) {
if (isset($argv[1])) $_GET['file'] = $argv[1];
if (isset($argv[2])) $_GET['dir'] = $argv[2];
if (isset($argv[3])) $_GET['pics'] = $argv[3];
}
// set variables
$dir_dest = (isset($_GET['dir']) ? $_GET['dir'] : 'test');
$dir_pics = (isset($_GET['pics']) ? $_GET['pics'] : $dir_dest);
if (!$cli) {
// ---------- IMAGE UPLOAD ----------
$handle = new Upload($_FILES['image']);
if ($handle->uploaded) {
$handle->image_resize = true;
$handle->image_ratio_x = true;
$handle->image_y = 500;
$handle->Process('/home/mysite/public_html/gallery/gallery/');
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
$success .= 'Image uploaded to the gallery successfully!';
} else {
// one error occured
$error .= '<li>file not uploaded to the wanted location';
$error .= '<li>Error: ' . $handle->error . '';
}
// we now process the image a second time, with some other settings
/******************************/
// produce thumbnails
/*****************************/
$handle->image_resize = true;
$handle->image_ratio_x = true;
$handle->image_y = 120;
$handle->image_reflection_height = 50;
$handle->image_reflection_opacity = 90;
$handle->image_convert = 'png';
$handle->Process('/home/mysite/public_html/gallery/gallery/thumbs/');
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
$success .= '<p>Thumbnail created successfully, see below...';
$success .= '<p><img src="/gallery/gallery/thumbs/' . $handle->file_dst_name . '" />';
} else {
// one error occured
$error .= 'file not uploaded to the wanted location';
$error .= ' Error: ' . $handle->error . '';
}
/******************************/
// END use this if you want to produce thumbnails
/*****************************/
// we delete the temporary files
$handle-> Clean();
} else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
$error .= '<li>file not uploaded on the server';
$error .= '<li>Error: ' . $handle->error . '';
}
}
}
I cannot fathom this out at all!

It looks like you set the src to the images' absolute path. Try this:
foreach (glob('/home/mysite/public_html/gallery/gallery/*.jpg') as $file) {
$file = '/gallery/gallery/'.basename($file);
echo '<a class="fancybox-effects-a" rel="gallery" href="'.$file.'">';
echo '<img src="'.$file.'" class="gallery_img" alt=""></a>';
}

Related

Either _POST or _FILES is empty when submitting form

I am trying to upload a simple image file to my project using php and html but when I submit the form, either the _FILE method is empty or the _POST method is empty. My code never makes it passed the if statement checking that all fields are not empty, as I get the error: "All fields are mandatory, please fill all the fields."
Here is my CRUD.php file up until the error message:
// Include and initialize database class
require_once(ROOT_DIR . '/Classes/database.class.php');
$imageDB = new DB();
$tblName = 'image';
// The folder where the images will be stored
$uploadDir = CONTENT_PATH . '/';
// Allow file formats
$allowTypes = array('jpg', 'png', 'jpeg', 'gif');
// Set default redirect url
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
$statusMsg = '';
$sessData = array();
$statusType = 'danger';
// Check if user has uploaded new image
if (isset($_POST['imgSubmit'])) {
//Set redirect url
$redirectURL = PUBLIC_PATH . '/addEdit.php';
//Get submitted data and clean it from injections
$id = $_POST['id'];
$image = $_FILES['image'];
echo $image['name'];
//Store title variable without any html or php tags and trims whitespace from beginning and end
$title = strip_tags(trim($_POST['title']));
// Validate user tags are separated by comma or space and contain only alphanumeric or space/comma input
$regex = '/^[ ,]*[a-zA-Z0-9]+(?:[ ,]+[a-zA-Z0-9]+){0,5}[ ,]*$/';
if (preg_match($regex, $_POST['tags']) == 0) {
exit('Tags are not valid!');
}
// Makes all tags lower case
$tag_input = strtolower($_POST['tags']);
// Clean up multiple commas or whitespaces
$clean_tag_input = preg_replace('/[\s,]+/', ' ', $tag_input);
// Replaces spaces with commas
$comma_tags = str_replace(' ', ',', $clean_tag_input);
// Submitted user data
$imgData = array('title' => $title,'tags' => $comma_tags);
// Store submitted data into session
$sessData['postData'] = $imgData;
$sessData['postData']['id'] = $id;
// ID query string
$idStr = !empty($id)?'?id='.$id:'';
// If the data is not empty
if ((!empty($image['name']) && !empty($title) && !empty($comma_tags)) || (!empty($id) && !empty($title) && !empty($comma_tags))) {
echo $title;
if(!empty($image)) {
$filename = basename($image['name']);
// Get file extension in lower case
$fileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
echo $fileType;
// Generate a unique name for the image to prevent throwing exists error
$unique_image_name = rand(10000, 990000) . '_' . time() . '.' . $fileType;
// The path of the new uploaded image
$targetFilePath = $uploadDir . $unique_image_name;
echo $targetFilePath;
if (in_array($fileType, $allowTypes)) {
// Check to make sure the image is valid
if (!empty($image['tmp_name']) && getimagesize($image['tmp_name'])) {
if (file_exists($unique_image_name)) {
$statusMsg = 'Image already exists, please choose another or rename that image.';
} else if ($image['size'] > 500000) {
$statusMsg = 'Image file size too large, please choose an image less than 500kb.';
} else {
// Everything checks out now we can move the uploaded image
if (move_uploaded_file($image['tmp_name'], $targetFilePath)){
$imgData['filename'] = $unique_image_name;
$imgData['username'] = $_SESSION['username'];
} else {
$statusMsg = 'Sorry, there was an error uploading your file.';
}
}
}
} else {
$statusMsg = 'Image file is empty or corrupt.';
}
} else {
$statusMsg = 'Sorry, only JPG, JPEG, PNG && GIF files are allowed to be uploaded.';
}
} else {
$statusMsg = 'Sorry something went wrong.';
}
if (!empty($id)) {
// Previous filename
$conditions['where'] = array('id' => $_GET['imageID'],);
$conditions['return_type'] = 'single';
$prevData = $imageDB->getRows('image', $conditions);
// Update data
$condition = array('id' => $id);
$update = $imageDB->update($tblName, $imgData, $condition);
if($update) {
//Remove old file from server
if (!empty($imgData['filename'])) {
#unlink($uploadDir . $prevData['filename']);
}
$statusType = 'success';
$statusMsg = 'Image data has been updated successfully.';
$sessData['postData'] = '';
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
} else {
$statusMsg = 'Some problem occurred, please try again.';
//Set redirect url
$redirectURL .= $idStr;
}
} elseif (!empty($imgData['filename'])) {
// Insert data
$insert = $imageDB->insert($tblName, $imgData);
if ($insert) {
$statusType = 'success';
$statusMsg = 'Image has been uploaded successfully.';
$sessData['postData'] = '';
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
} else {
$statusMsg = 'Some problem occurred, please try again.';
}
} else {
$statusMsg = 'All fields are mandatory, please fill all the fields.';
}
And here is my addEdit.php file with the form:
require_once(ROOT_DIR . '/Templates/header.php');
$postData = $imgData = array();
$newViewkey = uniqid();
// Get image data
if (!empty($_GET['imageID'])) {
//include and initialize DB class
require_once(ROOT_DIR . '/Classes/database.class.php');
$addEditDB = new DB();
$conditions['where'] = array('id' => $_GET['imageID'],);
$conditions['return_type'] = 'single';
$imgData = $addEditDB->getRows('image', $conditions);
}
// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;
// Define action
$actionLabel = !empty($_GET['imageID'])?'Edit':'Add';
head('Upload Image', $_SESSION['username'])
?>
<!-- Display status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="message">
<?php echo $statusMsg; ?>
</div>
<?php } ?>
<div class="upload-form">
<h1>Upload Image</h1>
<form action="<?php echo IMAGE_UTIL_PATH;?>/crud.php" method="POST" enctype="multipart/form-data">
<label for="title">Title</label>
<input
type="text" name="title" id="title"
placeholder="Type image title here."
value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" required>
<?php if (!empty($imgData['tags'])) {
$tagsSpaces = preg_replace('/,/', ', ', trim($imgData['tags']));
} ?>
<label for="tags">Tags</label>
<textarea name="tags" id="tags" placeholder="Enter at least 1 tag describing the image separated by a space ' ' or a ','." required><?php echo !empty($imgData['tags'])?$tagsSpaces:''; ?></textarea>
<input type="file" name="image" id="image" value="<?php echo !empty($imgData['filename'])?$imgData['filename']:''; ?>" required>
<input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
<input type="hidden" name="modified" value="<?php echo !empty($imgData['id'])?date('Y/m/d h:m:s'):''; ?>">
<input type="hidden" name="viewkey" value="<?php echo !empty($imgData['viewkey'])?$imgData['viewkey']:$newViewkey;?>">
<?php if (!empty($imgData['filename'])) { ?>
<div>
<img src="<?php echo !empty($imgData['filename'])?$imgData['filename']:'';?>" height=75 width=auto >
</div>
<?php } ?>
<input type="submit" value="Upload" name="imgSubmit">
</form>
<div class="message">
Back to Manage Uploads
</div>
</div>
<?php require_once(ROOT_DIR . '/Templates/footer.php')?>
And finally here is my config.php file with all the path definitions:
/*
Set include path to include files outside root directory
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\Shape_Search\resources');
/*
Error reporting
*/
ini_set("display_errors", "true");
error_reporting(E_ALL|E_STRICT);
/*
Create constants for heavily used paths relative to config file location
*/
defined('ROOT_DIR')
or define('ROOT_DIR', dirname(__FILE__));
defined('SRC_DIR')
or define('SRC_DIR', dirname(dirname(__FILE__)) . '\src');
defined('PUBLIC_PATH')
or define('PUBLIC_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html');
defined('CONTENT_PATH')
or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');
defined('LAYOUT_PATH')
or define('LAYOUT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/layout');
defined('CSS_PATH')
or define('CSS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/css');
defined('JS_PATH')
or define('JS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/js');
defined('LIBRARY_PATH')
or define('LIBRARY_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/resources/Library');
defined('CLASSES_PATH')
or define('CLASSES_PATH', realpath(dirname(__FILE__)) . '/Classes');
defined('TEMPLATES_PATH')
or define('TEMPLATES_PATH', realpath(dirname(__FILE__)) . "\Templates");
defined('IMAGE_UTIL_PATH')
or define('IMAGE_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/ImageUtilities');
defined('RATING_UTIL_PATH')
or define('RATING_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/RatingUtilities');
defined('USER_UTIL_PATH')
or define('USER_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/UserUtilities');
?>
And here is my php error log:
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning: move_uploaded_file(/Shape_Search/public_html/img/content/973439_1644497526.jpg): Failed to open stream: No such file or directory in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning: move_uploaded_file(): Unable to move "C:\xampp\tmp\phpCCA.tmp" to "/Shape_Search/public_html/img/content/973439_1644497526.jpg" in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
It was an issue of directory vs. path.
// The folder where the images will be stored
$uploadDir = CONTENT_PATH . '/';
Should be corrected to:
// The folder where the images will be stored
$uploadDir = CONTENT_DIR . '/';
Where the global variables CONTENT_PATH and CONTENT_DIR are:
defined('CONTENT_PATH')
or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');
defined('CONTENT_DIR')
or define('CONTENT_DIR', dirname(dirname(__FILE__)) . '/public_html/img/content');

PHP unlink() problem with files named with multiple extensions

I'm encountering an issue I've never come across before. I have some images uploaded as JPG or PNG with a duplicate of the image in WebP format, eg in this file naming convension:
https://example.com/uploads/memory-day.png >
https://example.com/uploads/memory-day.png.webp
If I delete a file through PHP using the unlink() function like normal, it works fine for everything else until I delete the PNG duplicate image. When I do that, the WebP file is also deleted and I can't see how it's happening -- is it a weird issue in the unlink() function with a file having a double extension? I can't seem to replicate it unless it's there's a WebP file involved.
For clarity, here's the PHP code that deletes the files (and yeah, I know it needs to be a prepare statement, I haven't updated it yet):
if(isset($_POST['delete'])) {
$countG = 0;
$err = 0;
foreach($_POST['delFile'] as $actionID) {
$action_id = $conn->real_escape_string($actionID);
$query = $conn->query("SELECT `filename`, `dir` FROM `fileuploads` WHERE `id` = '$action_id'");
$delF = $query->fetch_assoc();
$filenameDel = StripSlashes($delF['filename']);
$filenameDir = StripSlashes($delF['dir']);
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)){
if(unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel)) {
unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel);
}
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
$countG++;
} else {
$err++;
}
} else {
$err++;
if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
//Remove from db if file is not there physically
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
}
}
}
if($countG > 0) {
$green = 1;
$message1 = "$countG File(s) Deleted!";
}
if($err > 0) {
$red = 1;
$message2 = "Error deleting $err files!";
error_log(print_r(error_get_last(), TRUE));
}
}

How to download php scripts from a live server to local system with security?

I want to download project files specially (php) files from live site (shared hosting server) to my local development machine, If I am the owner for both locations, what is the secure way to download by using curl or any other way with php?
I wrote some code it does not download php script but the result of its execution.
$remoteUrl = $remoteConfig['remoteUrl'];
$remoteUrl = substr($remoteUrl, 0, strrpos( $remoteUrl, '/'));
$filePath = $_POST['file'];
$url = $remoteUrl .'/'. $filePath;
$downloaded = __DIR__ .DIRECTORY_SEPARATOR. $filePath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$st = curl_exec($ch);
$fd = fopen($downloaded, 'w');
fwrite($fd, $st);
if( fclose($fd) ) {
echo json_encode(['response' => true, 'msg' => 'File Downloaded']);
}
curl_close($ch);
exit();
No one was going to reply me but I found a way how can I download php(code) files from the live-site(shared hosting server) to local development-machine.
See the following link http://code.tutsplus.com/tutorials/how-to-work-with-php-and-ftp--net-20012
It helped me completly.
Edited little bit as under
class FTPClient
{
// *** Class variables
private $connectionId;
private $loginOk = false;
private $messageArray = array();
public function __construct()
{
}
private function logMessage($message)
{
$this->messageArray[] = $message;
}
public function getMessages()
{
return $this->messageArray;
}
public function connect($server, $ftpUser, $ftpPassword, $isPassive = false)
{
// *** Set up basic connection
$this->connectionId = ftp_connect($server);
// *** Login with username and password
$loginResult = ftp_login($this->connectionId, $ftpUser, $ftpPassword);
// *** Sets passive mode on/off (default off)
ftp_pasv($this->connectionId, $isPassive);
// *** Check connection
if ((!$this->connectionId) || (!$loginResult)) {
$this->logMessage('FTP connection has failed!');
$this->logMessage('Attempted to connect to ' . $server . ' for user ' . $ftpUser, true);
return false;
} else {
$this->logMessage('Connected to ' . $server . ', for user ' . $ftpUser);
$this->loginOk = true;
return true;
}
}
public function makeDir($directory)
{
if (!is_dir($directory)) {
// *** If creating a directory is successful...
if (#ftp_mkdir($this->connectionId, $directory)) {
$this->logMessage('Directory "' . $directory . '" created successfully');
return true;
} else {
// *** ...Else, FAIL.
$this->logMessage('Failed creating directory "' . $directory . '"');
return false;
}
} else {
$this->logMessage('Failed creating directory "' . $directory . '" already exist.');
}
}
public function uploadFile($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$value = explode('.', $fileFrom);
$extension = end($value);
if (in_array($extension, $asciiArray)) {
$mode = FTP_ASCII;
} else {
$mode = FTP_BINARY;
}
// *** Upload the file
$upload = ftp_put($this->connectionId, $fileTo, $fileFrom, $mode);
// *** Check upload status
if (!$upload) {
$this->logMessage('FTP upload has failed!');
return false;
} else {
$this->logMessage('Uploaded "' . $fileFrom . '" as "' . $fileTo);
return true;
}
}
public function changeDir($directory)
{
if (ftp_chdir($this->connectionId, $directory)) {
$this->logMessage('Current directory is now: ' . ftp_pwd($this->connectionId));
return true;
} else {
$this->logMessage('Couldn\'t change directory');
return false;
}
}
public function getDirListing($directory = '.', $parameters = '-la')
{
// get contents of the current directory
// $contentsArray = ftp_nlist($this->connectionId, $parameters . ' ' . $directory);
$contentsArray = ftp_nlist($this->connectionId, $directory);
return $contentsArray;
}
public function downloadFile($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$value = explode('.', $fileFrom);
$extension = end($value);
//$extension = end(explode('.', $fileFrom));
if (in_array($extension, $asciiArray)) {
$mode = FTP_ASCII;
} else {
$mode = FTP_BINARY;
}
// try to download $remote_file and save it to $handle
if (ftp_get($this->connectionId, $fileTo, $fileFrom, $mode, 0)) {
$this->logMessage(' file "' . $fileTo . '" successfully downloaded');
return true;
} else {
$this->logMessage('There was an error downloading file "' . $fileFrom . '" to "' . $fileTo . '"');
return false;
}
}
public function __deconstruct()
{
if ($this->connectionId) {
ftp_close($this->connectionId);
}
}
}
Usage below
// *** Define your host, username, and password
define('FTP_HOST', 'host');
define('FTP_USER', 'user');
define('FTP_PASS', 'password');
define('PASSIVE_MODE', TRUE);
// *** Create the FTP object
$ftpObj = new FTPClient();
// *** Connect
if ($ftpObj -> connect(FTP_HOST, FTP_USER, FTP_PASS, PASSIVE_MODE)) {
// *** Then add FTP code here
$filePath = $_POST['file'];
$path = dirname($filePath);
$fileName = basename($filePath);
if (!file_exists($path)) {
mkdir($path, 0755, true);
}
// *** Change to folder
$ftpObj->changeDir($path);
$fileFrom = $fileName; # The location on the remote
$fileTo = $filePath; # Source dir to save to
// *** Download file
$ftpObj->downloadFile($fileFrom, $fileTo);
echo json_encode(['response' => true, 'msg' => 'File Downloaded']);
} else {
echo json_encode(['response' => false, 'msg' => $ftpObj -> getMessages()]);
}
And finally I have done...

Creating a zip is renaming the files with \ on file

Im using this code to make a zip from my folder:
<?php
// DIRECTORY WE WANT TO BACKUP
$pathBase = '../'; // Relate Path
// ZIP FILE NAMING ... This currently is equal to = sitename_www_YYYY_MM_DD_backup.zip
$zipPREFIX = "sitename_www";
$zipDATING = '_' . date('Y_m_d') . '_';
$zipPOSTFIX = "backup";
$zipEXTENSION = ".zip";
// SHOW PHP ERRORS... REMOVE/CHANGE FOR LIVE USE
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// ############################################################################################################################
// NO CHANGES NEEDED FROM THIS POINT
// ############################################################################################################################
// SOME BASE VARIABLES WE MIGHT NEED
$iBaseLen = strlen($pathBase);
$iPreLen = strlen($zipPREFIX);
$iPostLen = strlen($zipPOSTFIX);
$sFileZip = $pathBase . $zipPREFIX . $zipDATING . $zipPOSTFIX . $zipEXTENSION;
$oFiles = array();
$oFiles_Error = array();
$oFiles_Previous = array();
// SIMPLE HEADER ;)
echo '<center><h2>PHP Example: ZipArchive - Mayhem</h2></center>';
// CHECK IF BACKUP ALREADY DONE
if (file_exists($sFileZip)) {
// IF BACKUP EXISTS... SHOW MESSAGE AND THATS IT
echo "<h3 style='margin-bottom:0px;'>Backup Already Exists</h3><div style='width:800px; border:1px solid #000;'>";
echo '<b>File Name: </b>',$sFileZip,'<br />';
echo '<b>File Size: </b>',$sFileZip,'<br />';
echo "</div>";
exit; // No point loading our function below ;)
} else {
// NO BACKUP FOR TODAY.. SO START IT AND SHOW SCRIPT SETTINGS
echo "<h3 style='margin-bottom:0px;'>Script Settings</h3><div style='width:800px; border:1px solid #000;'>";
echo '<b>Backup Directory: </b>',$pathBase,'<br /> ';
echo '<b>Backup Save File: </b>',$sFileZip,'<br />';
echo "</div>";
// CREATE ZIPPER AND LOOP DIRECTORY FOR SUB STUFF
$oZip = new ZipArchive;
$oZip->open($sFileZip, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$oFilesWrk = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathBase),RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($oFilesWrk as $oKey => $eFileWrk) {
// VARIOUS NAMING FORMATS OF THE CURRENT FILE / DIRECTORY.. RELATE & ABSOLUTE
$sFilePath = substr($eFileWrk->getPathname(),$iBaseLen, strlen($eFileWrk->getPathname())- $iBaseLen);
$sFileReal = $eFileWrk->getRealPath();
$sFile = $eFileWrk->getBasename();
// WINDOWS CORRECT SLASHES
$sMyFP = str_replace('\\', '/', $sFileReal);
if (file_exists($sMyFP)) { // CHECK IF THE FILE WE ARE LOOPING EXISTS
if ($sFile!="." && $sFile!="..") { // MAKE SURE NOT DIRECTORY / . || ..
// CHECK IF FILE HAS BACKUP NAME PREFIX/POSTFIX... If So, Dont Add It,, List It
if (substr($sFile,0, $iPreLen)!=$zipPREFIX && substr($sFile,-1, $iPostLen + 4)!= $zipPOSTFIX.$zipEXTENSION) {
$oFiles[] = $sMyFP; // LIST FILE AS DONE
$oZip->addFile($sMyFP, $sFilePath); // APPEND TO THE ZIP FILE
} else {
$oFiles_Previous[] = $sMyFP; // LIST PREVIOUS BACKUP
}
}
} else {
$oFiles_Error[] = $sMyFP; // LIST FILE THAT DOES NOT EXIST
}
}
$sZipStatus = $oZip->getStatusString(); // GET ZIP STATUS
$oZip->close(); // WARNING: Close Required to append files, dont delete any files before this.
// SHOW BACKUP STATUS / FILE INFO
echo "<h3 style='margin-bottom:0px;'>Backup Stats</h3><div style='width:800px; height:120px; border:1px solid #000;'>";
echo "<b>Zipper Status: </b>" . $sZipStatus . "<br />";
echo "<b>Finished Zip Script: </b>",$sFileZip,"<br />";
echo "<b>Zip Size: </b>",human_filesize($sFileZip),"<br />";
echo "</div>";
// SHOW ANY PREVIOUS BACKUP FILES
echo "<h3 style='margin-bottom:0px;'>Previous Backups Count(" . count($oFiles_Previous) . ")</h3><div style='overflow:auto; width:800px; height:120px; border:1px solid #000;'>";
foreach ($oFiles_Previous as $eFile) {
echo basename($eFile) . ", Size: " . human_filesize($eFile) . "<br />";
}
echo "</div>";
// SHOW ANY FILES THAT DID NOT EXIST??
if (count($oFiles_Error)>0) {
echo "<h3 style='margin-bottom:0px;'>Error Files, Count(" . count($oFiles_Error) . ")</h3><div style='overflow:auto; width:800px; height:120px; border:1px solid #000;'>";
foreach ($oFiles_Error as $eFile) {
echo $eFile . "<br />";
}
echo "</div>";
}
// SHOW ANY FILES THAT HAVE BEEN ADDED TO THE ZIP
echo "<h3 style='margin-bottom:0px;'>Added Files, Count(" . count($oFiles) . ")</h3><div style='overflow:auto; width:800px; height:120px; border:1px solid #000;'>";
foreach ($oFiles as $eFile) {
echo $eFile . "<br />";
}
echo "</div>";
}
// CONVERT FILENAME INTO A FILESIZE AS Bytes/Kilobytes/Megabytes,Giga,Tera,Peta
function human_filesize($sFile, $decimals = 2) {
$bytes = filesize($sFile);
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$sz[$factor];
}
?>
Source
When this finishes it zip the folder but it lefts a slash on every file on root of the zip:
image
Then i have another script to unzip zip files.
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/myzips/extract_path/');
$zip->close();
echo 'woot!';
} else {
echo 'doh!';
}
Source
But when the files and directory start with \ it mess up with the unzip. and it doesnt unzip into the directories, every file go to root of the unziped folder. image
How can i remove \ on root of the zip file?

I am trying to download a file from mysql, I saved the file location in the database, now I am trying to make a download link for the user on my page

Unable to create the download link. I am fetching the path saved from database and then try to make a link for it to download, but nothing happens.
Below is my code:
$query_print="SELECT vitae_pi FROM pi WHERE username='t124'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
echo ' this is file path '.$query_print_path;
Here I am simply trying to create the download link for user t124, instead of using the current user for testing purposes?
This is hyperlink code:
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
Any suggestions?
This my move file function:
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
//echo $filename;
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$_SESSION['current_filename']=$this->newName;
echo $_SESSION['current_filename'];
$result .= ', and was renamed ' . $this->newName;
}
else{
$_SESSION['current_filename']=$file['name'];
echo $_SESSION['current_filename'];
}
//$result .= '.';
//echo $this->newName;
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
Updating the table with file path:
$file_path_variable1= $destination1.$_SESSION['current_filename'];
echo '$file_path_variable1 : '.$file_path_variable1;
$query1="UPDATE proposal SET whitepaper_prop='$file_path_variable1' WHERE userName_prop='$currentuser'";
$result_query1=mysqli_query($conn,$query1);
....................
SOLUTION CODE IS:
Solution code is :
$query_print="SELECT vitae_pi FROM pi WHERE username='t115'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
$dir= 'uploaded/';
$path=opendir($dir);
<?php
}while($query_pi_array=mysqli_fetch_assoc($query_pi_result));?>
<div>
<?php while($file=readdir($path)){
if($file != "." || $file !=".."){
if($file==$query_print_path){ ?>
Proposal Whitepaper
What does this display ?
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
DOWNLOAD should be part of the PHP string, if not, it will be considered as a constant :
<?php echo "<a href='".$query_print_path."'>DOWNLOAD</a>"; ?>
Also, use double quotes for HTML attributes :
<?php echo "DOWNLOAD"; ?>
And the optimized way (to avoid useless string parsing) :
<?php echo 'DOWNLOAD'; ?>

Categories