2016-12-21 3 views
-2

Я хочу изменить изображение профиля пользователя, когда они нажмут изображение профиля изменения, но оно не работает. Noe ошибки или что-то просто не работает. Я хотел бы изменить изображение профиля в JavaScript или PHPИзменение профиля профиля пользователя PHP

profile.php:

<form id="form2" action="upload.php" method="post" enctype="multipart/form-data"> 
<p id="p1">Change profile picture:</p> <br /> 
<input type="file" name="fileToUpload" id="fileToUpload"><br /> 
<br><input id="sub1" type="submit" value="Change profile picture" name="submit"><br /> 
</form> 

upload.php:

<?php 

$target_dir = "C:\wamp\www\TestSocialNetwork\uploads"; 
//This is the directry where the images will be uploaded, "server_path/uploads" 

//Now since we have the target directory, let's define the actual path. 
//Actual Path = Target Dir + File Name + File Extension 

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 

//By now, we have just madefined locations, (in the form of Variables) 

//Now, lets do few checks, and make a success flag to keep a track 
$uploadOk = 1; 

// Check if file already exists 
if (file_exists($target_file)) { 
//If the file already exists 
echo "Sorry, file already exists."; 
$uploadOk = 0; 
//Echo and change the flag to False 
} 

// Check if image file is a actual image or fake image. 
//If file is image, then only image size will be returned 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
if(!($check)) { 
//That is, the Check is false, the file is NOT AN IMAGE 
echo "File is not an image."; 
$uploadOk = 0; 
//Echo, and change the Flag to false. 
} 

//Now check, if the flag is true, that means upload is OK, and NO ERRORS. 
//Then upload the file. 
if ($uploadOk) { 
//If upload is OK, then go ahead 
move_uploaded_file($_FILES['image']['tmp_name'], $target_file); 
// Move the uploaded file to the desired folder 
} 
?> 
+1

Как ваш HTML знает, где найти изображение для отображения? Фактическое изображение отсутствует в ваших образцах кода. Из того, что я вижу, этот метод не внесет изменений до тех пор, пока страницы не будут обновлены. – ToothlessRebel

ответ

0

Вам нужно перезагрузить страницу после успешной загрузки в порядке чтобы отразить изменения, вы можете использовать PHP header() для этого, то есть:

if ($uploadOk) { 
    //If upload is OK, then go ahead 
    // Move the uploaded file to the desired folder 
    move_uploaded_file($_FILES['image']['tmp_name'], $target_file); 
    header("Location: https://the user profile url"); 
} 

Вы также можете использовать заголовки html или php, чтобы запретить кешировать на странице на странице профиля пользователя.

PHP пример не-кэш:

header("Cache-Control: no-store, no-cache, must-revalidate"); 

html5 не пример нет кэша:

<!DOCTYPE html> 
<html manifest="manifest.appcache"> 

Затем создайте manifest.appcache с таким содержанием:

CACHE MANIFEST 
# Cache manifest version 1.0 
# no cache 
NETWORK: 
* 

SRC


PS:

одно важное дополнение, что вы никогда не может заставить браузер делать ничего. Все, что вы можете сделать, это сделать дружеские предложения. Это зависит от браузера и от пользователя, чтобы действительно следовать этим предложениям. Браузер может игнорировать это, или пользователь может переопределить значения по умолчанию.

SRC

+0

Я только что сделал, и я получил эту ошибку 'Undefined index: image on line 39' –

+0

строка 40' move_uploaded_file ($ _ FILES ['image'] ['tmp_name'], $ target_file); ' –

+0

Ошибка в строке 40 не 39 –

Смежные вопросы