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');
Related
I am using yii2. I am trying to select a file and then want to save it to my database table. I am using core PHP for it. Below is my code
<form action = <?=\yii\helpers\Url::toRoute(['meteracceptanceheader/import'])?> method ="post"
enctype="multipart/form-data">
.
.
.
.
.
.
.
<div class="row">
<div class="col-md-2">
Upload-Image
<input type="file" name="file"/>
<br />
<input type="submit" class="btn btn-primary pull-left" />
</div>
</div>
</form>
Controller
public function actionImport()
{
.
.
. // my other code
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileExt = explode('.',$fileName);
print_r($file);
die();
.
.
.
.
return $this->render('excel_finish', ['records_saved' => $ok_count,'status_arr'=>$status_arr]);
}
Database Table
In the above table, id is auto-increment accpt_id is the model id which I already have and file_path is the name of the file which should be saved like 123.jpg.
The file should be saved into a folder uploads/meter_acceptance/ and append with the file name.
Note:
I have already know how to upload images via the active form but here I want to do it in a traditional way.
Any help would be highly appreciated.
your controller should be like this
public function actionUpload(){
$model = new Images();
$uploadPath = Yii::getAlias('#root') .'/uploads/';
if (isset($_FILES['image'])) {
$file = \yii\web\UploadedFile::getInstanceByName('image');
$original_name = $file->baseName;
$newFileName = \Yii::$app->security
->generateRandomString().'.'.$file->extension;
// you can write save code here before uploading.
if ($file->saveAs($uploadPath . '/' . $newFileName)) {
$model->image = $newFileName;
$model->original_name = $original_name;
if($model->save(false)){
echo \yii\helpers\Json::encode($file);
}
else{
echo \yii\helpers\Json::encode($model->getErrors());
}
}
}
else {
return $this->render('upload', [
'model' => $model,
]);
}
return false;
}
I'm trying to upload a form that contains 2 files, one it's an .dae object, other is an image.
The form(it's inside a JS bootbox dialog):
message: '<form name="uploadForm" action="Control/upload.php" method="post" enctype="multipart/form-data"> '
+ ' Nome do objeto:<br />'
+ ' <input name="objectname" type="text"><br />'
+ ' <input type="hidden" name="MAX_FILE_SIZE" value="10000000">'
+ ' Objeto 3D(Formato <b>.dae</b>):<br />'
+ ' <input name="userfile[]" type="file" /><br />'
+ ' Imagem 2D do objeto(Formato <b>.png</b> ou <b>.jpg</b>) (<i>Opcional</i>):'
+ ' <input name="userfile[]" type="file" /><br />'
+ ' Comentário:<br />'
+ ' <textarea name="comment" rows="5" cols="75"></textarea>'
+ '</form>',
In the the form, theres two upload files, the "Objeto 3D"(3d object, .dae) and the "Imagem 2D do Objeto"(Image 2d of the object, .jpg, .png)
It's necessary to upload only the object file , the image is OPTIONAL, 'cause if it's not uploaded, there's a standard one in the database.
I tried to make it work creating an boolean $imageUploaded, that is setted in the getFileInputs method, but somehow, it doesn't quite work..
If I upload a .dae and an image, works perfectly
If I upload wrong file extension, it works perfectly(2 wrongs or 1 at
a time)
But if I upload only a .dae file, it get's me the error that the
image file extension is wrong...
Here's my code(it runs on other script)(without the database code, not necessary here)
<?php
class UploadObject{
//Control vars
private $uploadIsOk;
private $imageUploaded;
//Input vars
private $objectName;
private $objectComment;
private $uploadDir;
private $uploadFiles;
private $tmpFileNames;
//Messages
private $successMessage;
private $errorMessage;
public function __construct($uploadDir){
$this->uploadIsOk = TRUE;
$this->imageUploaded = FALSE;
$this->successMessage = '';
$this->errorMessage = '';
$this->uploadDir = $uploadDir;
}
//Methods
public function main(){
$this->getTextInputs();
$this->getFileInputs();
$this->checkFileExtensions();
if($this->getUploadIsOk()){
$this->uploadTheFiles();
$this->alertMessage($this->getSuccessMessage());
}else{
$this->alertMessage($this->getErrorMessage());
}
}
public function uploadTheFiles(){
$message = '';
$this->replaceFileNames();
if( move_uploaded_file( $this->getTmpFileNames()[0], $this->getUploadFiles()[0] ) ){
$message = $message . "Upload do objeto foi realizado com sucesso;<br>";
if($this->getImageUploaded()){
if( move_uploaded_file( $this->getTmpFileNames()[1], $this->getUploadFiles()[1] ) ){
$message = $message . "Upload da imagem do objeto foi realizado com sucesso;";
}
}
else{
$message = $message . "Imagem do objeto não foi enviada;";
}
$this->setSuccessMessage($message);
}
}
public function getTextInputs(){
if($_POST["objectname"] != "")
$this->setObjectName($_POST["objectname"]);
else
$this->setObjectName("objeto");
$this->setObjectComment($_POST["comment"]);
}
public function getFileInputs(){
$objectFile = $this->uploadDir . 'objects/' . basename($_FILES['userfile']['name'][0]);
$imageFile = '';
if($_FILES["userfile"]["name"][0] != ""){
$imageFile = $this->uploadDir . 'images/' . basename($_FILES["userfile"]["name"][1]);
$this->setImageUploaded(TRUE);
}
$uploadFiles = array($objectFile, $imageFile);
$this->setUploadFiles($uploadFiles);
$tmpObjectName = $_FILES["userfile"]["tmp_name"][0];
if($this->getImageUploaded())
$tmpImageName = $_FILES["userfile"]["tmp_name"][1];
else
$tmpImageName = "";
$tmpFileNames = array($tmpObjectName, $tmpImageName);
$this->setTmpFileNames($tmpFileNames);
}
public function checkFileExtensions(){
$message = '';
if(pathinfo( $this->getUploadFiles()[0], PATHINFO_EXTENSION ) != "dae"){
$this->setUploadIsOk(FALSE);
$message = $message . 'Erro: Objeto com formato inválido, utilize arquivos .dae;<br>';
}
if($this->getImageUploaded()){
if(pathinfo( $this->getUploadFiles()[1], PATHINFO_EXTENSION ) != "jpg" && pathinfo( $this->getUploadFiles()[1], PATHINFO_EXTENSION ) != "jpeg" && pathinfo( $this->getUploadFiles()[1], PATHINFO_EXTENSION ) != "png"){
$this->setUploadIsOk(FALSE);
$message = $message . 'Erro: Imagem com formato inválido, utilize arquivos .jpg, .jpeg ou .png;';
}
}
$this->setErrorMessage($message);
}
public function replaceFileNames(){
date_default_timezone_set("Brazil/East");
$data = date("h-i-sa-") . date("Y-m-d-");
$fileName = $data . $this->getObjectName();
$objectExtension = '.' . pathinfo($this->getUploadFiles()[0], PATHINFO_EXTENSION);
$newObjectName = str_replace(basename($_FILES['userfile']['name'][0]), $fileName . $objectExtension, $this->getUploadFiles()[0]);
$newImageName = '';
if($this->getImageUploaded()){
$imageExtension = '.' . pathinfo($this->getUploadFiles()[1], PATHINFO_EXTENSION);
$newImageName = str_replace(basename($_FILES['userfile']['name'][1]), $fileName . $imageExtension, $this->getUploadFiles()[1]);
}
$uploadFiles = array($newObjectName, $newImageName);
$this->setUploadFiles($uploadFiles);
}
public function alertMessage($message){
$alertMessage = "<script >bootbox.alert({ message: '";
$alertMessage = $alertMessage . $message;
$alertMessage = $alertMessage . "', callback: function(){location.href='../index.php';} })</script>";
echo $alertMessage;
}
//Getters and Setters
...
?>
Anyway, I'm new to PHP, wrote this code by myself to learn a bit, but can't work though this problem...Can someone tell me where's my mistake?
You can start by debugging what you get with print_r($_FILES);. Compare what you get when you upload the .dae file alone, and what you get when you upload both the .dae file and the image. Then you add a conditional logic to function uploadTheFiles() to skip trying to upload the image if one is not set.
I recently noticed on my website that users weren't able to upload profile pictures on mobile. So I copied all of the required HTML and PHP code from the root directory. The location where the profile pictures are moved was also modified so the pictures get uploaded to the right place. Now when I test it out and try to upload a profile picture using Safari for iOS, I get this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /home5/bobcatss/public_html/mobile/profile.propic.php on line 18
Here is the form the user submits:
<div class="propic"><form method="post" action="profile.propic.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Upload a profile picture <br><input name="file" type="file" id="file"/><br>
<input type="submit" value="Upload">
</form></div>
And this is the script that processes the image:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("../config.php");
session_start();
// Where the file is going to be placed
$target_path = "../propics/";
$filename = $_FILES["file"]["name"];
$limit_size=100000;
$temp = explode(".", $filename);
$extension = end($temp);
$info = getimagesize($_FILES["file"]["tmp_name"]); //Line 18
$allowed_types = array(IMG_GIF, IMG_JPEG, IMG_PNG, IMG_JPG);
if (in_array($info[2], $allowed_types))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
exit;
}
else
{
if (file_exists("../propics/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../propics/" . $_FILES["file"]["name"]);
try {
//insert into database
$stmt = $db->prepare('UPDATE users SET propic = :propic WHERE username = :username') ;
$stmt->execute(array(
':propic' => $filename,
':username' => $_SESSION["USER"]
));
//redirect to profile page
header("Location: profile.php?msg=Profile picture upload complete");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
}
else
{
echo "Invalid file";
}
?>
I emailed the image to myself and tried uploading it from my laptop but it gave me the same error.
I know this is old but this has just happened to me as well and I have bumped into this trying to figure out what happened. If you were using 3G connection the request may have taken longer than MAX_REQUEST_TIMEOUT so it probably failed ( duplicate here )
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'; ?>
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>';
}