I'm trying to implement a small update profile pic form.
<form method="post" action="<?php echo $filename;?>" name="change_picture_form" id="change_picture_form" enctype="multipart/form-data">
<input type="hidden" name="action" value="change_picture" />
<input type="file" name="new_user_picture">
<input type="submit" class="submitButton" value="Save Changes"/>
</form>
The target php file has the following code:
echo $_FILES['new_user_picture']['size']." ";
echo $_FILES['new_user_picture']['tmp_name']." ";
echo $_FILES['new_user_picture']['name']." ";
echo $_FILES['new_user_picture']['error']." ";
echo $_FILES['new_user_picture']['type']." ";
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"];
if( is_uploaded_file( $picture_uploaded ) ) {
$imagesize = getimagesize( $picture_uploaded );
switch( $imagesize[2] ) {
case IMAGETYPE_PNG:
$extension = '.png';
echo "<script>console.log('Reached here!!')</script>";
try {
$image_original = imagecreatefrompng( $picture_uploaded );
if (!$image_original)
echo '<script>console.log("not image original")</script>';
} catch(Exception $e) {
echo "<script>console.log('Error!!')</script>";
}
break;
case IMAGETYPE_JPEG: ....
...
}
}
Here, I have similar code for many image types. I tested this code by trying to uploading a png image. The first 5 echo statements display expected results - the size, error value of zero, the name, the type and the temp name.
I get "Reached here!!" on my console.
imagecreatefrompng, however, seems to crash silently. Try-catch somehow doesn't seem to catch the error.
Help? Thanks!
I haven't handled file uploads in PHP in forever, but is it possible that this line:
$picture_uploaded = $_FILES["new_user_picture"]["tmp_name"]
should be
$picture_uploaded = $_FILES["new_user_picture"] ?
The first line, as is, should be getting you the uploaded file's file name, whereas the second line (the edited line above) should be a reference to the file itself.
HTH.
EDIT: Well, seeing as how my answer is incorrect... does this help? http://www.php.net/manual/en/function.imagecreatefromstring.php
. There's a helper function in the user notes/comments that might simplify what you're doing
Related
I have a problem in using $_FILES and $_POST at the same the because I have a form to upload an image and some data bus when I use one of them it works but when I used the other one id doesn't work.
my code is :
<?php
include 'debugging.php';
//phpinfo();
echo '<br />';
echo '<h1>Image Upload</h1>';
//create a form with a file upload control and a submit button
echo <<<_END
<br />
<form method='post' action='uplaodex.php' enctype='multipart/form-data'>
Select File: <input type='file' name='picName' size='50' />
name: <input type='text' name='usName' size='50' />
username : <input type='text' name='usUsername' size='50' />
pass: <input type='password' name='usPass' size='50' />
email: <input type='text' name='usEmail' size='50' />
<br />
<input type='submit' value='Upload' />
<input type="hidden" name="submit" value="1" />
</form>
<br />
_END;
//above is a special use of the echo function - everything between <<<_END
//and _END will be treated as one large echo statement
//$_FILES is a PHP global array similar to $_POST and $_GET
if (isset($_FILES['picName'])and isset($_POST['submit'])) {
//we access the $_FILES array using the name of the upload control in the form created above
//
//create a file path to save the uploaded file into
$name = "images//" . $_FILES['picName']['name']; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if (move_uploaded_file($_FILES['picName']['tmp_name'], $name)) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
//we are going to store the file type and the size so we get that info
$type = $_FILES['picName']['type'];
$size = $_FILES['picName']['size'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//select the ID of the image just stored so we can create a link
//display success message
echo "<h1> Thankyou </h1><p>Image stored successfully</p>";
//this above line of code displays the image now stored in the images sub directory
echo "<p>Uploaded image '$name'</p><br /><img src='$name' height='200' width='200'/>";
//create alink to the page we will use to display the stored image
echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
} else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
}
} else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
echo "</body></html>";
?>
I don't know what is the problem, any help??
Everything inside that if (isset($_FILES['picName'])and isset($_POST['submit'])) doesn't work because the superglobal $_FILES is probably not having a key named picName. To check this out, try var_dump-ing the $_FILES, like var_dump($_FILES);
By the output of the var_dump you'd get to know if there is any content inside $_FILES. And if it is populated, just see what the key name is and, access the file by using that key.
But if the array is empty, there may be some mis-configurations in PHP, or APACHE.
One possible fix would be setting file_uploads = On in the ini file for php.
Hope it helps!
You have to validate the size of the file if you want to do an isset. I don't know if this is works, but the better way for do that is check first the size for validate if isset or was send to the server.
Then, in your <form method='post' action='uplaodex.php' enctype='multipart/form-data'> you have to create another PHP file with the name uplaodex.php where you'll send al the data. So, your code with be like the below code following and considering the step 1. This will be your uploadex.php
$name_file = $_FILES['picName']['name'];
$type = $name_file['type'];
$size = $name_file['size'];
$tmp_folder = $name_file['tmp'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
if ( $size > 0 ) {
//REMOVE another slash images//
$name = "images/" . $name_file; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if ( move_uploaded_file($tmp_folder, $name) ) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//USE PRINTF
printf('<h1> Thankyou </h1><p>Image stored successfully</p><br>
<p>Uploaded file: %s</p>. <img src="%s" height="200" width="200" />',
$name_file, $name );
#WHAT IS $fileId? In which moment was define?
//echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
}
else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
} //ENDIF OF if (move_uploaded_file($_FILES['picName']['tmp_name'], $name))
} //ENDIF OF if ( $size > 0 )
#ELSE OF YOUR if ( $size > 0 )
else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
I solved the problem, you can't perform $_FILES and $_post at the same time or one of them inside the other.
start with $_Post and then $_FILES and outside the $_FILES run your saving function
thats it
so far I've successfully moved an uploaded image to its designated directory and stored the file path of the moved image into a database I have.
Problem is, however, is that the img src I have echoed fails to read the variable containing the file path of the image. I've been spending time verifying the validity of my variables, the code syntax in echoing the img src, and the successful execution of the move/storing code, but I still get <img src='' when I refer to the view source of the page that is supposed to display the file path contained in the variable.
I believe the file path is stored within the variable because the variable was able to be recognized by the functions that both moved the image to a directory and the query to database.
My coding and troubleshooting experience is still very adolescent, thus pardon me if the nature of my question is bothersomely trivial.
Before asking this question, I've searched for questions within SOF but none of the answers directly addressed my issue (of the questions I've searched at least).
Main PHP Block
//assigning post values to simple variables
$location = $_POST['avatar'];
.
.
.
//re-new session variables to show most recent entries
$_SESSION["avatar"] = $location;
.
.
.
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
//define variables relevant to image uploading
$type = explode('.', $_FILES["avatar"]["name"]);
$type = $type[count($type)-1];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//check image size
if($_FILES["avatar"]["size"] > 6500000) {
echo"Image must be below 6.5 MB.";
unlink($_FILES["avatar"]["tmp_name"]);
exit();
}
//if image passes size check continue
else {
$location = "user_data/user_avatars/$rdn/".uniqid(rand()).'.'.$type;
mkdir("user_data/user_avatars/$rdn/");
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else {
$location = "img/default_pic.jpg";
}
HTML Block
<div class="profileImage">
<?php
echo "<img src='".$location."' class='profilePic' id='profilePic'/>";
?><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
View Source
<div class="profileImage">
<img src='' class='profilePic' id='profilePic'/><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
Alright, I've finally found the error and was able to successfully solve it!
Simply declare a avatar session variable to the $location variable after updating the table, update the html insert by replacing all $location variables with $_SESSION["avatar_column"] and you are set!
PHP:
$updateCD = "UPDATE users SET languages=?, interests=?, hobbies=?, bio=?, personal_link=?, country=?, avatar=? WHERE email=?";
$updateST = $con->prepare($updateCD);
$updateST->bind_param('ssssssss', $lg, $it, $hb, $bio, $pl, $ct, $location, $_SESSION["email_login"]);
$updateST->execute();
$_SESSION["avatar"] = $location; //Important!
if ($updateST->errno) {
echo "FAILURE!!! " . $updateST->error;
}
HTML:
<div class="profileImage">
<?php
$_SESSION["avatar"] = (empty($_SESSION["avatar"])) ? "img/default_pic.jpg" : $_SESSION["avatar"] ;
echo "<img src='".$_SESSION["avatar"]."' class= 'profilePic' id='profilePic'> ";
?>
.
.
.
Thank you!
try this code
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$location = ""; //path
if($_POST && $_FILES)
{
if(is_uploaded_file())
{
// your code
if(<your condition >)
{
}
else
{
$location = "./user_data/user_avatars/".$rdn."/".uniqid(rand()).'.'.$type;
if(!is_dir("./user_data/user_avatars/".$rdn."/"))
{
mkdir("./user_data/user_avatars/".$rdn."/",0777,true);
}
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else
{
$location = "img/default_pic.jpg";
}
}
?>
Html Code :-
<div>
<?php
$location = (empty($location)) ? "img/default_pic.jpg" : $location ;
echo "<img src='".location."' alt='".."'> ";
?>
</div>
If it helpful don't forget to marked as answer so another can get correct answer easily.
Good Luck..
I'm working on a function to upload images to my website fileserver and at the same time would create a thumb preview and create an entry to my mysql database. So long the function to upload_image() is working, it uploads the image and creates a thumb perfectly.
The issue is, that when I click the submit button to upload the image selected, the PHP function do its job but will return a BLANK PAGE. Yes, I know, "another blank page of death question, go find all the other 53 posts related to this question and find a solution" right? Well, it's not that simple.
I have tried every single method in those questions and another bunch that I've found over this forsaken place called internet and nothing works for me, I always get the same Blank Page of death with no warning or error.
What have I tried would you ask? The following would just represent a relevant set of solutions that I recall:
Configuring PHP.INI's options for error: DONE. Even creating the log file for every single detailed error.
Overriding PHP.INI's options from the php file function with the settings: DONE. Also I have used a script from some answers that override error log protocol.
Place an exit('wtf') function from start to bottom to see if its an Syntax error or an error on a certain line: DONE. Every single line will print WTF on the god forsaken Blank Page.
Well, there are other solutions I have tried, be my guest and offer some answers and I would tell you if I have already tried it.
Lets get to it then. My HTML code that calls the php file is:
<form action="assets/php/image_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="fileToUpload">
</br>
</br>
<input type="text" name="title" value="Titulo" size="64">
<br>
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
And my image_uploader.php code is:
<?php
function upload_image()
{
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
$name = "image_" . date('Y-m-d-H-i-s') . "_" . uniqid() . ".jpg";
$type= $_FILES["myfile"]["type"];
$size= $_FILES["myfile"]["size"];
$temp= $_FILES["myfile"]["tmp_name"];
$error= $_FILES["myfile"]["error"];
if ($error > 0)
{
die("Error uploading file! code $error.");
}
else
{
if($type=="image/png" || $size > 2000000)//condition for the file
{
die("Format not allowed or file size too big!");
}
else
{
if(move_uploaded_file($temp, $root . "/images/fulls/" . $name))
{
list($ancho, $alto) = getimagesize($root . "/images/fulls/" .$name);
$nuevo_alto = 212;
$nuevo_ancho = 212;
$dx = 0;
$dy = 0;
$sx = 0;
$sy = 0;
if($ancho == $alto)
{
}
else
{
if($ancho > $alto)
{
$nuevo_ancho = $ancho * (212/$alto);
}
else
{
$sy = $alto/2 - $nuevo_alto/2;
$alto = $ancho;
}
}
$thumb = imagecreatetruecolor($nuevo_ancho, $nuevo_alto);
$origen = imagecreatefromjpeg($root . "/images/fulls/" .$name);
imagecopyresampled($thumb, $origen, $dx, $dy, $sx, $sy, $nuevo_ancho, $nuevo_alto, $ancho, $alto);
imagejpeg($thumb, $root . "/images/thumbs/" .$name);
imagedestroy($thumb);
echo "The file ". basename( $_FILES["myfile"]["name"]). " has been uploaded.";
}
}
}
}
if(isset($_POST['submit']))
{
upload_image();
}
?>
try this:
$new_file = $root . "/images/fulls/" . $name;
copy($temp, $new_file);
if(!is_file($new_file)) {
die('cannot copy file');
}
also wrap main part with:
try{
}
catch(Exception $ex) {die('['.$ex->getLine().'] '.$ex->getMessage());}
Placed the code into the HTML file which was renamed later to have the extension .php and called the function in the form section as:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="fileToUpload">
</br>
</br>
<input type="text" name="title" value="Titulo" size="64">
<br>
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
And now it works as if it was magic, I do not know if htmlspecialchar() function has anything to do with it, but now the code works with no errors. Therefore I would post this as an answer but reminding you to not consider this as a solution to the BLANK PAGE death screen.
I have two files, one to upload an image and another to retrieve it from the database and present it on the web page. However the image only appears as broken image icon. I do not understand why.
Thanks for any help in advance.
The HTML form:
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
The php to upload it(The connection to the DB is left out below but it works perfectly):
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image";
else {
$image=addslashes(file_get_contents($_FILES['image']['tmp_name']));
$imageName=addslashes($_FILES['image']['name']);
$imageSize=getimagesize($_FILES['image']['tmp_name']);
if(!$imageSize)
echo "Thats not an image you mong";
else {
//upload
$query="INSERT INTO store VALUES('','$imageName','$image')";
$sendQuery=mysql_query($query);
if(!$sendQuery)
echo "This is embarressing. It didn't work";
else {
$lastid=mysql_insert_id();
echo "Image was uploaded. <br>Your image:";
echo "<img src=get.php?id=$lastid/>";
}
}
}
The PHP to retrieve the image(Again the DB connection is left out below but works perfectly):
$id=addslashes($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
Make sure the the opening php tag is the very first line of the file. If the opening php tag is not on the first line of the file then content has already been written to the response causing calls to the header() function to be ignored.
<?php // this has to be on line 1
// do database connections stuff, no output can be sent to the response.
$id=addslashes($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
Maybe one of the magic quote setting (magic_quotes_gpc), try:
$image=stripslashes($image['image']);
You should be using mysql_real_escape_string() instead of addslashes() and only if magic quotes are not enabled.
I have a folder where I keep my images, named img/. I have a table with all of my images:
<table border="3">
<tr>
<td>
<?php
$files = glob("img/*");
foreach ($files as $file) {
echo "<div class='divimages'>";
echo '<img src="'.$file.'"/>';
echo "<input type='submit' value='Delete image'/><br>";
echo "</div>";
}
?>
</td>
</tr>
</table>
How can I delete the image associated to the button with the value:"Delete image".
There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink
DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.
Each image's display markup would contain a form something like this:
echo '<form method="post">';
echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
echo '</form>';
...and at at the top of that same PHP file:
if (array_key_exists('delete_file', $_POST)) {
$filename = $_POST['delete_file'];
if (file_exists($filename)) {
unlink($filename);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
// existing code continues below...
You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.
Documentation and Related Reading
unlink - http://php.net/manual/en/function.unlink.php
$_POST - http://php.net/manual/en/reserved.variables.post.php
file_exists - http://php.net/manual/en/function.file-exists.php
array_key_exists - http://php.net/manual/en/function.array-key-exists.php
"Using PHP With HTML Forms" - http://www.tizag.com/phpT/forms.php
You can delete files in PHP using the unlink() function.
unlink('path/to/file.jpg');
First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
For deleting use http://www.php.net/manual/en/function.unlink.php
Hope you'll can to write logic?
You can try this code. This is Simple PHP Image Deleting code from the server.
<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>
<?php
if (isset($_POST['submit']))
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
{
echo ("Error deleting $photoname");
}
else
{
echo ("Deleted $photoname");
}
}
?>
<?php
require 'database.php';
$id = $_GET['id'];
$image = "SELECT * FROM slider WHERE id = '$id'";
$query = mysqli_query($connect, $image);
$after = mysqli_fetch_assoc($query);
if ($after['image'] != 'default.png') {
unlink('../slider/'.$after['image']);
}
$delete = "DELETE FROM slider WHERE id = $id";
$query = mysqli_query($connect, $delete);
if ($query) {
header('location: slider.php');
}
?>
<?php
$path = 'img/imageName.jpg';
if (is_file($path)) {
unlink($path);
} else {
die('your image not found');
}