I'm trying to create a php cropper based on other online tutorials but I keep coming up with errors and I can't understand what the actual errors mean. Here is my php code with the errors written in too:
<?php
include("settings.php");
$extension = end(explode(".", $_FILES["avatar"]["name"]));
$id = mysqli_real_escape_string($con, $_POST["id"]);
$time = time();
$avatarid= time().'-'.mt_rand(1000, 9999);
$avatar = mysqli_real_escape_string($con, $_POST["avatar"]);
$w= mysqli_real_escape_string($con, $_POST["w"]);
$h= mysqli_real_escape_string($con, $_POST["h"]);
$x= mysqli_real_escape_string($con, $_POST["x"]);
$y= mysqli_real_escape_string($con, $_POST["y"]);
$rw = 300;
$rh = 300;
$path = "../uploads/avatars/";
$unlink = "$path$avatar";
$newimage = "$path$avatar";
$insert_avatar_sql = "UPDATE members SET avatar = '".$avatarid.".".$extension."' WHERE id = '$id'";
$insert_avatar_res = mysqli_query($con, $insert_avatar_sql);
if(mysqli_affected_rows($con)>0){
unlink($unlink);
move_uploaded_file($_FILES["avatar"]["tmp_name"],"$path" . $avatarid . "." . $extension);
$wratio = ($rw/$w);
$hratio = ($rh/$h);
$newW = ceil($w * $wratio);
$newH = ceil($h * $hratio);
$newimg = imagecreatetruecolor($newW,$newH);
$ext=$extension;
if($ext=="jpg" || $ext=="jpeg" )
{
$source = imagecreatefromjpeg($newimage); // Warning: imagecreatefromjpeg(../uploads/avatars/1380641918-4496.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\AppServ\www\music.co.uk\php\avatar.php on line 34
}
else if($ext=="png")
{
$source = imagecreatefrompng($newimage);
}
else
{
$source = imagecreatefromgif($newimage);
}
imagecopyresampled($newimg,$source,0,0,$x1,$y1,$newW,$newH,$w,$h); // Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\AppServ\www\music.co.uk\php\avatar.php on line 44
uploads/1380642027-5994
imagejpeg($newimg,$path.$avatarid,90);
echo "uploads/".$avatarid;
exit;
header("Location: ../edit.php?page=profile");
}
else{
header("Location: ../404.php");
exit();
}
?>
Please help me with this, I've been messing with Avatar uploads for 3 days solid now and I want to get this done, even if I have to use a different php script
For your first error you're passing $newimage to imagecreatefromjpeg(). During this process $newimage does not have a value that imagecreatefromjpeg() can understand. So basically if $newimage is a file or directory, it's not valid so your problem is the value assigned to $newimage.(Make sure "../uploads/avatars/1380641918-4496.jpg" is valid) Not sure what to tell you on the second warning. Good Luck.
Related
I want to use PHP in GAE to upload file image files.
Before storing, I want to convert each file to JPEG and reduce it to thumbnail quality.
Using the following code (which fully works in a normal PHP environment, less the bucket-specific adjustments), I am able to receive the uploads and determine the temporary file name and location, but getimagesize produces an error when attempting to access the CloudStorage.
$bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$bucketPath = "gs://" . $bucket . "/" . $_SERVER["REQUEST_ID_HASH"] . "/";
$counter = 0;
foreach($_FILES["file"]["name"] as $idx => $tempFile) {
$counter++;
$sourceFile = $bucketPath . $tempFile;
syslog(LOG_DEBUG, $sourceFile);
$photoInfo = getimagesize($sourceFile);
if ($photoInfo["mime"] == "image/jpeg") {
$photoImage = imagecreatefromjpeg($sourceFile);
$valid = true;
}
elseif ($photoInfo["mime"] == "image/gif") {
$photoImage = imagecreatefromgif($sourceFile);
$valid = true;
}
elseif ($photoInfo["mime"] == "image/png") {
$photoImage = imagecreatefrompng($sourceFile);
$valid = true;
}
if (isset($valid)) {
$date = date("Y-m-d H:i:s");
$photoFolder = rtrim($photoFolder, "/") . "/";
$photoFile = "Test {$counter} {$date}.jpg";
$imageSaved = imagejpeg($photoImage, $photoFolder.$photoFile, 50);
syslog(LOG_DEBUG, "File saved is " . $imageSaved);
}
}
The first syslog entry confirms the file path and name...
gs://[myappid].appspot.com/AC3E3530/IMG_20160701_120144.jpg
The error log shows an error in attempting to open the stream, but I don't know how to address it.
PHP Warning: getimagesize(gs://[myappid].appspot.com/AC3E3530/IMG_20160701_120144.jpg): failed to open stream: "\google\appengine\ext\cloud_storage_streams\CloudStorageStreamWrapper::stream_open" call failed in /base/data/home/apps/s~[myappid]/v1.394746390020376247/code/server.php on line 169
I already have a variation of this functionality working on GAE with photos that my server receives through Twilio (where processPhoto() is a function identical to the code I excerpted above). In this case, I'm using getimagesize and imagecreate with a URL. I just don't know how to do the same with CloudStorage.
if ($fetch && $numMedia > 0) {
for ($x = 0; $x < $numMedia; $x++) {
$sourceFile = $_REQUEST["MediaUrl" . $x];
$sid = $_REQUEST["MessageSid"];
processPhoto("sms", $projectID, $sourceFile, $caption, $sid, $mobile, $message);
}
}
I think the problem was that the temporary file was removed before I could process it. So, I...
Removed the functionality of processing multiple files (which I
didn't need anyhow).
Immediately move the file to another bucket.
Examine the file for its type.
Save it as desired.
Remove the temporary file.
This is the form that I generate in PHP. There's no Submit button because I watch for a file change with jQuery.
<form id='form_uploadPhotos' method='post' enctype='multipart/form-data' action='{$websiteURL}?action=uploadPhotos'>
<input type='file' id='input_uploadPhoto' name='file'>
<input type='hidden' name='projectID' value='{$projectID}'>
</form>
This is the uploadPhotos function that's called when the form is submitted:
if ($action == "uploadPhotos") {
$projectID = preg_replace("/\D/", "", $_REQUEST["projectID"]);
$bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$bucketPath = "gs://" . $bucket . "/" . $_SERVER["REQUEST_ID_HASH"] . "/";
$date = date("Y-m-d H:i:s");
$time = time();
$photoFile = sprintf("%08d", $projectID) . "." . $date . "." . $time . ".TEMP";
$sourceFile = $photoFolder.$photoFile; // The default photo folder is defined elsewhere.
move_uploaded_file($_FILES["file"]["tmp_name"], $sourceFile);
processPhoto("upload", $projectID, $sourceFile, null, null, null, null);
}
This is the function that processes the photo. It's called by other processes that also receive photos (e.g., SMS attachments via Twilio).
function processPhoto($via, $projectID, $sourceFile, $caption, $twilioMessageID, $smsMobile, $smsMessage) {
global $photoFolder;
$photoInfo = getimagesize($sourceFile);
if ($photoInfo["mime"] == "image/jpeg") {
$photoImage = imagecreatefromjpeg($sourceFile);
$valid = true;
}
elseif ($photoInfo["mime"] == "image/gif") {
$photoImage = imagecreatefromgif($sourceFile);
$valid = true;
}
elseif ($photoInfo["mime"] == "image/png") {
$photoImage = imagecreatefrompng($sourceFile);
$valid = true;
}
if (isset($valid)) {
$date = date("Y-m-d H:i:s");
$time = time();
$photoFile = sprintf("%08d", $projectID) . "." . $date . "." . $time . ".JPEG";
$photoImage = imagecreatefromjpeg($sourceFile);
list($width, $height) = getimagesize($sourceFile);
if (max($width, $height) > 800) {
$scale = 800/max($width, $height);
$newWidth = floor($width * $scale);
$newHeight = floor($height * $scale);
$saveImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($saveImage, $photoImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
}
$imageSaved = imagejpeg($photoImage, $photoFolder.$photoFile);
imagedestroy($photoImage);
if ($imageSaved) {
if (isset($twilioMessageID)) {
$twilioMediaID = substr($sourceFile, strrpos($sourceFile, "/") + 1);
purgeTwilioMedia($twilioMessageID, $twilioMediaID);
}
elseif (substr($sourceFile, strrpos($sourceFile, ".")) == ".TEMP") {
unlink($sourceFile);
}
<Additional processing (e.g., adding entry to database.)
.
.
.
}
}
}
Note: The image scaling code between "list($width, $height..." and "imagecopyresampled..." is based on Dano's answer to another question.
I'm guessing that you're hitting a limitation of the Standard Environment where the getimagesize native function in the Standard runtime doesn't work with file extensions like gs:// URLs.
I have created a website that uploads anything. The problem I have is that I'm new to all this. I have tried every code that generates random strings but I have nothing. Here is the code anyway:
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")) {
echo '<a href="uploads/'.$fileName.'"><input type="button" class="button"
value="Download" /></a>';
} else {
echo "move_uploaded_file function failed";
}
?>
Could there be a way to generate random file names so that when someone uploads the same name as a file already on the server, it does not overwrite the existing file?
$fileName = "image_".uniqid();
The uniqid() function generates a unique ID based on the microtime
(current time in microseconds).
About uniqid function: http://www.php.net/manual/en/function.uniqid.php
You can use md5(microtime()) to get unique file name even you uploading more than one file at a time
you can use microtime time to make sure file name is unique.
$file_name = "custom_name_" . microtime();
Because a folder is limited to 65535 files, you need to create subfolders. This technique creates 3 subfolders (with 3 characters each) depending on the timestamp then creates a random filename.
For more randomness and future-proofness (because using time() and microtime() is weak if you have multiple users uploading at the same time) :
//Get the extension of the file
$fileExtension = end(explode(".", $_FILES['item']['name']));
$randOctalName = openssl_random_pseudo_bytes(5);
$randName = bin2hex($randOctalName).".".$fileExtension;
//Save it into uploads/123/456/789/
$path = "";
$timestamp = time();
$path = substr($timestamp,0,3)."/".substr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;$timestamp = time();
$path = substr($timestamp,0,3)."/".ubstr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;
_r_mkdir($relativePath);
And the mkdir recursive function :
private function _r_mkdir($path, $mode = 0755, $recursive = true)
{
if(empty($path)){
return false;
}
if($recursive) {
$toDo = substr($path, 0, strrpos($path, '/'));
if($toDo !== '.' && $toDo !== '..'){
_r_mkdir($toDo, $mode);
}
}
if(!is_dir($path)){
mkdir($path, $mode);
}
return true;
}
use the timestamp (or microtime), so you know it is necessarily different every time
$fileName = "image_".time();
TimeStamp
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Microtime
microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.
//you can use both random and time function to get more unique no count:
$fileName = 'mypic'.mt_rand(100000, 999999).'_'.time(). $_FILES["file1"]["name"];
use are:-
mt_rand(100000, 999999)// for randm no.
time()// for timestring
$_FILES["file1"]["name"]//also you can give your file name
Study this code thoroughly. This is all you need.
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "")
{
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileError = $_FILES["avatar"]["error"];
$kaboom = explode(".",$fileName);
$fileExt = end($kaboom);
list($width,$height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10)
{
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 5048576)
{
header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb");
exit();
}
else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) )
{
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
}
else if ($fileErrorMsg == 1)
{
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx,$sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != "")
{
$picurl = "../user/$log_username/$avatar";
if (file_exists($picurl))
unlink($picurl);
}
$moveResult = move_uploaded_file($fileTmpLoc,"../user/$log_username/$db_file_name");
if ($moveResult != true)
{
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../user.php?u=$log_username");
exit();
}
?>
try this
$now=date('d/m/y');
if(move_uploaded_file($fileTmpLoc, "uploads/$now.$fileName"))
it will add date infront of the filename
I have this piece of code that executes a multi image upload and renaming it.
it works, The file is renamed correctly, but I do not understand why in the mysql database I do not have the file extension but only the name.
Example:
file name (folder): abcdefg.jpg
pd_image (mysql field): abcdefg
$resultname is the same for both
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image);
$extension = end($parts);
$resultname = str_replace("." . $extension,"",$image);
$handle->file_new_name_body = $resultname;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 800;
$handle->image_y = 600;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (pd_id, file_name, pd_image) VALUES('$pd_id','$mainame','$resultname')";
$result2 = dbQuery($query_img);
I am using the class "class.upload.php"
Check this line, You are replacing the extension with the "".
$resultname = str_replace("." . $extension,"",$image);
Replace this line to
$resultname = $image.'.'.$extension;
your are giving variable $db_name as string.Correct way to concatenate the variable to another string is
$image = md5(rand() * time()).$db_name;
I've run into a conundrum and was wondering if anyone might be able to give me a straight answer. So I built a photo upload script using PHP/MySQL. Within the script photos are re-sized and given a temporary name while being uploaded. I tested it using several pictures (file size 220 KB | 960 x 720) and everything was working just fine. Then I attempted to upload several pictures from my digital camera (file size 2.47 MB | 3000 x 4000) and all of a sudden I got this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in /php_parsers/photo_system.php on line 94
Warning: Cannot modify header information - headers already sent by (output started at /php_parsers/photo_system.php:94) in /php_parsers/photo_system.php on line 96
I checked stackoverflow for a post with a similar issue and came upon one however it didn't seem to apply to the scenario I'm experiencing.
Here is the applicable code for "photo_system.php". I have commented the offending lines 94 and 96. Any help/ideas you could give would be greatly appreciated!
<?php
if (isset($_FILES["photo"]["name"]) && isset($_POST["gallery"])){
$sql = "SELECT COUNT(id) FROM photos WHERE user='$log_username'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] > 79){
header("location: ../message.php?msg=The system allows only 80 pictures total");
exit();
}
$gallery = preg_replace('#[^a-z 0-9,]#i', '', $_POST["gallery"]);
$fileName = $_FILES["photo"]["name"];
$fileTmpLoc = $_FILES["photo"]["tmp_name"];
$fileType = $_FILES["photo"]["type"];
$fileSize = $_FILES["photo"]["size"];
$fileErrorMsg = $_FILES["photo"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
$db_file_name = date("DMjGisY")."".rand(1000,9999).".".$fileExt; // WedFeb272120452013RAND.jpg
list($width, $height) = getimagesize($fileTmpLoc); //Offending Line 94
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions"); //Offending Line 96
exit();
}
if($fileSize > 4194304) {
header("location: ../message.php?msg=ERROR: Your image file was larger than 4mb");
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
exit();
} else if ($fileErrorMsg == 1) {
header("location: ../message.php?msg=ERROR: An unknown error occurred");
exit();
}
$moveResult = move_uploaded_file($fileTmpLoc, "../user/$log_username/$db_file_name");
if ($moveResult != true) {
header("location: ../message.php?msg=ERROR: File upload failed");
exit();
}
include_once("../php_includes/image_resize.php");
$wmax = 800;
$hmax = 600;
if($width > $wmax || $height > $hmax){
$target_file = "../user/$log_username/$db_file_name";
$resized_file = "../user/$log_username/$db_file_name";
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
}
$sql = "INSERT INTO photos(user, gallery, filename, uploaddate) VALUES ('$log_username','$gallery','$db_file_name',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
header("location: ../photos.php?u=$log_username");
exit();
}
?><?php
if (isset($_POST["delete"]) && $_POST["id"] != ""){
$id = preg_replace('#[^0-9]#', '', $_POST["id"]);
$query = mysqli_query($db_conx, "SELECT user, filename FROM photos WHERE id='$id' LIMIT 1");
$row = mysqli_fetch_row($query);
$user = $row[0];
$filename = $row[1];
if($user == $log_username){
$picurl = "../user/$log_username/$filename";
if (file_exists($picurl)) {
unlink($picurl);
$sql = "DELETE FROM photos WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
mysqli_close($db_conx);
echo "deleted_ok";
exit();
}
?>
OK everyone. I figured out what the issue was. Hopefully this will help someone in the future. So I checked my phpinfo() and found that upload_max_filesize was only set to 2M. I added php.ini to the directory of the offending file and included:
upload_max_filesize = 250M
post_max_size = 250M
max_execution_time = 300
date.timezone = "America/Los_Angeles"
I had to add the date.timezone because my system didn't like the fact that I didn't have it defined. Anyway this has resolved the issue.
i have a upload script and that works fine, but i want that its upload twice, one orginal format and one in a thubm size.
I did allready search on google and stackoverflow and i tried allready something, but i dont get it work.
My upload script
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
include('./../includes/core.php');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Alleen '.implode(',',$allowed_ext).' bestanden zijn toegestaan');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
$name = $pic['name'];
$sname = hashing($name);
$datum = date("d-m-Y");
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$sname)){
mysql_query("INSERT INTO foto VALUES ('','".$pic['name']."','".$sname."', '".$datum."', '0')");
exit_status('Bestand succesvol geupload');
}
}
exit_status('Er is iets mis gegaan!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function hashing($naam){
$info = pathinfo($naam);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$hash = basename($naam, $ext);
$hash = $hash . genRandomstring();
$hash = md5($hash);
$hash = $hash . '-' . genRandomstring();
return $hash . $ext;
}
function genRandomString() {
$length = 5;
$string = "";
$characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-+!#"; // change to whatever characters you want
while ($length > 0) {
$string .= $characters[mt_rand(0,strlen($characters)-1)];
$length -= 1;
}
return $string;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
If someone can help me? I will be very happy then becuase i have allready try this for a week and i can get it out.
Thanks, Chris
You have the image uploaded once, which is all you need, then use that to create the second thumbnail file.
Try looking over the GD documentation.
as mentioned before you don't need to upload twice, copy and resize image once it's uploaded like this:
$pathToImages = "path/to/images"
$pathToThumbs = "path/to/thumbs"
$fname = "image-file-name";
$new_fname = "thumb-file-name";
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
$thumbWidth = //someValue//;
$thumbHeight = //someValue//;
// calculate thumbnail size
$new_height = floor($height * ($thumbWidth/$width));
$new_width = $thumbWidth;
// create a new temporary image
$tmp_img = imagecreatetruecolor($thumbWidth, $thumbHeight);
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width,$new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$new_fname}" );