PHP: file_exist errors preventing show entire page - php

I got an error when handling a not seated avatar image, 0.jpg is a default user avatar and every user had an avatar called firstname_lastname.jpg
<?php
$uname_ = 'John_Doe';
$avname = "media/avatars/" . $uname_ . '.jpg';
if(file_exists($avname) {
$avatar = $uname_ ;
} else {
$avatar = "0" ;
}
?>
<img src="media/avatars/<?php echo $avatar ?>.jpg">
This does't work, and is preventing the page to show. I get a blank response.

you got this
if(file_exists($avname) {
need this
if(file_exists($avname)) {

Related

I have created a form where i can upload image but i have problem.while displaying it . I jave written the codes below

if(isset($_POST['submit'])
{
if(!file_exists("Uploads"))
{
makdir("Uploads/");
}
$base=basename($_FILES['image']['name']);
$file_path="Uploads/".$base;
if(file_exists($file_path))
{
$err[]="File already exist";
$uploadOk=0;
}
else
{
$uploadOk=1;
move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
}
if($uploadOk ==1)
{
?>
" height="100" width="100">
}
}
Check the directory where you are uploading the image and confirm its same directory from where you are trying to fetch image.
It look like that you have given incorrect image path for loading image try to debug it with pressing F12 in your browser (chrome) if it is showing error in console tab than the path you are giving is incorrect.

How to Prevent Form Resubmission when page is refreshed or back button is clicked

On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code
developerUpload.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
echo '<br><h3 style="color:red;">File(s) were already submitted! Please re-name file or select a different file...</h3>';
}
if(isset($_COOKIE['username'])){
if($_SERVER['REQUEST_METHOD'] =="POST"){
$price = addslashes(trim($_POST['price']));
$description = addslashes(trim($_POST['description']));
if(!empty($price) && !empty($description)){
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
echo '<br>'.$userid;
$pack_id = rand();
//Check file 1
if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){
$file1 = null;
}else{
$target1 = "devFiles/";
$target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
$file1 = addslashes(trim($_FILES['file1']['tmp_name']));
}
//Check file 2
if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){
$file2 = null;
}else{
$target2 = "devFiles/";
$target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
$file2 = addslashes(trim($_FILES['file2']['tmp_name']));
}
//Check file 3
if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){
$file3 = null;
}else{
$target3 = "devFiles/";
$target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
$file3 = addslashes(trim($_FILES['file3']['tmp_name']));
}
//Check file 4
if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){
$file4 = null;
}else{
$target4 = "devFiles/";
$target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
$file4 = addslashes(trim($_FILES['file4']['tmp_name']));
}
//Check file 5
if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){
$file5 = null;
}else{
$target5 = "devFiles/";
$target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
$file5 = addslashes(trim($_FILES['file5']['tmp_name']));
}
//Check video
if($_FILES['video']['error'] !== UPLOAD_ERR_OK){
$video = null;
$videoName = null;
}else{
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
$video = addslashes(trim($_FILES['video']['tmp_name']));
$videoName = addslashes(trim($_FILES['video']['name']));
}
if(file_exists($target_file1)
or file_exists($target_file2)
or file_exists($target_file3)
or file_exists($target_file4)
or file_exists($target_file5)
or file_exists($target_file)){
header("Location: developerUpload.php?invalid");
exit;
}
if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
&& move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
&& move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
&& move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
&& move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
&& move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
header("Location: submission_successful.php?");
die();
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
}
}
}else {
header("Location: developerLogin.php");
}
?>
submission_successful.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
header("Location: developerUpload.php?invalid");
}
if(isset($_COOKIE['username'])){
echo '<br><h1 style="color:red; text_align:center;">Thank You for Submitting!</h1>';
}else{
header("Location: developerLogin.php");
}
?>
I was searching around for days and finally found something. IF you use a HTML command it will remove any input the user put when the user goes back. Because my problem was when the user goes back after be redirected, their information was still there but if you use
<form method="post" enctype="multipart/form-data" autocomplete="off">
it removes everything so it kinda helps. The user will still be allowed to go back but at least now they can't resubmit the data.
Not sure whether you can check if a value exists twice in the database (thus preventing multiple submissions), but you could block users from submitting the form too frequently. Create a timestamp that gets saved upon first submission, and if the second resubmission's timestamp is not too far(big) from the first one, you could try sth like (you are submitting too frequently), or you could use ajax, or this https://es.m.wikipedia.org/wiki/Post/Redirect/Get
Use a session variable like this
$_SESSION["post_id"] = "";
if($_POST) {
if($_POST["post_id"] != $_SESSION["post_id"]) {
$_SESSION["post_id"] = $_POST["post_id"];
// do database submission here
}
}
This sets a session variable and if they resubmit the form it won't post the data twice.

Cant get Steam API to show avatar upon Login

I have used this tutorial to implement the steam login for a website I am creating: https://github.com/SmItH197/SteamAuthentication/blob/f47fc78056081d6a83d277ae447c5386dc0909fc/README.md . Problem is, when I log in, it does not display any info, only a logout button. Here is the code I am dealing with.
if(isset($_SESSION['steamid'])){
include("settings.php");
if (empty($_SESSION['steam_uptodate']) or $_SESSION['steam_uptodate'] == false or empty($_SESSION['steam_personaname'])) {
//We mute alerts from the following line because we do not want to give away our API key in case file_get_contents() throws a warning.
# $url = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=".$steamauth['apikey']."&steamids=".$_SESSION['steamid']);
if($url === FALSE) { die('Error: failed to fetch content form Steam. It may be down. Please, try again later.'); }
$content = json_decode($url, true);
$_SESSION['steam_steamid'] = $content['response']['players'][0]['steamid'];
$_SESSION['steam_communityvisibilitystate'] = $content['response']['players'][0]['communityvisibilitystate'];
$_SESSION['steam_profilestate'] = $content['response']['players'][0]['profilestate'];
$_SESSION['steam_personaname'] = $content['response']['players'][0]['personaname'];
$_SESSION['steam_lastlogoff'] = $content['response']['players'][0]['lastlogoff'];
$_SESSION['steam_profileurl'] = $content['response']['players'][0]['profileurl'];
$_SESSION['steam_avatar'] = $content['response']['players'][0]['avatar'];
$_SESSION['steam_avatarmedium'] = $content['response']['players'][0]['avatarmedium'];
$_SESSION['steam_avatarfull'] = $content['response']['players'][0]['avatarfull'];
$_SESSION['steam_personastate'] = $content['response']['players'][0]['personastate'];
if (isset($content['response']['players'][0]['realname'])) {
$_SESSION['steam_realname'] = $content['response']['players'][0]['realname'];
} else {
$_SESSION['steam_realname'] = "Real name not given";
}
$_SESSION['steam_primaryclanid'] = $content['response']['players'][0]['primaryclanid'];
$_SESSION['steam_timecreated'] = $content['response']['players'][0]['timecreated'];
$_SESSION['steam_uptodate'] = true;
}
$steamprofile['steamid'] = $_SESSION['steam_steamid'];
$steamprofile['communityvisibilitystate'] = $_SESSION['steam_communityvisibilitystate'];
$steamprofile['profilestate'] = $_SESSION['steam_profilestate'];
$steamprofile['personaname'] = $_SESSION['steam_personaname'];
$steamprofile['lastlogoff'] = $_SESSION['steam_lastlogoff'];
$steamprofile['profileurl'] = $_SESSION['steam_profileurl'];
$steamprofile['avatar'] = $_SESSION['steam_avatar'];
$steamprofile['avatarmedium'] = $_SESSION['steam_avatarmedium'];
$steamprofile['avatarfull'] = $_SESSION['steam_avatarfull'];
$steamprofile['personastate'] = $_SESSION['steam_personastate'];
$steamprofile['realname'] = $_SESSION['steam_realname'];
$steamprofile['primaryclanid'] = $_SESSION['steam_primaryclanid'];
$steamprofile['timecreated'] = $_SESSION['steam_timecreated'];
}
What I want to happen is when someone logs in, where the sign in button was, I want to show the steam name as well as the avatar of whoever signed in.
Did you read the documentation? To show avatar, do the following:
$steamprofile['avatar'] // 32x32 version of avatar
$steamprofile['avatarmedium'] // 64x64 version of avatar
$steamprofile['avatarfull'] // 184x184 version of avatar
To display the Steam username, do the following:
$steamprofile['personaname']
It's all written in the README.md file at the bottom.
EDIT: If you want to show the image, do something like this:
echo '<img src="' . $steamprofile['avatar'] . '" />';
That will put the image URL from $steamprofile['avatar'] into an <img> element.

Don't Display Photo if Not Found

I'm developing a browser extension (content script) that scans and highlights certain words on a page, and uses AJAX and PHP to echo back content into a tooltip that appears when a user hover over said words. One thing that gets echoed back from the PHP file is an image, but my problem is that I don't have an image for every keyword - what I want is the PHP to only echo back an image when one exists at the given URL. As of now, certain words show images, others show the "image not found" icon. What I want is for no "image not found" icon if the image doesn't exist.
I have the AJAX send the variable ($data) to the PHP files hosted on my website. Maybe have it check the HTTP header of the url before echoing?
Here is my code:
$data = $_POST['id'];
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
Why don't you just check it like this?
$data = $_POST['id'];
if($data !== "") {
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "http://extension.nicholasrub.in/headshots/notFound.png'>";
}
EDIT:
Use file_exists():
$data = $_POST['id'];
$imagePath = "/path/images/" . $data . ".png";
if (file_exists($imagePath)) {
echo "http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "http://extension.nicholasrub.in/headshots/notFound.png'>";
}
You can check if a file exists using this function
http://php.net/manual/en/function.file-exists.php
if you want to check image what is not exist on your server then use this code:
$data = $_POST['id'];
$imagePath = "http://extension.nicholasrub.in/headshots/$data.png";
echo "http://extension.nicholasrub.in/headshots/".(file_get_contents(imagePath) ? $data : 'notFound').".png'>"
I ended up solving the problem by checking whether the HTTP headers were 404 or not.
My Code:
$file = "http://extension.nicholasrub.in/headshots/" . $data . ".png";
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
if ($exists == true) {
echo "<div id='my-tooltip-2986234'><div><img src='http://extension.nicholasrub.in/headshots/" . $data . ".png'>";
}
else {
echo "<div id='my-tooltip-2986234'><div>";
}

User uploading images to specific directories

So basically I have a site in which certain members are allowed to upload images (comic pages) to their own image galleries (to a specific comic). I have a successful image uploading script that I used to upload profile/avatar images for each member, but now that I want to upload files to a more specific place I'm having a little trouble.
Here's what I have so far:
(This is what appears at the top of the page)
<?php
session_start();
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
(This is the uploading script)
<?php
// Here we run a login check
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
// Run error handling on the file
// Set Max file size limit to somewhere around 120kb
$maxfilesize = 400000;
// Check file size, if too large exit and tell them why
if($_FILES['uploadedfile']['size'] > $maxfilesize ) {
echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// Check file extension to see if it is .jpg or .gif, if not exit and tell them why
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// If no errors on the file process it and upload to server
} else {
// Rename the pic
$newname = ""; //numbers only, so they show up sequentially
// Set the direntory for where to upload it, use the member id to hit their folder
// Upload the file
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "comics/$comicid/".$newname)) {
echo "Success, the image has been uploaded and will display to visitors!<br /><br />
Click here to return to your profile edit area";
exit();
} else {
echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
Click here to return to your profile edit area";
exit();
}
} // close else after file error checks
} // close if post the form
?>
Ideally, I would like to be able to upload an image like this: comics/comic_id/chapter_id/uploaded_file.extension
With the user profile image uploader, I was able to grab the $ID from the $_Session['id'] variable, but with the comics, I don't really know how to grab that information and use it to set the comic_id directory (chapter_id will be selected on the form so I'm not too worried about that one).
Any thoughts?
You can upload a file to wherever you choose. This will save the comic in a folder of its id and chapter, but retaining the filename. If you wanted to use the comic id as the filename I am sure you can work that out.
$basepath = "/home/path/to/www/comics/member_" . $member_id . "/";
function construct_path($chapter_id,$comic_id)
{
$saveimagepath = $basepath . $comic_id . $chapter
}
if (!isset($_SESSION['id'])) {
echo 'Please log in to access your account';
exit();
}
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
// Run error handling on the file
// Set Max file size limit to somewhere around 120kb
$maxfilesize = 400000;
// Check file size, if too large exit and tell them why
if($_FILES['uploadedfile']['size'] > $maxfilesize ) {
echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// Check file extension to see if it is .jpg or .gif, if not exit and tell them why
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
click here to try again";
unlink($_FILES['uploadedfile']['tmp_name']);
exit();
// If no errors on the file process it and upload to server
} else {
// Rename the pic
$newname = $saveimagepath . $_FILES['uploadedfile']['tmp_name'];
//numbers only, so they show up sequentially
// Set the direntory for where to upload it, use the member id to hit their folder
// Upload the file
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $newname)) {
echo "Success, the image has been uploaded and will display to visitors!<br /><br />
Click here to return to your profile edit area";
exit();
} else {
echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
Click here to return to your profile edit area";
exit();
}
} // close else after file error checks
} // close if post the form
?>
The $_SESSION variable is available at any site you started with session_start(). So if the id is set right after the login, you can access this value at any other page in the same way with $_SESSION['id']. Make sure that the value of id won't kill your filesystem or leads to security issues!

Categories